How to delete messages from firebase Database? - java

I am working on a chat application connected to firebase. I am trying to add a future where I can delete a message. This is what I have tried but it's not working.
This is the code
...package com.sollie.ian.eunice.ui
public class ChatActivity extends AppCompatActivity {
private RecyclerView recyclerChat;
public static final int VIEW_TYPE_USER_MESSAGE = 0;
public static final int VIEW_TYPE_FRIEND_MESSAGE = 1;
private ListMessageAdapter adapter;
public String roomId;
private ArrayList<CharSequence> idFriend;
private Consersation consersation;
private MessageInput editWriteMessage;
private LinearLayoutManager linearLayoutManager;
public static HashMap<String, Bitmap> bitmapAvataFriend;
public Bitmap bitmapAvataUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intentData = getIntent();
idFriend = intentData.getCharSequenceArrayListExtra(StaticConfig.INTENT_KEY_CHAT_ID);
roomId = intentData.getStringExtra(StaticConfig.INTENT_KEY_CHAT_ROOM_ID);
String nameFriend = intentData.getStringExtra(StaticConfig.INTENT_KEY_CHAT_FRIEND);
consersation = new Consersation();
String base64AvataUser = SharedPreferenceHelper.getInstance(this).getUserInfo().avata;
if (!base64AvataUser.equals(StaticConfig.STR_DEFAULT_BASE64)) {
byte[] decodedString = Base64.decode(base64AvataUser, Base64.DEFAULT);
bitmapAvataUser = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
} else {
bitmapAvataUser = null;
}
editWriteMessage = findViewById(R.id.input);
if (idFriend != null && nameFriend != null) {
getSupportActionBar().setTitle(nameFriend);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerChat = findViewById(R.id.recyclerChat);
recyclerChat.setLayoutManager(linearLayoutManager);
adapter = new ListMessageAdapter(this, consersation, bitmapAvataFriend, bitmapAvataUser);
FirebaseDatabase.getInstance().getReference().child("message/" + roomId).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
HashMap mapMessage = (HashMap) dataSnapshot.getValue();
Message newMessage = new Message();
newMessage.idSender = (String) mapMessage.get("idSender");
newMessage.idReceiver = (String) mapMessage.get("idReceiver");
newMessage.text = (String) mapMessage.get("text");
newMessage.timestamp = (long) mapMessage.get("timestamp");
consersation.getListMessageData().add(newMessage);
adapter.notifyDataSetChanged();
linearLayoutManager.scrollToPosition(consersation.getListMessageData().size() - 1);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
recyclerChat.setAdapter(adapter);
}
editWriteMessage.setInputListener(input -> {
String content = input.toString().trim();
if (content.length() > 0) {
// editWriteMessage.setTex("");
Message newMessage = new Message();
newMessage.text = content;
newMessage.idSender = StaticConfig.UID;
newMessage.idReceiver = roomId;
newMessage.timestamp = System.currentTimeMillis();
FirebaseDatabase.getInstance().getReference().child("message/" + roomId).push().setValue(newMessage);
}
return true;
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home){
Intent result = new Intent();
result.putExtra("idFriend", idFriend.get(0));
setResult(RESULT_OK, result);
this.finish();
}
return true;
}
#Override
public void onBackPressed() {
Intent result = new Intent();
result.putExtra("idFriend", idFriend.get(0));
setResult(RESULT_OK, result);
this.finish();
}
}
class ListMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private Consersation consersation;
private HashMap<String, Bitmap> bitmapAvata;
private HashMap<String, DatabaseReference> bitmapAvataDB;
private Bitmap bitmapAvataUser;
private String roomId;
public ListMessageAdapter(Context context, Consersation consersation, HashMap<String, Bitmap> bitmapAvata, Bitmap bitmapAvataUser) {
this.context = context;
this.consersation = consersation;
this.bitmapAvata = bitmapAvata;
this.bitmapAvataUser = bitmapAvataUser;
bitmapAvataDB = new HashMap<>();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ChatActivity.VIEW_TYPE_FRIEND_MESSAGE) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_friend, parent, false);
return new ItemMessageFriendHolder(view);
} else if (viewType == ChatActivity.VIEW_TYPE_USER_MESSAGE) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_message_user, parent, false);
return new ItemMessageUserHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ItemMessageFriendHolder) {
((ItemMessageFriendHolder) holder).txtContent.setText(consersation.getListMessageData().get(position).text);
Bitmap currentAvata = bitmapAvata.get(consersation.getListMessageData().get(position).idSender);
if (currentAvata != null) {
((ItemMessageFriendHolder) holder).avata.setImageBitmap(currentAvata);
} else {
final String id = consersation.getListMessageData().get(position).idSender;
if(bitmapAvataDB.get(id) == null){
bitmapAvataDB.put(id, FirebaseDatabase.getInstance().getReference().child("user/" + id + "/avata"));
bitmapAvataDB.get(id).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
String avataStr = (String) dataSnapshot.getValue();
if(!avataStr.equals(StaticConfig.STR_DEFAULT_BASE64)) {
byte[] decodedString = Base64.decode(avataStr, Base64.DEFAULT);
ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
}else{
ChatActivity.bitmapAvataFriend.put(id, BitmapFactory.decodeResource(context.getResources(), R.drawable.default_avata));
}
notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
} else if (holder instanceof ItemMessageUserHolder) {
((ItemMessageUserHolder) holder).txtContent.setText(consersation.getListMessageData().get(position).text);
if (bitmapAvataUser != null) {
((ItemMessageUserHolder) holder).avata.setImageBitmap(bitmapAvataUser);
}
((ItemMessageUserHolder) holder).txtContent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Delete Message");
builder.setMessage("Are You Sure To Delete This Messgae");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteMsg(position);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
return false;
}
});
}
}
private void deleteMsg(int position) {
final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String msgtimestmp =String.valueOf(consersation.getListMessageData().get(position).timestamp);
String message=consersation.getListMessageData().get(position).text;
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(message)
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemViewType(int position) {
return consersation.getListMessageData().get(position).idSender.equals(StaticConfig.UID) ? ChatActivity.VIEW_TYPE_USER_MESSAGE : ChatActivity.VIEW_TYPE_FRIEND_MESSAGE;
}
#Override
public int getItemCount() {
return consersation.getListMessageData().size();
}
}
class ItemMessageUserHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageUserHolder(View itemView) {
super(itemView);
txtContent = itemView.findViewById(R.id.textContentUser);
avata = itemView.findViewById(R.id.imageView2);
}
}
class ItemMessageFriendHolder extends RecyclerView.ViewHolder {
public TextView txtContent;
public CircleImageView avata;
public ItemMessageFriendHolder(View itemView) {
super(itemView);
txtContent = itemView.findViewById(R.id.textContentFriend);
avata = itemView.findViewById(R.id.imageView3);
}
}
And this is what I have tried
private void deleteMsg(int position) {
final String myuid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String msgtimestmp =String.valueOf(consersation.getListMessageData().get(position).timestamp);
String message=consersation.getListMessageData().get(position).text;
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(message)
.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(context, "deleted", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();
}
}
});
}
What am I doing wrong?

The problem is here:
String message=consersation.getListMessageData().get(position).text;
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(message).removeValue()
You're trying to delete the message based on its text, but to delete a node from Firebase you need to know its key.
This means that when you read the messages from the database, you'll need to store dataSnapshot.getKey() for each message (probably as a field in your Message class). Then when you are ready to delete the message, you can get the key from that class and pass it into the database call, with something like:
String key= consersation.getListMessageData().get(position).key; // 👈
DatabaseReference roofRef=FirebaseDatabase.getInstance().getReference();
roofRef.child("message").child(key).removeValue()... // 👈

Related

How to solve error: class x Binding is public, should be declared in a file named x .java public final class x Binding implements ViewBinding {

When i Try to build then this error will come. Actually i have integrated another app source code in my existing app source code. Error: class ActivitySigUupBinding is public, should be declared in a file named ActivitySignUpBinding.java public final class ActivitySigUupBinding implements ViewBinding
ActivitySignUpBinding.java ⬇️
public final class ActivitySignUpBinding implements ViewBinding {
#NonNull
private final ConstraintLayout rootView;
#NonNull
public final EditText editText;
#NonNull
public final ImageView imageView;
#NonNull
public final EditText password;
#NonNull
public final ProgressBar pb;
#NonNull
public final TextView privacy;
#NonNull
public final Button signUp;
#NonNull
public final TextView terms;
#NonNull
public final TextView textView;
#NonNull
public final TextView textView2;
#NonNull
public final EditText username;
private ActivitySignUpBinding(#NonNull ConstraintLayout rootView, #NonNull EditText
editText,
#NonNull ImageView imageView, #NonNull EditText password, #NonNull ProgressBar pb,
#NonNull TextView privacy, #NonNull Button signUp, #NonNull TextView terms,
#NonNull TextView textView, #NonNull TextView textView2, #NonNull EditText username) {
this.rootView = rootView;
this.editText = editText;
this.imageView = imageView;
this.password = password;
this.pb = pb;
this.privacy = privacy;
this.signUp = signUp;
this.terms = terms;
this.textView = textView;
this.textView2 = textView2;
this.username = username;
}
#Override
#NonNull
public ConstraintLayout getRoot() {
return rootView;
}
#NonNull
public static ActivitySignUpBinding inflate(#NonNull LayoutInflater inflater) {
return inflate(inflater, null, false);
}
#NonNull
public static ActivitySignUpBinding inflate(#NonNull LayoutInflater inflater,
#Nullable ViewGroup parent, boolean attachToParent) {
View root = inflater.inflate(R.layout.activity_sign_up, parent, false);
if (attachToParent) {
parent.addView(root);
}
return bind(root);
}
#NonNull
public static ActivitySignUpBinding bind(#NonNull View rootView) {
// The body of this method is generated in a way you would not otherwise write.
// This is done to optimize the compiled bytecode for size and performance.
int id;
missingId: {
id = R.id.editText;
EditText editText = rootView.findViewById(id);
if (editText == null) {
break missingId;
}
id = R.id.imageView;
ImageView imageView = rootView.findViewById(id);
if (imageView == null) {
break missingId;
}
id = R.id.password;
EditText password = rootView.findViewById(id);
if (password == null) {
break missingId;
}
id = R.id.pb;
ProgressBar pb = rootView.findViewById(id);
if (pb == null) {
break missingId;
}
id = R.id.privacy;
TextView privacy = rootView.findViewById(id);
if (privacy == null) {
break missingId;
}
id = R.id.signUp;
Button signUp = rootView.findViewById(id);
if (signUp == null) {
break missingId;
}
id = R.id.terms;
TextView terms = rootView.findViewById(id);
if (terms == null) {
break missingId;
}
id = R.id.textView;
TextView textView = rootView.findViewById(id);
if (textView == null) {
break missingId;
}
id = R.id.textView2;
TextView textView2 = rootView.findViewById(id);
if (textView2 == null) {
break missingId;
}
id = R.id.username;
EditText username = rootView.findViewById(id);
if (username == null) {
break missingId;
}
return new ActivitySignUpBinding((ConstraintLayout) rootView, editText, imageView,
password,
pb, privacy, signUp, terms, textView, textView2, username);
}
String missingId = rootView.getResources().getResourceName(id);
throw new NullPointerException("Missing required view with ID: ".concat(missingId));
}
}
FrontSignup.java ⬇️
public class FrontSignup extends AppCompatActivity {
ActivitySignupBinding binding;
Activity activity;
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
AlertDialog loadingDialog,alert;
Session session;
boolean check=false;
boolean email_=false;
boolean emailactive= false;
private static final int SELECT_PICTURE = 0;
private Bitmap bitmap;
String filepath,encodedimage;
int type;
Uri image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(Color.TRANSPARENT);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
binding=ActivitySignupBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
activity=FrontSignup.this;
session= new Session(activity);
loadingDialog=Method.loading(activity);
alert=Method.Alerts(activity);
if(Constant.EMAIL_VERIFICATION){
type=2;
}else {
type=5;
}
binding.layoutImg.setOnClickListener(v -> Dexter.withActivity(FrontSignup
.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent i = new Intent(Intent.ACTION_PICK);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {}
#Override
public void onPermissionRationaleShouldBeShown(com.karumi.dexter.listener.PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check());
binding.sendAgain.setOnClickListener(v -> {
funVerifyEmail(binding.email.getText().toString().trim());
});
binding.terms.setOnClickListener(v -> {
Method.launchCustomTabs(activity, Constant.PRIVACY_POLICY_URL);
});
}
void showLoading(){
loadingDialog.show();
}
void dismisLoading(){
if(loadingDialog.isShowing())
loadingDialog.dismiss();
}
private boolean validateData() {
boolean valid= true;
if(TextUtils.isEmpty(binding.username.getText().toString().trim())){
binding.username.setError(getResources().getString(R.string.error_field_required));
valid=false;
}
if(TextUtils.isEmpty(binding.email.getText().toString().trim())){
binding.email.setError(getResources().getString(R.string.error_field_required));
valid=false;
}
else if(!binding.email.getText().toString().trim().matches(emailPattern)){
binding.email.setError(getResources().getString(R.string.error_invalid_email));
valid=false;
}
if(TextUtils.isEmpty(binding.password.getText().toString().trim())){
binding.password.setError(getResources().getString(R.string.error_invalid_password));
valid=false;
}
if(image==null){
showAlert(getString(R.string.please_select_profile_image));
valid=false;
}
return valid;
}
public void Signup(View view) {
if(!Method.isConnected(activity)){
Method.ToastWarning(activity,getString(R.string.no_internet));
}
if(!validateData()){
return;
}else {
if(check){
if(email_){
funOtpVerify(binding.email.getText().toString().trim(),binding.otp.getText().toString().trim());
}else{
reqSignup(binding.username.getText().toString().trim(),binding.email.getText().toString().trim(),binding.password.getText().toString().trim(),5);
}
}else {
reqSignup(binding.username.getText().toString().trim(),binding.email.getText().toString().trim(),binding.password.getText().toString().trim(),type);
}
}
}
private void reqSignup(String name, String email, String password, int types) {
File file = new File(filepath);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part parts = MultipartBody.Part.createFormData("newimage", file.getName(), requestBody);
OSDeviceState device = OneSignal.getDeviceState();
Constant.API_TYPE = "signup";
Constant.P1 = name;
Constant.P2 = email;
Constant.P3 = password;
Constant.P4 = Method.deviceId(activity);
Constant.P5 = device.getUserId();
Constant.P6 = String.valueOf(types);
showLoading();
Call<BonusResponse> call = ApiClient.getClient(activity).create(ApiInterface.class).Signup(parts);
call.enqueue(new Callback<BonusResponse>() {
#Override
public void onResponse(Call<BonusResponse> call, Response<BonusResponse> response) {
dismisLoading();
if(response.isSuccessful() && response.body().getStatus()==201){
check=true;
if(types==5){
session.saveUserData("",email,"","",password,"","","","");
session.setBoolean(session.LOGIN,true);
Method.ToastSuccess(activity,"Account Created!");
Intent intent = new Intent(activity, FrontLogin.class);
overridePendingTransition(R.anim.enter,R.anim.exit);
startActivity(intent);
}else{
binding.loginLayout.setVisibility(View.GONE);
binding.layoutOtp.setVisibility(View.VISIBLE);
funVerifyEmail(email);
}
}else{
Method.ToastError(activity,response.body().getData());
}
}
#Override
public void onFailure(Call<BonusResponse> call, Throwable t) {
dismisLoading();
}
});
}
public void login(View view) {
overridePendingTransition(R.anim.exit,R.anim.enter);
startActivity(new Intent(activity,FrontLogin.class));
}
private void funOtpVerify(String email , String otp) {
if(otp.isEmpty()){
Method.ToastWarning(activity,"Enter Valid Otp");
}else {
showLoading();
Call<BonusResponse> call = ApiClient.getClient(activity).create(ApiInterface.class).Verify_OTP(otp, email);
call.enqueue(new Callback<BonusResponse>() {
#Override
public void onResponse(Call<BonusResponse> call, Response<BonusResponse> response) {
dismisLoading();
if (response.isSuccessful() && response.body().getStatus() == 201) {
reqSignup(binding.username.getText().toString().trim(), binding.email.getText().toString().trim(), binding.password.getText().toString().trim(), 5);
} else {
binding.otp.setText(null);
Method.ToastError(activity, response.body().getData());
}
}
#Override
public void onFailure(Call<BonusResponse> call, Throwable t) {
dismisLoading();
}
});
}
}
private void funVerifyEmail(String email) {
emailactive=true;
showLoading();
Call<BonusResponse> call = ApiClient.getClient(activity).create(ApiInterface.class).VerifyEmail(email);
call.enqueue(new Callback<BonusResponse>() {
#Override
public void onResponse(Call<BonusResponse> call, Response<BonusResponse> response) {
dismisLoading();
if(response.isSuccessful() && response.body().getStatus()==201) {
email_=true;
Method.ToastSuccess(activity,"OTP has been sended To Email");
binding.procced.setText(getString(R.string.verify_otp));
} else {
Method.ToastWarning(activity,response.body().getData());
}
}
#Override
public void onFailure(Call<BonusResponse> call, Throwable t) {
dismisLoading();
Method.ToastWarning(activity,getString(R.string.try_again_later));
}
});
}
public String getRealPathFromURI(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && data != null) {
image = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(image);
bitmap = BitmapFactory.decodeStream(inputStream);
Bitmap.createScaledBitmap(bitmap, 120, 120, false);
binding.image.setImageBitmap(bitmap);
filepath=getRealPathFromURI(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
void showAlert(String msg){
alert.show();
TextView tv =alert.findViewById(R.id.txt);
tv.setText(msg);
alert.findViewById(R.id.close).setOnClickListener(v -> {
alert.dismiss();
});
}
#Override
public void onBackPressed() {
if(emailactive){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.txt_exit));
builder.setMessage(getString(R.string.txt_confirm_exit));
builder.setPositiveButton(getString(R.string.txt_yes), (dialog, which) -> {
overridePendingTransition(R.anim.exit,R.anim.enter);
finish();
});
builder.setNegativeButton(getString(R.string.txt_no), (dialog, which) -> {
dialog.dismiss();
});
AlertDialog alert = builder.create();
alert.show();
}
super.onBackPressed();
}
}
Error ⬇️

Debug error :java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.List [duplicate]

This question already has answers here:
Explanation of ClassCastException in Java
(12 answers)
Closed 1 year ago.
Every time I click on a profile in my application, it causes this crash and error and I wanted to know why and try to find it.
The error:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.List
at com.example.soulforge.fragments.Profile.lambda$loadBasicData$4$Profile(Profile.java:274)
at com.example.soulforge.fragments.-$$Lambda$Profile$KwoPqF2dchhRaWfrPFWRwwexTfQ.onEvent(Unknown Source:4)
at com.google.firebase.firestore.DocumentReference.lambda$addSnapshotListenerInternal$2(DocumentReference.java:504)
at com.google.firebase.firestore.DocumentReference$$Lambda$3.onEvent(Unknown Source:6)
at com.google.firebase.firestore.core.AsyncEventListener.lambda$onEvent$0(AsyncEventListener.java:42)
at com.google.firebase.firestore.core.AsyncEventListener$$Lambda$1.run(Unknown Source:6)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
The part of the profile that causes the issue
followersList = (List<Object>) value.get("followers");
followingList = (List<Object>) value.get("following");
and the whole profile.java
public class Profile extends Fragment {
boolean isMyProfile = true;
String uid;
String userUID;
FirestoreRecyclerAdapter<PostImageModel, PostImageHolder> adapter;
private TextView nameTv, toolbarNameTv, statusTv, followingCountTv, followersCountTv, postCountTv;
private CircleImageView profileImage;
private Button followBtn;
private RecyclerView recyclerView;
private LinearLayout countLayout;
private FirebaseUser user;
private ImageButton editProfileBtn;
List<Object> followersList, followingList, followingList_2;
boolean isFollowed;
DocumentReference userRef, myRef;
public Profile() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_profile, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
myRef = FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid());
if (IS_SEARCHED_USER) {
isMyProfile = false;
userUID = USER_ID;
loadData();
} else {
isMyProfile = true;
userUID = user.getUid();
}
if (isMyProfile) {
editProfileBtn.setVisibility(View.VISIBLE);
followBtn.setVisibility(View.GONE);
countLayout.setVisibility(View.VISIBLE);
} else {
editProfileBtn.setVisibility(View.GONE);
followBtn.setVisibility(View.VISIBLE);
countLayout.setVisibility(View.GONE);
}
userRef = FirebaseFirestore.getInstance().collection("Users")
.document(userUID);
loadBasicData();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
loadPostImages();
recyclerView.setAdapter(adapter);
clickListener();
}
private void loadData() {
myRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.e("Tag_b", error.getMessage());
return;
}
if (value == null || !value.exists()) {
return;
}
followingList_2 = (List<Object>) value.get("Following");
}
});
}
private void clickListener() {
followBtn.setOnClickListener(v -> {
if (isFollowed) {
followersList.remove(user.getUid());
followingList_2.remove(userUID);
final Map<String, Object> map_2 = new HashMap<>();
map_2.put("following", followingList_2);
Map<String, Object> map = new HashMap<>();
map.put("followers", followersList);
userRef.update(map).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
followBtn.setText("Follow");
myRef.update(map_2).addOnCompleteListener(task1 -> {
if (task1.isSuccessful()) {
Toast.makeText(getContext(), "UnFollowed", Toast.LENGTH_SHORT).show();
} else {
Log.e("Tag_3", task1.getException().getMessage());
}
});
} else {
Log.e("Tag", "" + task.getException().getMessage());
}
});
} else {
followersList.add(user.getUid());
followingList_2.add(userUID);
Map<String, Object> map_2 = new HashMap<>();
map_2.put("following", followingList_2);
Map<String, Object> map = new HashMap<>();
map.put("followers", followersList);
userRef.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
followBtn.setText("UnFollow");
myRef.update(map_2).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Followed", Toast.LENGTH_SHORT).show();
} else {
Log.e("Tag", " " + task.getException().getMessage());
}
}
});
} else {
Log.e("Tag", "" + task.getException().getMessage());
}
}
});
}
});
editProfileBtn.setOnClickListener(v -> {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(requireContext(), Profile.this);
});
}
private void init(View view) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
assert getActivity() != null;
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
nameTv = view.findViewById(R.id.nameTv);
toolbarNameTv = view.findViewById(R.id.toolbarNameTV);
statusTv = view.findViewById(R.id.statusTv);
followersCountTv = view.findViewById(R.id.followersCountTv);
followingCountTv = view.findViewById(R.id.followingCountTv);
postCountTv = view.findViewById(R.id.postCountTv);
profileImage = view.findViewById(R.id.profileImage);
followBtn = view.findViewById(R.id.followBtn);
recyclerView = view.findViewById(R.id.recyclerView);
countLayout = view.findViewById(R.id.countLayout);
editProfileBtn = view.findViewById(R.id.edit_profileImage);
FirebaseAuth auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
}
private void loadBasicData() {
userRef.addSnapshotListener((value, error) -> {
if (error != null) {
Log.e("Tag_0", error.getMessage());
return;
}
assert value != null;
if (value.exists()) {
String name = value.getString("name");
String status = value.getString("status");
String profileURL = value.getString("profileImage");
nameTv.setText(name);
toolbarNameTv.setText(name);
statusTv.setText(status);
followersList = (List<Object>) value.get("followers");
followingList = (List<Object>) value.get("following");
followersCountTv.setText("" + followersList.size());
followingCountTv.setText("" + followingList.size());
try {
Glide.with(getContext().getApplicationContext())
.load(profileURL)
.placeholder(R.drawable.ic_person)
.timeout(6500)
.into(profileImage);
} catch (Exception e) {
e.printStackTrace();
}
if (followingList.contains(userUID)) {
followBtn.setText("UnFollow");
isFollowed = true;
} else {
isFollowed = false;
followBtn.setText("Follow");
}
}
});
postCountTv.setText("" + LIST_SIZE);
}
private void loadPostImages() {
DocumentReference reference = FirebaseFirestore.getInstance().collection("Users").document(userUID);
Query query = reference.collection("Post Images");
FirestoreRecyclerOptions<PostImageModel> options = new FirestoreRecyclerOptions.Builder<PostImageModel>()
.setQuery(query, PostImageModel.class)
.build();
adapter = new FirestoreRecyclerAdapter<PostImageModel, PostImageHolder>(options) {
#NonNull
#Override
public PostImageHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.profile_image_items, parent, false);
return new PostImageHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull PostImageHolder holder, int position, #NonNull PostImageModel model) {
Glide.with(holder.itemView.getContext().getApplicationContext())
.load(model.getImageUrl())
.timeout(6500)
.into(holder.imageView);
}
};
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri uri = result.getUri();
uploadImage(uri);
}
}
private void uploadImage(Uri uri) {
StorageReference reference = FirebaseStorage.getInstance().getReference().child("Profile Images");
reference.putFile(uri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String imageURL = uri.toString();
UserProfileChangeRequest.Builder request = new UserProfileChangeRequest.Builder();
request.setPhotoUri(uri);
user.updateProfile(request.build());
Map<String, Object> map = new HashMap<>();
map.put("profileImage", imageURL);
map.put("date", FieldValue.serverTimestamp());
FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid())
.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
Toast.makeText(getContext(), "Updated Successfully", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext(), "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
} else {
Toast.makeText(getContext(), "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private static class PostImageHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
public PostImageHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
Why is this happening ,and why is it a Long instead of being a list and causing all this issues?
The problem is that the data is of Long class and you are trying to cast it to List
What you should try is
Map<String, Object> followerMap= new HashMap<>();
followerMap= value.getData();
assert followerMap!= null;
for (Map.Entry<String, Object> e : followerMap.entrySet()) {
long following= e.getValue();
followingList_2 .add(following);
}

AppWidget is frozen before message has been sent or recieved. How to initiate the intent before messages are sent?

So appwidget is fixed after some help on here but before any message has been sent or received the intent to launch the ChatRoomActivity doesn't work.
How could I set it up so it's intent launches the activity before any message has been sent/received(obviously it would have no message but it has a textView saying click to open chat..etc).
my code:
public class ProTalkWidget extends AppWidgetProvider {
private static final String ACTION_BROADCASTWIIDGET = "ACTION_BROADCASTWIIDGET";
public static final String PROTALK_APPWIDGET_UPDATE = "PROTALK_APPWIDGET_UPDATE";
private final int REQUEST_CODE = 0;
public static final String USER_ID = "userId";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String msgReceiverId;
private void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
final int appWidgetId) {
//Construct the RemoteViews object
final RemoteViews views;
views = new RemoteViews(context.getPackageName(), R.layout.pro_talk_widget);
Intent intent = new Intent(context, ProTalkWidget.class);
intent.setAction(ACTION_BROADCASTWIIDGET);
context.sendBroadcast(intent);
appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(PROTALK_APPWIDGET_UPDATE.equals(intent.getAction())){
Log.i("onReceive", "getting onReceived!");
handleMsg(intent, context);
}
}
private void handleMsg(final Intent intent, final Context ctx){
msgReceiverId = intent.getStringExtra("receiverId");
if(msgReceiverId!=null) {
String my_Id = mAuth.getCurrentUser().getUid();
final RemoteViews views;
views = new RemoteViews(ctx.getPackageName(), R.layout.pro_talk_widget);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Messages").child(my_Id).child(msgReceiverId).limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Messages messages = ds.getValue(Messages.class);
String message = messages.getMessage();
String from = messages.getFrom();
Log.d("TAG", message + "+" + from);
views.setTextViewText(R.id.appwidget_message, message);
Intent mainIntent = new Intent(ctx, ChatRoomActivity.class);
if(msgReceiverId != null)
mainIntent.putExtra("profile_view_userId", msgReceiverId);
mainIntent.putExtra("username", "Ben");
PendingIntent mainPendingIntent = PendingIntent.getActivity(ctx, REQUEST_CODE, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_layout, mainPendingIntent);
AppWidgetManager.getInstance(ctx).updateAppWidget(new ComponentName(ctx, ProTalkWidget.class), views);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
Please note intent and displaying message works after chatroomactivity has been opened and message sent.
ChatroomActivity
public class ChatRoomActivity extends AppCompatActivity {
private static final String TAG = ChatRoomActivity.class.getSimpleName();
private static final int IMAGE_PICK = 1;
private String msgReceiverId;
private String msgReceiverName;
private static final int TOTAL_ITEMS = 10;
private int currentPage = 1;
private TextView chatUserName;
private TextView chatLastSeen;
private CircleImageView chatProfileImg;
private DatabaseReference rootRef;
private ImageView sendMsgBtn;
private EditText textInputET;
private RecyclerView usersMsgList;
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
//private TabsPagerAdapter.MessagesAdapter messagesAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private int ITEM_POSITION = 0;
private String lastKey;
private String prevKey;
private StorageReference imgStorage;
FirebaseAuth mAuth;
String msgSenderId;
Toolbar appBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES){
setTheme(R.style.darkTheme);
}else{
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_chat_room);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
msgSenderId = mAuth.getCurrentUser().getUid();
msgReceiverId = getIntent().getExtras().getString("profile_view_userId");
msgReceiverName = getIntent().getExtras().getString("username");
sendMsgBtn = findViewById(R.id.input_text_btn);
textInputET = findViewById(R.id.input_text);
ProTalkApplication.getInstance().messagesAdapter = new TabsPagerAdapter.MessagesAdapter(messagesList);
usersMsgList = findViewById(R.id.users_messages_list);
linearLayoutManager = new LinearLayoutManager(this);
usersMsgList.setHasFixedSize(true);
usersMsgList.setLayoutManager(linearLayoutManager);
usersMsgList.setAdapter(ProTalkApplication.getInstance().messagesAdapter);
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
imgStorage = FirebaseStorage.getInstance().getReference();
fetchMsg();
Intent widgetIntent = new Intent(this,ProTalkWidget.class);
//send value
widgetIntent.putExtra("receiverID", msgReceiverName);
sendBroadcast(widgetIntent);
appBar = findViewById(R.id.chat_appbar);
setSupportActionBar(appBar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View actionBarView = inflater.inflate(R.layout.chat_bar, null);
actionBar.setCustomView(actionBarView);
chatUserName = findViewById(R.id.chat_profile_name);
chatLastSeen = findViewById(R.id.chat_last_seen);
chatProfileImg = findViewById(R.id.chat_profile_img);
chatUserName.setText(msgReceiverName);
sendMsgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMsg();
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
currentPage++;
ITEM_POSITION = 0;
fetchMoreMsg();
}
});
rootRef.child("User").child(msgReceiverId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("online").getValue().toString().trim();
final String userImg = dataSnapshot.child("thumbnail").getValue().toString();
if (online.equals("true")) {
chatLastSeen.setText(R.string.online);
} else {
GetTimeAgo getTime = new GetTimeAgo();
long lastSeen = Long.parseLong(online);
String lastOnline = getTime.getTimeAgo(lastSeen, getApplicationContext());
//
chatLastSeen.setText(lastOnline);
}
Picasso.get().load(userImg).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.defaultimg).into(chatProfileImg, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(userImg)
.placeholder(R.drawable.defaultimg).into(chatProfileImg);
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void fetchMoreMsg() {
DatabaseReference msgRef = rootRef.child("Messages").child(msgSenderId).child(msgReceiverId);
Query msgQuery = msgRef.orderByKey().endAt(lastKey).limitToLast(10);
msgQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if (!prevKey.equals(messageKey)) {
messagesList.add(ITEM_POSITION++, messages);
} else {
prevKey = lastKey;
}
if (ITEM_POSITION == 1) {
lastKey = messageKey;
}
ProTalkApplication.getInstance().messagesAdapter.notifyDataSetChanged();
linearLayoutManager.scrollToPositionWithOffset(10, 0);
swipeRefreshLayout.setRefreshing(false);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void fetchMsg() {
DatabaseReference msgRef = rootRef.child("Messages").child(msgSenderId).child(msgReceiverId);
Query msgQuery = msgRef.limitToLast(currentPage * TOTAL_ITEMS);
msgQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
ITEM_POSITION++;
if (ITEM_POSITION == 1) {
lastKey = messageKey;
prevKey = messageKey;
}
messagesList.add(messages);
ProTalkApplication.getInstance().messagesAdapter.notifyDataSetChanged();
usersMsgList.scrollToPosition(messagesList.size() - 1);
swipeRefreshLayout.setRefreshing(false);
Intent intent = new Intent(ChatRoomActivity.this, ProTalkWidget.class);
intent.setAction(ProTalkWidget.PROTALK_APPWIDGET_UPDATE);
intent.putExtra("senderId", msgSenderId);
intent.putExtra("receiverId", msgReceiverId);
sendBroadcast(intent);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendMsg() {
String msgTxt = textInputET.getText().toString();
if (TextUtils.isEmpty(msgTxt)) {
Toast.makeText(ChatRoomActivity.this, R.string.please_write_a_msg, Toast.LENGTH_SHORT).show();
} else {
String sender_message_ref = "/Messages/" + msgReceiverId + "/" + msgSenderId;
String receiver_message_ref = "/Messages/" + msgSenderId + "/" + msgReceiverId;
DatabaseReference userMsgKey = rootRef.child("Messages").child(msgReceiverId)
.child(msgSenderId).push();
String push_id = userMsgKey.getKey();
Map msgTxtBody = new HashMap();
msgTxtBody.put("message", msgTxt);
msgTxtBody.put("from", msgSenderId);
msgTxtBody.put("seen", false);
msgTxtBody.put("type", "text");
msgTxtBody.put("time", ServerValue.TIMESTAMP);
Map msgBodyDetails = new HashMap();
msgBodyDetails.put(sender_message_ref + "/" + push_id, msgTxtBody);
msgBodyDetails.put(receiver_message_ref + "/" + push_id, msgTxtBody);
rootRef.updateChildren(msgBodyDetails, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d(TAG, databaseError.getMessage().toString());
}
textInputET.setText("");
}
});
}
}
}
Thanks Again!!!

Show error note if image not selected android

This is my full code below. am coding an android app that can select image from gallery or any where and upload it to Mysql server through php but if image is not selected and the upload button is press the application crashes so i want to implement the function that it shows error dialog / warning dialog if image is not selected from gallery have already implemented it in EditText but cannot implement it in Image. below is my code
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}
Just copy this code and paste
package com.app.markeet;
public class ActivityPost extends AppCompatActivity implements View.OnClickListener {
private Button buttonUpload;
private Button buttonChoose;
EditText editTitle, editTextPrice, editTextDescription, editTextStatus, editTextAuthorsname, editTextAuthorsphone;
private ImageView imageView,choiceItemImg,choiceItemImg2,choiceItemImg3,choiceItemImg4;
public static final String KEY_TITLE = "name";
public static final String KEY_IMAGE = "image";
public static final String KEY_PRICE = "price";
public static final String KEY_DESCRIPTION = "description";
public static final String KEY_STOCK = "stock";
public static final String KEY_AUTHORSNAME = "authorsname";
public static final String KEY_AUTHORSPHONE = "authorsphone";
public static final String KEY_STATUS = "status";
public static final String UPLOAD_URL = "http://192.168.0.199/config/upload.php";
private int PICK_IMAGE_REQUEST = 1;
public static final int CREATE_POST_IMG = 5;
private Bitmap bitmap;
private Uri outputFileUri;
public static final int SELECT_POST_IMG = 3;
public static final String APP_TEMP_FOLDER = "kobobay";
String[] categories = { "Animals and Pets", "Electronics and Video",
"Fashion and Beauty", "Home, Furniture and Garden", "Mobile Phone and Tablets", "PC, Laptop and Accessories",
"Jobs and Services", "Real Estate and Roommate", "Hobbles, Art and Sport", "Books and Tutorial",
"Vehicles", "Other"};
int[] catevalue = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Spinner spinner1;
TextView textView1;
private Toolbar toolbar;
private ActionBar actionBar;
private String selectedPostImg = "";
ImageView mChoiceItemImg, mLocationDelete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle("");
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
editTitle = (EditText)findViewById(R.id.editTitle);
editTextPrice = (EditText)findViewById(R.id.editPrice);
editTextDescription = (EditText)findViewById(R.id.editDescription);
editTextStatus = (EditText)findViewById(R.id.editStatus);
editTextAuthorsname = (EditText)findViewById(R.id.editName);
editTextAuthorsphone = (EditText)findViewById(R.id.editPhone);
imageView = (ImageView) findViewById(R.id.imageView);
textView1 = (TextView)findViewById(R.id.text1);
spinner1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter1 =
new ArrayAdapter<String>(ActivityPost.this,
android.R.layout.simple_spinner_item, categories);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(onItemSelectedListener1);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
choiceItemImg = (ImageView) findViewById(R.id.choiceItemImg);
choiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
mChoiceItemImg = (ImageView) findViewById(R.id.choiceItemImg2);
mChoiceItemImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (selectedPostImg.length() == 0) {
imageFromGallery();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ActivityPost.this);
alertDialog.setTitle(getText(R.string.action_remove));
alertDialog.setMessage(getText(R.string.label_delete_img));
alertDialog.setCancelable(true);
alertDialog.setNeutralButton(getText(R.string.action_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton(getText(R.string.action_remove), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
mChoiceItemImg.setImageResource(R.drawable.ic_camera);
selectedPostImg = "";
dialog.cancel();
}
});
alertDialog.show();
}
}
});
String URL = Constant.WEB_URL + "get/user_info.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse= new JSONObject(response);
//txtName.setText(jsonResponse.getString("fullname"));
editTextAuthorsname.setText(jsonResponse.getString("login"));
//txtEmail.setText(jsonResponse.getString("email"));
editTextAuthorsphone.setText(jsonResponse.getString("phone"));// you need to create this textView txtPoints.
} catch (Throwable t) {
Log.e("onResponse", "The response: " + response + " seems to not be json formatted.");
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityPost.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username",ThisApplication.getInstance().getUsername());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
AdapterView.OnItemSelectedListener onItemSelectedListener1 =
new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String s1 = String.valueOf(catevalue[position]);
textView1.setText(s1);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
};
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public void imageFromGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getText(R.string.label_select_img)), SELECT_POST_IMG);
}
public void imageFromCamera() {
try {
File root = new File(Environment.getExternalStorageDirectory(), APP_TEMP_FOLDER);
if (!root.exists()) {
root.mkdirs();
}
File sdImageMainDirectory = new File(root, "post.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CREATE_POST_IMG);
} catch (Exception e) {
Toast.makeText(ActivityPost.this, "Error occured. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCode == SELECT_POST_IMG && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
choiceItemImg2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage(){
final String GetAuthorsname = editTextAuthorsname.getText().toString();
final String GetAuthorsphone = editTextAuthorsphone.getText().toString();
final String GetTitle = editTitle.getText().toString().trim();
final String image = getStringImage(bitmap);
final String GetPrice = editTextPrice.getText().toString();
final String GetStock = textView1.getText().toString();
final String GetDescription = editTextDescription.getText().toString();
final String GetStatus = editTextStatus.getText().toString();
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityPost.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(ActivityPost.this,s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
HashMap<String,String> param = new HashMap<String,String>();
param.put(KEY_TITLE,GetTitle);
param.put(KEY_IMAGE,image);
param.put(KEY_PRICE,GetPrice);
param.put(KEY_STOCK,GetStock);
param.put(KEY_DESCRIPTION,GetDescription);
param.put(KEY_STATUS,GetStatus);
param.put(KEY_AUTHORSNAME,GetAuthorsname);
param.put(KEY_AUTHORSPHONE,GetAuthorsphone);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
}
}
UploadImage u = new UploadImage();
u.execute();
}
public Boolean checkPicture() {
String image = getStringImage(bitmap);
String GetPrice = editTextPrice.getText().toString();
String GetDescription = editTextDescription.getText().toString();
String GetStatus = editTextStatus.getText().toString();
editTitle.setError(null);
editTextPrice.setError(null);
editTextDescription.setError(null);
editTextStatus.setError(null);
if (image.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
} if (GetPrice.length() == 0) {
editTextPrice.setError(getString(R.string.error_field_empty));
return false;
} if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
} if (GetStatus.length() == 0) {
editTextStatus.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkDesc() {
String GetDescription = editTextDescription.getText().toString();
editTextDescription.setError(null);
if (GetDescription.length() == 0) {
editTextDescription.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkProductName() {
String GetTitle = editTitle.getText().toString();
editTitle.setError(null);
if (GetTitle.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
public Boolean checkCategory() {
String GetStock = textView1.getText().toString();
textView1.setError(null);
if (GetStock.length() == 0) {
editTitle.setError(getString(R.string.error_field_empty));
return false;
}
return true;
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
//imageFromGallery();
}
if(v == buttonUpload){
// checkUsername();
if (!ThisApplication.getInstance().isConnected()) {
Toast.makeText(getApplicationContext(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else if (!checkProductName() || !checkDesc() || !checkCategory()) {
} else {
uploadImage();
}
}
}
#Override
public void onBackPressed(){
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_new_item, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sync:
Intent intent = getIntent();
finish();
startActivity(intent);
return true;
case R.id.action_post:
uploadImage();
default:
return super.onOptionsItemSelected(item);
}
}
}

Working with Sinch Instant Messaging System

I am using Sinch and Parse for my instant messaging system integrated in our application, and I have two concerns.
1) For some reason, I am receiving the following error when the messaging activity is displayed: The message client did not start". Furthermore, the message does not seem to go through in Sinch and not reflected visually in the application.
Below is the activity code (when the user clicks on the "quick chat" button, it takes them to the messaging activity page.
Below is the activity code for the messaging activity
public class MessagingActivity extends Activity implements ServiceConnection, MessageClientListener {
private String recipientId;
private Button sendButton;
private EditText messageBodyField;
private String messageBody;
private MessageService.MessageServiceInterface messageService;
private MessageAdapter messageAdapter;
private ListView messagesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging);
doBind();
messagesList = (ListView) findViewById(R.id.listMessages);
messageAdapter = new MessageAdapter(this);
messagesList.setAdapter(messageAdapter);
Intent intent = getIntent();
recipientId = intent.getStringExtra("Name");
messageBodyField = (EditText) findViewById(R.id.messageBodyField);
sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
private void sendMessage() {
messageBodyField = (EditText) findViewById(R.id.messageBodyField);
messageBody = messageBodyField.getText().toString();
if (messageBody.isEmpty()) {
Toast.makeText(this, "Please enter a message", Toast.LENGTH_LONG).show();
return;
}
//Here is where you will actually send the message throught Sinch
messageService.sendMessage(recipientId, messageBody);
messageBodyField.setText("");
}
private void doBind() {
Intent serviceIntent = new Intent(this, MessageService.class);
bindService(serviceIntent, this, BIND_AUTO_CREATE);
}
#Override
public void onDestroy() {
unbindService(this);
super.onDestroy();
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//Define the messaging service and add a listener
messageService = (MessageService.MessageServiceInterface) iBinder;
messageService.addMessageClientListener(this);
if (!messageService.isSinchClientStarted()) {
Toast.makeText(this, "The message client did not start."
,Toast.LENGTH_LONG).show();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
messageService = null;
}
#Override
public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {
//Intentionally left blank
}
#Override
public void onMessageFailed(MessageClient client, Message message,
MessageFailureInfo failureInfo) {
//Notify the user if message fails to send
Toast.makeText(this, "Message failed to send.", Toast.LENGTH_LONG).show();
}
#Override
public void onIncomingMessage(MessageClient client, Message message) {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_INCOMING);
}
#Override
public void onMessageSent(MessageClient client, Message message, String recipientId) {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_OUTGOING);
}
#Override
public void onShouldSendPushData(MessageClient client, Message message, List<PushPair> pushPairs) {
//Intentionally left blank
}
}
I have verified that the APP_KEY, the APP_SECRET and ENVIRONMENT matches what was recorded on Sinch.
I have tried this both on the emulator, and on a physical device.
Thanks in advance
Code service
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "XXXXX";
private static final String APP_SECRET = "YYYYY";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
currentUserId = ParseUser.getCurrentUser().getObjectId().toString();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
return super.onStartCommand(intent, flags, startId);
}
public void startSinchClient(String username) {
sinchClient = Sinch.getSinchClientBuilder().context(this).userId(username).applicationKey(APP_KEY)
.applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT).build();
sinchClient.addSinchClientListener(this);
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
#Override
public void onClientFailed(SinchClient client, SinchError error) {
sinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
}
#Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
public void stop() {
if (isSinchClientStarted()) {
sinchClient.stop();
sinchClient.removeSinchClientListener(this);
}
sinchClient = null;
}
#Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
#Override
public void onLogMessage(int level, String area, String message) {
//Intentionally left blank
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {
//Intentionally left blank
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
public boolean isSinchClientStarted() {
return MessageService.this.isSinchClientStarted();
}
}
}
2) Limit: I would like to set a limit, where a only 25 messages would be available between a particular party.
Thanks in advance, and if you need any clarification, let me know.
Update 3
When user clicks on this button, he is taking to the MessagingActivity with the person he has been matched to based upon the below criteria
final Button ibutton = (Button) this.findViewById(R.id.btnQuickChat);
idrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
openConversation();
}
private void openConversation() {
// TODO Auto-generated method stub
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", ParseUser.getCurrentUser()
.getObjectId());
query.setLimit(1);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
});
MessagingActivity (nearly same as one provided in tutorial):
public class MessagingActivity extends Activity {
private String recipientId;
private EditText messageBodyField;
private String messageBody;
private MessageService.MessageServiceInterface messageService;
private MessageAdapter messageAdapter;
private ListView messagesList;
private String currentUserId;
private ServiceConnection serviceConnection = new MyServiceConnection();
private MessageClientListener messageClientListener = new MyMessageClientListener();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging);
bindService(new Intent(this, MessageService.class), serviceConnection, BIND_AUTO_CREATE);
Intent intent = getIntent();
recipientId = intent.getStringExtra("RECIPIENT_ID");
currentUserId = ParseUser.getCurrentUser().getObjectId();
messagesList = (ListView) findViewById(R.id.listMessages);
messageAdapter = new MessageAdapter(this);
messagesList.setAdapter(messageAdapter);
populateMessageHistory();
messageBodyField = (EditText) findViewById(R.id.messageBodyField);
findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
//get previous messages from parse & display
private void populateMessageHistory() {
String[] userIds = {currentUserId, recipientId};
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereContainedIn("senderId", Arrays.asList(userIds));
query.whereContainedIn("recipientId", Arrays.asList(userIds));
query.orderByAscending("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
for (int i = 0; i < messageList.size(); i++) {
WritableMessage message = new WritableMessage(messageList.get(i).get("recipientId").toString(), messageList.get(i).get("messageText").toString());
if (messageList.get(i).get("senderId").toString().equals(currentUserId)) {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_OUTGOING);
} else {
messageAdapter.addMessage(message, MessageAdapter.DIRECTION_INCOMING);
}
}
}
}
});
}
private void sendMessage() {
messageBody = messageBodyField.getText().toString();
if (messageBody.isEmpty()) {
Toast.makeText(this, "Please enter a message", Toast.LENGTH_LONG).show();
return;
}
messageService.sendMessage(recipientId, messageBody);
messageBodyField.setText("");
}
#Override
public void onDestroy() {
messageService.removeMessageClientListener(messageClientListener);
unbindService(serviceConnection);
super.onDestroy();
}
private class MyServiceConnection implements ServiceConnection {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
messageService = (MessageService.MessageServiceInterface) iBinder;
messageService.addMessageClientListener(messageClientListener);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
messageService = null;
}
}
private class MyMessageClientListener implements MessageClientListener {
#Override
public void onMessageFailed(MessageClient client, Message message,
MessageFailureInfo failureInfo) {
Toast.makeText(MessagingActivity.this, "Message failed to send.", Toast.LENGTH_LONG).show();
}
#Override
public void onIncomingMessage(MessageClient client, Message message) {
if (message.getSenderId().equals(recipientId)) {
WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_INCOMING);
}
}
#Override
public void onMessageSent(MessageClient client, Message message, String recipientId) {
final WritableMessage writableMessage = new WritableMessage(message.getRecipientIds().get(0), message.getTextBody());
//only add message to parse database if it doesn't already exist there
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereEqualTo("sinchId", message.getMessageId());
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> messageList, com.parse.ParseException e) {
if (e == null) {
if (messageList.size() == 0) {
ParseObject parseMessage = new ParseObject("ParseMessage");
parseMessage.put("senderId", currentUserId);
parseMessage.put("recipientId", writableMessage.getRecipientIds().get(0));
parseMessage.put("messageText", writableMessage.getTextBody());
parseMessage.put("sinchId", writableMessage.getMessageId());
parseMessage.saveInBackground();
messageAdapter.addMessage(writableMessage, MessageAdapter.DIRECTION_OUTGOING);
}
}
}
});
}
#Override
public void onMessageDelivered(MessageClient client, MessageDeliveryInfo deliveryInfo) {}
#Override
public void onShouldSendPushData(MessageClient client, Message message, List<PushPair> pushPairs) {}
}
}
MessageService activity
public class MessageService extends Service implements SinchClientListener {
private static final String APP_KEY = "61b1bfc0-b82a-44f5-ab68-dedca69ead8c";
private static final String APP_SECRET = "jrFrLr8Adkm0Na4nLdASDw==";
private static final String ENVIRONMENT = "sandbox.sinch.com";
private final MessageServiceInterface serviceInterface = new MessageServiceInterface();
private SinchClient sinchClient = null;
private MessageClient messageClient = null;
private String currentUserId;
private LocalBroadcastManager broadcaster;
private Intent broadcastIntent = new Intent("com.dooba.beta.matchOptionActivity");
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
currentUserId = ParseUser.getCurrentUser().getObjectId();
if (currentUserId != null && !isSinchClientStarted()) {
startSinchClient(currentUserId);
}
broadcaster = LocalBroadcastManager.getInstance(this);
return super.onStartCommand(intent, flags, startId);
}
public void startSinchClient(String username) {
sinchClient = Sinch.getSinchClientBuilder().context(this).userId(username).applicationKey(APP_KEY)
.applicationSecret(APP_SECRET).environmentHost(ENVIRONMENT).build();
sinchClient.addSinchClientListener(this);
sinchClient.setSupportMessaging(true);
sinchClient.setSupportActiveConnectionInBackground(true);
sinchClient.checkManifest();
sinchClient.start();
}
private boolean isSinchClientStarted() {
return sinchClient != null && sinchClient.isStarted();
}
#Override
public void onClientFailed(SinchClient client, SinchError error) {
broadcastIntent.putExtra("success", false);
broadcaster.sendBroadcast(broadcastIntent);
sinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
broadcastIntent.putExtra("success", true);
broadcaster.sendBroadcast(broadcastIntent);
client.startListeningOnActiveConnection();
messageClient = client.getMessageClient();
}
#Override
public void onClientStopped(SinchClient client) {
sinchClient = null;
}
#Override
public IBinder onBind(Intent intent) {
return serviceInterface;
}
#Override
public void onLogMessage(int level, String area, String message) {
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client, ClientRegistration clientRegistration) {
}
public void sendMessage(String recipientUserId, String textBody) {
if (messageClient != null) {
WritableMessage message = new WritableMessage(recipientUserId, textBody);
messageClient.send(message);
}
}
public void addMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.addMessageClientListener(listener);
}
}
public void removeMessageClientListener(MessageClientListener listener) {
if (messageClient != null) {
messageClient.removeMessageClientListener(listener);
}
}
public class MessageServiceInterface extends Binder {
public void sendMessage(String recipientUserId, String textBody) {
MessageService.this.sendMessage(recipientUserId, textBody);
}
public void addMessageClientListener(MessageClientListener listener) {
MessageService.this.addMessageClientListener(listener);
}
public void removeMessageClientListener(MessageClientListener listener) {
MessageService.this.removeMessageClientListener(listener);
}
public boolean isSinchClientStarted() {
return MessageService.this.isSinchClientStarted();
}
}
Message adapter activity:
public class MessageAdapter extends BaseAdapter {
public static final int DIRECTION_INCOMING = 0;
public static final int DIRECTION_OUTGOING = 1;
private List<Pair<WritableMessage, Integer>> messages;
private LayoutInflater layoutInflater;
public MessageAdapter(Activity activity) {
layoutInflater = activity.getLayoutInflater();
messages = new ArrayList<Pair<WritableMessage, Integer>>();
}
public void addMessage(WritableMessage message, int direction) {
messages.add(new Pair(message, direction));
notifyDataSetChanged();
}
#Override
public int getCount() {
return messages.size();
}
#Override
public Object getItem(int i) {
return messages.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int i) {
return messages.get(i).second;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
int direction = getItemViewType(i);
//show message on left or right, depending on if
//it's incoming or outgoing
if (convertView == null) {
int res = 0;
if (direction == DIRECTION_INCOMING) {
res = R.layout.message_right;
} else if (direction == DIRECTION_OUTGOING) {
res = R.layout.message_left;
}
convertView = layoutInflater.inflate(res, viewGroup, false);
}
WritableMessage message = messages.get(i).first;
TextView txtMessage = (TextView) convertView.findViewById(R.id.txtMessage);
txtMessage.setText(message.getTextBody());
return convertView;
}
}
I wrote the tutorial you're following, and actually just updated it yesterday to fix your first problem. Check out http://tutorial.sinch.com/android-messaging-tutorial/#show-spinner to see the updates. Instead of showing a toast message when the service is not started, the new version will show a progress dialog (loading spinner) until the service has either started or failed to start.
Could you clarify your second question?
Just declare your service in manifest. I had the same problem and it solved it.

Categories