Android Studio Firebase Cloud Messaging Not Working? - firebase

I am developing an e-commerce application in which when user orders places an order, the seller should receive a notification of new order. I am able to send notifications as it shows a toast message of "Response" but no notification is received on the seller part. I checked the code multiple times but I am still unable to find out where I am making the mistake. Here is my code
public class MyFirebaseMessaging extends FirebaseMessagingService {
private static final String NOTIFICATION_CHANNEL_ID = "MY_NOTIFICATION_CHANNEL_ID";
FirebaseAuth firebaseAuth;
FirebaseUser firebaseUser;
#Override
public void onMessageReceived(#NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
String notificationType = remoteMessage.getData().get("notificationType");
if (notificationType.equals("NewOrder")){
String buyerUid = remoteMessage.getData().get("buyerUid");
String sellerUid = remoteMessage.getData().get("sellerUid");
String orderId = remoteMessage.getData().get("orderId");
String notificationTitle = remoteMessage.getData().get("notificationTitle");
String notificationMessage = remoteMessage.getData().get("notificationMessage");
if (firebaseUser != null && firebaseAuth.getUid().equals(sellerUid)){
showNotification(orderId,sellerUid,buyerUid,notificationTitle,notificationMessage,notificationType);
}
}
if (notificationType.equals("OrderStatusChanged")){
String buyerUid = remoteMessage.getData().get("buyerUid");
String sellerUid = remoteMessage.getData().get("sellerUid");
String orderId = remoteMessage.getData().get("orderId");
String notificationTitle = remoteMessage.getData().get("notificationTitle");
String notificationMessage = remoteMessage.getData().get("notificationMessage");
if (firebaseUser != null && firebaseAuth.getUid().equals(buyerUid)){
showNotification(orderId,sellerUid,buyerUid,notificationTitle,notificationMessage,notificationType);
}
}
}
private void showNotification(String orderId,String sellerUid,String buyerUid,String notificationTitle,String notificationDescription,String notificationType){
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int notificationID = new Random().nextInt(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
setUpNotificationChannel(notificationManager);
}
Intent intent = null;
if (notificationType.equals("NewOrder")){
intent = new Intent(this,ShopOrderDetails.class);
intent.putExtra("orderId",orderId);
intent.putExtra("orderBy",buyerUid);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
} else if (notificationType.equals("OrderStatusChanged")){
intent = new Intent(this,UserOrderDetailsActivity.class);
intent.putExtra("orderId",orderId);
intent.putExtra("orderTo",sellerUid);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.drawable.indianflag);
//notification sound
Uri notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.indianflag)
.setLargeIcon(largeIcon)
.setContentTitle(notificationTitle)
.setContentText(notificationDescription)
.setSound(notificationSoundUri)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
//show notification
notificationManager.notify(notificationID,notificationBuilder.build());
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setUpNotificationChannel(NotificationManager notificationManager) {
CharSequence channelName = "Some sample text";
String channelDescription = "Channel Description Here";
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,channelName,NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(channelDescription);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
if (notificationManager != null){
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
private void prepareNotification(String orderId){
String NOTIFICATION_TOPIC = "/topics/"+ Constants.FCM_TOPIC;
String NOTIFICATION_TITLE = "New Order "+orderId;
String NOTIFICATION_MESSAGE = "You have a new order";
String NOTIFICATION_TYPE = "NewOrder";
JSONObject notificationJo = new JSONObject();
JSONObject notificationBodyJo = new JSONObject();
Log.d("userId",mAuth.getUid());
Log.d("shopId",shopId);
Log.d("orderId",orderId);
try{
notificationBodyJo.put("notificationType",NOTIFICATION_TYPE);
notificationBodyJo.put("buyerUid",mAuth.getUid());
notificationBodyJo.put("sellerUid",shopId);
notificationBodyJo.put("orderId",orderId);
notificationBodyJo.put("notificationTitle",NOTIFICATION_TITLE);
notificationBodyJo.put("notificationMessage",NOTIFICATION_MESSAGE);
notificationJo.put("to",NOTIFICATION_TOPIC);
notificationJo.put("data",notificationBodyJo);
}catch (Exception e){
Toast.makeText(ProceedToCheckoutActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
sendFCMNotification(notificationJo,orderId);
}
private void sendFCMNotification(JSONObject notificationJo, String timeStamp1) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", notificationJo, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(ProceedToCheckoutActivity.this, "Response", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ProceedToCheckoutActivity.this,UserOrderDetailsActivity.class);
intent.putExtra("shopID",shopId);
intent.putExtra("orderId",timeStamp1);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error Here",error.toString());
Toast.makeText(ProceedToCheckoutActivity.this, "Error", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ProceedToCheckoutActivity.this,UserOrderDetailsActivity.class);
intent.putExtra("shopID",shopId);
intent.putExtra("orderId",timeStamp1);
startActivity(intent);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
headers.put("Content-Type","application/json");
headers.put("Authorization","key="+Constants.FCM_KEY);
return headers;
}
};
Volley.newRequestQueue(this).add(jsonObjectRequest);
}

Please use retrofit or volley to send notifications to second user.
Link: sending fcm push notifications using retrofit library in android
Module:app dependencies
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
ApiClient
public class ApiClient {
private static final String BASE_URL = "https://fcm.googleapis.com/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiInterface
public interface ApiInterface {
#Headers({"Authorization: key=" + ConstantKey.SERVER_KEY, "Content-Type:application/json"})
#POST("fcm/send")
Call<ResponseBody> sendNotification(#Body RootModel root);
}
RootModel
public class RootModel {
#SerializedName("to") // "to" changed to token
private String token;
#SerializedName("notification")
private NotificationModel notification;
#SerializedName("data")
private DataModel data;
public RootModel(String token, NotificationModel notification, DataModel data) {
this.token = token;
this.notification = notification;
this.data = data;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public NotificationModel getNotification() {
return notification;
}
public void setNotification(NotificationModel notification) {
this.notification = notification;
}
public DataModel getData() {
return data;
}
public void setData(DataModel data) {
this.data = data;
}
}
NotificationModel
public class NotificationModel {
private String title;
private String body;
public NotificationModel(String title, String body) {
this.title = title;
this.body = body;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
DataModel
public class DataModel {
private String name;
private String age;
public DataModel(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Send notification by using this method
private void sendNotificationToUser(String token) {
RootModel rootModel = new RootModel(token, new NotificationModel("Title", "Body"), new DataModel("Name", "30"));
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
retrofit2.Call<ResponseBody> responseBodyCall = apiService.sendNotification(rootModel);
responseBodyCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
Log.d(TAG,"Successfully notification send by using retrofit.");
}
#Override
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
}
});
}

Related

Retrofit Authenticator called but not work

at the first I am sorry for my poor english.
I am developing an android app with nodejs backend.JWT is used for authorization, so I send access token to the server to authorize my request. access token life is short and expire in 60s. for refreshing the access token the app must to send refresh token to server. for this purpose I am using OkHttp authenticator but authenticator is not work. can any body help me to solve this problem
ServiceGenerator
public class ServiceGenerator {
private static final OkHttpClient httpClient =
new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
private static final Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
public static <S> S createServiceWithAuth(Class<S> serviceClass, String accessToken, Context context) {
OkHttpClient newClient = httpClient.newBuilder().addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder = request.newBuilder();
if(!accessToken.isEmpty()){
builder.addHeader("x-auth-token", accessToken);
}
request = builder.build();
return chain.proceed((request));
}
}).authenticator(CustomAuthenticator.getInstance(accessToken, context))
.build();
Retrofit newRetrofit = retrofit.newBuilder().client(newClient).baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
return newRetrofit.create(serviceClass);
}
}
CustomAuthenticator
public class CustomAuthenticator implements Authenticator {
private String accessToken;
private static CustomAuthenticator INSTANCE;
Context context;
private CustomAuthenticator(String accessToken, Context context){
this.accessToken = accessToken;
Hawk.init(context).build();
this.context = context;
}
static synchronized CustomAuthenticator getInstance(String accessToken, Context context){
if(INSTANCE == null){
INSTANCE = new CustomAuthenticator(accessToken, context);
}
return INSTANCE;
}
#Nullable
#Override
public Request authenticate(#Nullable Route route, #NotNull Response response) throws IOException {
if(responseCount(response) >= 2){
return null;
}
ApiClient client = ServiceGenerator.createService(ApiClient.class);
User user = new User();
user.setRefreshToken(Hawk.get("RefreshToken"));
Call<User> refreshAccessTokenCall = client.refresh(user);
retrofit2.Response<User> res = refreshAccessTokenCall.execute();
if(res.isSuccessful()){
assert res.body() != null;
String accessToken = res.body().getAccessToken();
Hawk.put("AccessToken", accessToken);
return response.request().newBuilder().addHeader("x-auth-token", res.body().getAccessToken()).build();
}else{
return null;
}
}
private int responseCount(Response response){
int result = 1;
while ((response = response.priorResponse()) != null){
result++;
}
return result;
}
}
and method that POST data to server (in Fragment)
private void saveExpert() {
if (!validate()) {
return;
}
progressBar.setVisibility(View.VISIBLE);
Objects.requireNonNull(getActivity()).getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
String first_and_last_name = firstAndLastName.getText().toString();
String national_code = nationalCode.getText().toString();
String phone_number = phoneNumber.getText().toString();
String home_office_city = homeOfficeCity.getText().toString();
String _address = address.getText().toString();
String _field = field.getText().toString();
String sub_field = subField.getText().toString();
String _grade = grade.getText().toString();
ApiClient client = ServiceGenerator.createServiceWithAuth(ApiClient.class, Hawk.get("AccessToken"), getContext());
SetExpert setExpert = new SetExpert(first_and_last_name, national_code, phone_number, home_office_city, _address, _field, sub_field, _grade);
Call<Expert> expertCall = client.saveExpert(setExpert);
expertCall.enqueue(new Callback<Expert>() {
#Override
public void onResponse(#NotNull Call<Expert> call, #NotNull Response<Expert> response) {
if (response.isSuccessful()) {
Expert expert = response.body();
if (expert != null) {
Hawk.init(Objects.requireNonNull(getContext())).build();
Hawk.put("ExpertNationalCode", expert.getNational_code());
progressBar.setVisibility(View.GONE);
Objects.requireNonNull(getActivity()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
new MaterialDialog.Builder(Objects.requireNonNull(getContext()))
.typeface("IRANSansWebMedium.ttf", "IRANSansWeb.ttf")
.title("پیام سیستم")
.content(expert.getFirst_and_last_name() + " عزیز با تشکر از ثبت نام شما. این ثبت نام به منزله تایید نهایی نبوده و پس از بررسی مشخصات و مدارک، با شما تماس گرفته خواهد شد.")
.positiveText("تایید.")
.canceledOnTouchOutside(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
dismiss();
}
})
.show();
}
} else {
ApiError apiError = ErrorUtils.parseError(response);
progressBar.setVisibility(View.GONE);
Objects.requireNonNull(getActivity()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(getContext(), apiError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NotNull Call<Expert> call, #NotNull Throwable t) {
progressBar.setVisibility(View.GONE);
Objects.requireNonNull(getActivity()).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
removeHeader("x-auth-token") may solve this.
return response.request().newBuilder()
.removeHeader("x-auth-token") // Remove old header
.addHeader("x-auth-token", res.body().getAccessToken())
.build();
To prevent old "x-auth-token" from being sent, removeHeader() seems to be needed.

Save data from fragment to custom session

I am creating a project in which I am using navigation drawer and on navigation item click it opens a login page and after login it movies to my main activity. Now, I want to save my login details and all data in my custom shared preference from the fragment. After that it on app restarts and I go to navigation login items it should check if the user is already logged in then it should move to an activity otherwise it should run my login fragment
my login fragment
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
CDSMainViewModel =
ViewModelProviders.of(this).get(CDP_MainViewModel.class);
View root = inflater.inflate(R.layout.fragment_cdplogin, container, false);
context = container.getContext();
context = getActivity().getApplicationContext();
session = new Session(context);
if (session.isLoggedIn()) {
Intent itra = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(itra);
getActivity().finish();
}
else{
login_button = root.findViewById(R.id.button_click_login);
edit1 = root.findViewById(R.id.input_username);
edit2 = root.findViewById(R.id.input_password);
layout_1 = root.findViewById(R.id.usnamelayout);
layout_2 = root.findViewById(R.id.password_layout);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
return root;
}
private void Login_data() {
String URL = "http://117.240.196.238:8080/api/cdp/getAuth";
Log.i("response", URL);
StringRequest jsonObjRequest = new StringRequest(
Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response_login", response);
parseData1(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
showServerConnectionError();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("AuthID", name);
params.put("AuthPwd", password);
return params;
}
};
RequestQueue queue = SingletonRequestQueue.getInstance(getActivity().getApplicationContext()).getRequestQueue();
queue.add(jsonObjRequest);
}
private void parseData1(String response){
try {
JSONObject json = new JSONObject(response);
int success = json.getInt("success");
String msg = json.getString("message");
if(success == 1){
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
JSONArray recData = json.getJSONArray("data");
for (int i = 0; i < recData.length(); i++) {
JSONObject c = recData.getJSONObject(i);
String uname = name;
String upass = password;
String emp_id = c.getString("emp_id");
String empname = c.getString("EmpName");
String office = c.getString("OfficeNameFull");
String desig = c.getString("DesignationName");
String mobile = c.getString("EmpMobile");
String office_code = c.getString("OfficeCode");
String OfficeType = c.getString("OfficeType");
String district = c.getString("DistrictCode");
String DistrictName = c.getString("DistrictName");
String designationCode = c.getString("designationCode");
String DesignationName1 = c.getString("DesignationName1");
String DesigShortName = c.getString("DesigShortName");
Log.i("session",district);
//Here my loginsession is not working its not saving my data in my session..
Session.getInstance(getContext()).loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
// String email = SessionManager.getInstance(context).getUserEmail();
// session.loginsession(emp_id,uname,upass,empname,office,desig,mobile,office_code,OfficeType,district,DistrictName,designationCode,DesignationName1,DesigShortName);
Intent its12 = new Intent(getActivity().getApplicationContext(), Verification_Activity.class);
startActivity(its12);
getActivity().overridePendingTransition(R.anim.from_right, R.anim.slide_to_left);
getActivity().finish();
}
} else {
Toast.makeText(context,msg, Toast.LENGTH_LONG).show();
}
}catch(Exception ex){
}
}
}
//Session manager class
package com.example.agridept.domain;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.example.agridept.ui.CDP_login.CDP_MainFragment;
public class Session {
private static Session jInstance;
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
int PRIVATE_MODE = 0;
private static final String IS_LOGIN = "IsLoggedIn";
private static final String PREF_NAME = "AndroidHivePref";
String emp_id1,username1,password1 ,empname1 , office1 , desig1, mobile1, office_code1, OfficeType1 , district1 ,DistrictName1 , designationCode1, DesignationName11 , DesigShortName1;
public Session(Context context){
this.context = context;
preferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = preferences.edit();
}
public void loginsession(String emp_id,String username,String password11 ,String empname ,String office ,String desig,String mobile,String office_code,String OfficeType ,String district ,String DistrictName ,String designationCode,String DesignationName1 ,String DesigShortName){
editor.putBoolean(IS_LOGIN, true);
editor.putString(emp_id1,emp_id);
editor.putString(username1,username);
editor.putString(password1,password11);
editor.putString(empname1,empname);
editor.putString(office1,office);
editor.putString(desig1,desig);
editor.putString(mobile1,mobile);
editor.putString(office_code1,office_code);
editor.putString(OfficeType1,OfficeType);
editor.putString(district1,district);
editor.putString(DistrictName1,DistrictName);
editor.putString(designationCode1,designationCode);
editor.putString(DesignationName11,DesignationName1);
editor.putString(DesigShortName1,DesigShortName);
}
public boolean isLoggedIn() {
return preferences.getBoolean(IS_LOGIN, false);
}
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(context, CDP_MainFragment.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
context.startActivity(i);
}
public void clearinfo() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
}
public SharedPreferences getPreferences() {
return preferences;
}
public void setPreferences(SharedPreferences preferences) {
this.preferences = preferences;
}
public SharedPreferences.Editor getEditor() {
return editor;
}
public void setEditor(SharedPreferences.Editor editor) {
this.editor = editor;
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public int getPRIVATE_MODE() {
return PRIVATE_MODE;
}
public void setPRIVATE_MODE(int PRIVATE_MODE) {
this.PRIVATE_MODE = PRIVATE_MODE;
}
public static String getIsLogin() {
return IS_LOGIN;
}
public static String getPrefName() {
return PREF_NAME;
}
public String getEmp_id1() {
return emp_id1;
}
public void setEmp_id1(String emp_id1) {
this.emp_id1 = emp_id1;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public String getEmpname1() {
return empname1;
}
public void setEmpname1(String empname1) {
this.empname1 = empname1;
}
public String getOffice1() {
return office1;
}
public void setOffice1(String office1) {
this.office1 = office1;
}
public String getDesig1() {
return desig1;
}
public void setDesig1(String desig1) {
this.desig1 = desig1;
}
public String getMobile1() {
return mobile1;
}
public void setMobile1(String mobile1) {
this.mobile1 = mobile1;
}
public String getOffice_code1() {
return office_code1;
}
public void setOffice_code1(String office_code1) {
this.office_code1 = office_code1;
}
public String getOfficeType1() {
return OfficeType1;
}
public void setOfficeType1(String officeType1) {
OfficeType1 = officeType1;
}
public String getDistrict1() {
return district1;
}
public void setDistrict1(String district1) {
this.district1 = district1;
}
public String getDistrictName1() {
return DistrictName1;
}
public void setDistrictName1(String districtName1) {
DistrictName1 = districtName1;
}
public String getDesignationCode1() {
return designationCode1;
}
public void setDesignationCode1(String designationCode1) {
this.designationCode1 = designationCode1;
}
public String getDesignationName11() {
return DesignationName11;
}
public void setDesignationName11(String designationName11) {
DesignationName11 = designationName11;
}
public String getDesigShortName1() {
return DesigShortName1;
}
public void setDesigShortName1(String desigShortName1) {
DesigShortName1 = desigShortName1;
}
public static synchronized Session getInstance(Context context) {
if (jInstance != null) {
return jInstance;
} else {
jInstance = new Session(context);
return jInstance;
}
}
}

Using database on recyclerview

The first activity save some data at the firebase database and i need to show on the second activity using a recyclerview. I'm trying many times and i follow a tutorial, but always the recyclerview isn't displaying anything.
The Firebase was working correctly saving the data, but i can't put at recyclerview.
The activities are:
MenuActivity (recyclerview)
private RecyclerView recyclerView;
private Informações informações;
FirebaseDatabase database;
DatabaseReference myRef;
List<Informações> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Informações");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<Informações>();
for (DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
Informações value = dataSnapshot1.getValue(Informações.class);
Informações informações = new Informações();
String empresa = value.getEmpresa();
String setor = value.getSetor();
String data = value.getData();
informações.setEmpresa(empresa);
informações.setSetor(setor);
informações.setData(data);
list.add(informações);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list, MenuActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MenuActivity.this,2);
recyclerView.setLayoutManager(recyce);
recyclerView.setAdapter(recyclerAdapter);
The RecyclerAdapter
List<Informações> list;
Context context;
public RecyclerAdapter(List<Informações> list, Context context){
this.list = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.adapter_lista,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder( MyViewHolder holder, int position) {
Informações mylist = list.get( position );
holder.empresa.setText(mylist.getEmpresa());
holder.setor.setText(mylist.getSetor());
holder.data.setText(mylist.getData());
}
#Override
public int getItemCount() {
int arr = 0;
try {
if (list.size() == 0)
{ arr = 0;
} else { arr = list.size(); }
} catch (Exception e) {}
return arr;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView empresa, setor, data;
public MyViewHolder(View itemView) {
super(itemView);
empresa = (TextView) itemView.findViewById(R.id.textEmpresa);
setor = (TextView) itemView.findViewById(R.id.textSetor);
data = (TextView) itemView.findViewById(R.id.textData);
}
}
}
And the Firebase
public class Informações {
private String equipe;
private String empresa;
private String setor;
private String responsavel;
private String visita;
private String ferramenta;
private String data;
public Informações() {
}
public void salvar(){
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase();
firebase.child("Informações")
.child( this.empresa )
.setValue( this );
}
public String getVisita() { return visita; }
public void setVisita(String visita) { this.visita = visita; }
public String getFerramenta() { return ferramenta; }
public void setFerramenta(String ferramenta) { this.ferramenta = ferramenta; }
public String getData() { return data; }
public void setData(String data) { this.data = data; }
public String getEquipe() { return equipe; }
public void setEquipe(String equipe) { this.equipe = equipe; }
public String getEmpresa() { return empresa; }
public void setEmpresa(String empresa) { this.empresa = empresa; }
public String getSetor() { return setor; }
public void setSetor(String setor) { this.setor = setor; }
public String getResponsavel() { return responsavel; }
public void setResponsavel(String responsavel) { this.responsavel = responsavel; }
}

Amazon SNS Confirmation Token

I was trying to implement Amazon SNS service to my project. I am able to create a topic and subscribe to a topic as well. Here, I am using sms as a protocol and phone number as endpoint. The main problem is I am not getting any confirmation to my mobile phone number and unable to publish message. How can I get a token to confirmSubscription? //subscriptionRequest.withToken(token);
public class SNSServiceImpl implements SNSService {
private static final Logger logger = LoggerFactory.getLogger(SNSServiceImpl.class);
#Value("${AWS_ACCESS_KEY_ID:key}")
private String awsAccessKeyId;
#Value("${AWS_SECRET_ACCESS_KEY:secret}")
private String awsAccessKeySecret;
#Value("${AWS_REGION:us-west-2}")
private String awsRegion;
private AmazonSNS snsClient;
private String subscriptionArn;
#PostConstruct
public void setConnection() {
AWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKeyId, awsAccessKeySecret);
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
snsClient = AmazonSNSClient.builder()
.withRegion(awsRegion)
.withCredentials(awsCredentialsProvider)
.build();
}
#Override
public String createTopic(String topicName) {
CreateTopicRequest topicRequest = new CreateTopicRequest(topicName);
CreateTopicResult topicResult = snsClient.createTopic(topicRequest);
return topicResult.getTopicArn();
}
#Override
public void subscribeToTopic(String topicArn) {
SubscribeRequest subscribeRequest = new SubscribeRequest();
subscribeRequest.setTopicArn(topicArn);
subscribeRequest.setProtocol("sms");
subscribeRequest.setEndpoint("+14699011920");
SubscribeResult subscribeResult = snsClient.subscribe(subscribeRequest);
subscriptionArn = subscribeResult.getSubscriptionArn();
}
#Override
public void confirmSubscription(String topicArn) {
ConfirmSubscriptionRequest subscriptionRequest = new ConfirmSubscriptionRequest();
subscriptionRequest.withTopicArn(topicArn);
//subscriptionRequest.withToken(token);
ConfirmSubscriptionResult confirmSubscriptionResult = snsClient.confirmSubscription(subscriptionRequest);
confirmSubscriptionResult.withSubscriptionArn(subscriptionArn);
}
#Override
public void publishMessage(String topicArn, String message) {
PublishRequest publishRequest = new PublishRequest(topicArn, message);
PublishResult publishResult = snsClient.publish(publishRequest);
System.out.println(publishResult);
}
}
I just change the publishMessage method and delete the confirmSubscription this method from my service.
#Component
public class SNSServiceImpl implements SNSService {
private static final Logger logger = LoggerFactory.getLogger(SNSServiceImpl.class);
#Value("${AWS_ACCESS_KEY_ID:key}")
private String awsAccessKeyId;
#Value("${AWS_SECRET_ACCESS_KEY:secret}")
private String awsAccessKeySecret;
#Value("${AWS_REGION:us-west-2}")
private String awsRegion;
private AmazonSNS snsClient;
#PostConstruct
public void setConnection() {
AWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKeyId, awsAccessKeySecret);
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
snsClient = AmazonSNSClient.builder()
.withRegion(awsRegion)
.withCredentials(awsCredentialsProvider)
.build();
}
#Override
public String createTopic(String topicName) {
CreateTopicRequest topicRequest = new CreateTopicRequest(topicName);
CreateTopicResult topicResult = snsClient.createTopic(topicRequest);
logger.info("Create topic request: " + snsClient.getCachedResponseMetadata(topicRequest));
logger.info("Create topic result: " + topicResult);
return topicResult.getTopicArn();
}
#Override
public void subscribeSNSToTopic(String topicArn, String phoneNumber) {
String protocol = "sms";
SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, protocol, phoneNumber);
SubscribeResult subscribeResult = snsClient.subscribe(subscribeRequest);
logger.info("Subscribe request: " + snsClient.getCachedResponseMetadata(subscribeRequest));
logger.info("Subscribe result: " + subscribeResult);
}
#Override
public void sendSMSMessageToTopic(String topicArn, String message) {
Map<String, MessageAttributeValue> smsAttributes =
new HashMap<>();
smsAttributes.put("AWS.SNS.SMS.SenderID", new MessageAttributeValue()
.withStringValue("mySenderID") //The sender ID shown on the device.
.withDataType("String"));
smsAttributes.put("AWS.SNS.SMS.MaxPrice", new MessageAttributeValue()
.withStringValue("0.50") //Sets the max price to 0.50 USD.
.withDataType("Number"));
smsAttributes.put("AWS.SNS.SMS.SMSType", new MessageAttributeValue()
.withStringValue("Promotional") //Sets the type to promotional.
.withDataType("String"));
PublishResult publishResult = snsClient.publish(new PublishRequest()
.withTopicArn(topicArn)
.withMessage(message)
.withMessageAttributes(smsAttributes));
logger.info("Public Result: " + publishResult);
}
}

Get the userId (or interact with other users) in Firebase Database

I am building a chat app with Firebase and I am having issues identifying who is who, when a user sends another user a message, he needs to post it to the receivers node and he needs to know his UID to do that. I need to know how to get the receiver's UID, so I can post directly to his own node.
I tried using intent.putExtra and intent.getExtras from my MainActivity which lists out every user from their directories, this is my current code that does not successfully pass the data I need.
public static class PlaceholderFragment extends Fragment {
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public static class UserHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View mView;
public UserHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mView = itemView;
}
public void setName(String name) {
TextView field = (TextView) mView.findViewById(R.id.thename);
field.setText(name);
}
public void setImage(String image){
ImageView pp = (ImageView) mView.findViewById(R.id.imageurl);
try{
Picasso.with(Application.getAppContext()).load(image).placeholder(R.drawable.nodp).error(R.drawable.nodp).transform(new CircleTransform()).into(pp);
}
catch (IllegalArgumentException e){
Picasso.with(Application.getAppContext()).load(R.drawable.nodp).transform(new CircleTransform()).into(pp);
}
}
#Override
public void onClick(View mView) {
//what to do here
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
//private static final String TAG = "UserListActivity";
//final TextView name = (TextView) rootView.findViewById(R.id.lastname) ;
//final ImageView profileImage = (ImageView) rootView.findViewById(R.id.imageView4);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
final DatabaseReference root = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = root.child("users");
RecyclerView recycler = (RecyclerView) rootView.findViewById(R.id.recyclerview3);
recycler.setHasFixedSize(true);
recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
FirebaseRecyclerAdapter mAdapter = new FirebaseRecyclerAdapter<UserList, UserHolder>(UserList.class, R.layout.userlistrow, UserHolder.class, userRef) {
#Override
public void populateViewHolder(UserHolder userViewHolder, final UserList userList, final int position) {
//try catch block to catch events of no posts, it will most likely return a null error, so im catching it, else
//find its exception and catch it
try {
String firstname = userList.getFirstname().toString();
String lastname = userList.getLastname().toString();
firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1); //convert first string to uppercase
lastname = lastname.substring(0, 1).toUpperCase() + lastname.substring(1);// same thing happening here
String name = (firstname + " " + lastname); // concatenate firstname and lastname variable.
userViewHolder.setName(name);
}
catch(NullPointerException e) {
String firstname = "Not";
String lastname = "set";
String name = (firstname + " " + lastname );
userViewHolder.setName(name);
}
catch (StringIndexOutOfBoundsException e) {
String firstname = "No";
String lastname = "name";
String name = (firstname + " " + lastname );
userViewHolder.setName(name);
}
//note that picasso view holder was applied in the view holder instead
//String image = userList.getImgUrl().toString();
//userViewHolder.setImage(image);
//findViewById(R.id.progressBar3).setVisibility(View.GONE);
This is where I am passing the extras, and it doesnt seem to work
userViewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.w(TAG, "You clicked on "+position);
//String firstname = userList.getFirstname();
//String lastname = userList.getLastname();
//firstname = firstname.substring(0, 1).toUpperCase() + firstname.substring(1); //convert first string to uppercase
//lastname = lastname.substring(0, 1).toUpperCase() + lastname.substring(1);// same thing happening here
//String name = (firstname + " " + lastname); // concatenate firstname and lastname variable.
Intent intent = new Intent(getActivity(), Userdetail.class); //change to onclick
intent.putExtra("userId", userList.getUserId());//you can name the keys whatever you like
intent.putExtra("lastname", userList.getLastname().toString());
intent.putExtra("firstname", userList.getFirstname().toString());
intent.putExtra("image", userList.getImgUrl().toString()); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
startActivity(intent);
}
});
}
};
recycler.setAdapter(mAdapter);
return rootView;
}
}
If you need more information, please ask in the comments. Ive googled around but no help
package com.mordred.theschoolapp;
import com.google.firebase.database.IgnoreExtraProperties;
/**
* Created by mordred on 11/28/16.
*/
public class UserList {
public String firstname;
public String lastname;
public String userId;
public String imgUrl;
public UserList() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}

Resources