List ImageView repeating same image when shared - android

I have a listView that is supposed to accept a shared message and image where the image is placed within the ImageView. This feature works for just the first message, but once an image is shared, each message received after that initial one becomes a copy of that same image even though the blank image placeholder was already set, which is just a one pixel black png:
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
An example is below:
The green textbox is the recipient. They have recieved a shared image from the yellow textbox. The yellow textbox then simply sends a normal message and I have set another image as a placeholder for normal messages: holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
The same previously shared image takes precedence. I have used notifyDataSetChanged() so as to allow for the updating the adapter so that it would recognize not to use the same image, but to no avail.
How can I reformulate this class so that the image shared is only displayed with the proper message and not copied into each subsequent message?
The ArrayAdapter class:
public class DiscussArrayAdapter extends ArrayAdapter<OneComment> {
class ViewHolder {
TextView countryName;
ImageView sharedSpecial;
LinearLayout wrapper;
}
private TextView countryName;
private ImageView sharedSpecial;
private MapView locationMap;
private GoogleMap map;
private List<OneComment> countries = new ArrayList<OneComment>();
private LinearLayout wrapper;
private JSONObject resultObject;
private JSONObject imageObject;
String getSharedSpecialURL = null;
String getSharedSpecialWithLocationURL = null;
String specialsActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecial/";
String specialsLocationActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecialWithLocation/";
String JSON = ".json";
#Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public DiscussArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.countries.size();
}
private OneComment comment = null;
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.message_list_item, parent, false);
holder = new ViewHolder();
holder.wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
holder.countryName = (TextView) row.findViewById(R.id.comment);
holder.sharedSpecial = (ImageView) row.findViewById(R.id.sharedSpecial);
// Store the ViewHolder as a tag.
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Log.v("COMMENTING","Comment is " + countries.get(position).comment);
//OneComment comment = getItem(position);
holder.countryName.setText(countries.get(position).comment);
// Initiating Volley
final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
// Check if message has campaign or campaign/location attached
if (countries.get(position).campaign_id == "0" && countries.get(position).location_id == "0") {
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
Log.v("TESTING", "It is working");
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id != "0") {
// If both were shared
getSharedSpecialWithLocationURL = specialsLocationActionURL + countries.get(position).campaign_id + "/" + countries.get(position).location_id + JSON;
// Test Campaign id = 41
// Location id = 104
// GET JSON data and parse
JsonObjectRequest getCampaignLocationData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialWithLocationURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignLocationData);
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id == "0") {
// Just the campaign is shared
getSharedSpecialURL = specialsActionURL + countries.get(position).campaign_id + JSON;
// Test Campaign id = 41
// GET JSON data and parse
JsonObjectRequest getCampaignData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignData);
// Location set to empty
}
// If left is true, then yellow, if not then set to green bubble
holder.countryName.setBackgroundResource(countries.get(position).left ? R.drawable.bubble_yellow : R.drawable.bubble_green);
holder.wrapper.setGravity(countries.get(position).left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
}
The messaging class that sends normal messages only but can receive image messages and set to the adapter:
public class GroupMessaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
public String groupname;
private Button sendMessageButton;
private Manager imService;
private InfoOfGroup group = new InfoOfGroup();
private InfoOfGroupMessage groupMsg = new InfoOfGroupMessage();
private StorageManipulater localstoragehandler;
private Cursor dbCursor;
private com.example.feastapp.ChatBoxUi.DiscussArrayAdapter adapter;
private ListView lv;
private EditText editText1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message_activity);
lv = (ListView) findViewById(R.id.listView1);
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.message_list_item);
lv.setAdapter(adapter);
editText1 = (EditText) findViewById(R.id.editText1);
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
group.userName = extras.getString(InfoOfGroupMessage.FROM_USER);
group.groupName = extras.getString(InfoOfGroup.GROUPNAME);
group.groupId = extras.getString(InfoOfGroup.GROUPID);
String msg = extras.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
setTitle("Group: " + group.groupName);
// Retrieve the information
localstoragehandler = new StorageManipulater(this);
dbCursor = localstoragehandler.groupGet(group.groupName);
if (dbCursor.getCount() > 0) {
// Probably where the magic happens, and keeps pulling the same
// thing
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
}
}
localstoragehandler.close();
if (msg != null) {
// Then friends username and message, not equal to null, recieved
adapter.add(new OneComment(true, group.groupId + ": " + msg, "0", "0"));
adapter.notifyDataSetChanged();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel((group.groupId + msg).hashCode());
}
// The send button
sendMessageButton.setOnClickListener(new OnClickListener() {
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = editText1.getText();
if (message.length() > 0) {
// When general texting, the campaign and location will always be "0"
// Only through specials sharing is the user permitted to change the campaign and location to another value
adapter.add(new OneComment(false, imService.getUsername() + ": " + message.toString(), "0", "0"));
adapter.notifyDataSetChanged();
localstoragehandler.groupInsert(imService.getUsername(), group.groupName,
group.groupId, message.toString(), "0", "0");
// as msg sent, will blank out the text box so can write in
// again
editText1.setText("");
Thread thread = new Thread() {
public void run() {
try {
// JUST PUTTING "0" AS A PLACEHOLDER FOR CAMPAIGN AND LOCATION
// IN FUTURE WILL ACTUALLY ALLOW USER TO SHARE CAMPAIGNS
if (imService.sendGroupMessage(group.groupId,
group.groupName, message.toString(), "0", "0") == null) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
// showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id) {
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1) {
return null;
} else {
return new AlertDialog.Builder(GroupMessaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked OK so do some stuff */
}
}).create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(groupMessageReceiver);
unbindService(mConnection);
ControllerOfGroup.setActiveGroup(null);
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(MessagingService.TAKE_GROUP_MESSAGE);
registerReceiver(groupMessageReceiver, i);
ControllerOfGroup.setActiveGroup(group.groupName);
}
// For receiving messages form other users...
public class GroupMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = intent.getExtras();
//Log.i("GroupMessaging Receiver ", "received group message");
String username = extra.getString(InfoOfGroupMessage.FROM_USER);
String groupRId = extra.getString(InfoOfGroupMessage.TO_GROUP_ID);
String message = extra
.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
// NEED TO PLACE INTO THE MESSAGE VIEW!!
String received_campaign_id = extra.getString(InfoOfGroupMessage.CAMPAIGN_SHARED);
String received_location_id = extra.getString(InfoOfGroupMessage.LOCATION_SHARED);
// NEED TO INTEGRATE THIS INTO LOGIC ABOVE, SO IT MAKES SENSE
if (username != null && message != null) {
if (group.groupId.equals(groupRId)) {
adapter.add(new OneComment(true, username + ": " + message, received_campaign_id, received_location_id));
localstoragehandler
.groupInsert(username, groupname, groupRId, message, received_campaign_id, received_location_id);
Toast.makeText(getApplicationContext(), "received_campaign: " + received_campaign_id +
" received_location:" + received_location_id, Toast.LENGTH_LONG).show();
received_campaign_id = "0";
received_location_id = "0";
} else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(GroupMessaging.this,
username + " says '" + message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
}
;
// Build receiver object to accept messages
public GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}

I have gone through your code and this is common problem with listview that images starts repeating itself. In your case I think you have assigned image to Imageview every if and else if condition but if none of the condition satisfy it uses the previous image.
I would suggest to debug the getview method and put break points on the setImageResource. I use volley for these image loading and it has a method called defaultImage so that if no url is there the image is going to get the default one. So add that default case and see if it works.
If any of the above point is not clear feel free to comment.

Related

Updating recyclerview using findViewHolderForLayoutPosition

We are creating a chat application using openfire, smack. In that there is a chatscreen where users can send and receive messages and media files. For storing messages we are using Realm as local db. I want to show the progress of files during upload of files.
My Upload file code is :
public void firebasestorageMeth(final String msg, final String path, final String filetype, final String mykey, final String otheruserkey, final String username) {
StorageReference riversRef = STORAGE_REFERENCE.child(mykey).child("files").child(GetTimeStamp.timeStampDate());
final String timestampdate = GetTimeStamp.timeStampDate();
final String timestamptime = GetTimeStamp.timeStampTime();
final long id = GetTimeStamp.Id();
ChatMessageRealm cmr = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, msg, mykey, timestamptime, timestampdate, filetype, String.valueOf(id), "0", "",path);
ChatHelper.addChatMesgRealmMedia1(cmr, this, mykey, otheruserkey);
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_STARTING).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
Log.d(TAG, cmr.getChatref()+cmr.getMsgid()+cmr.getMsgstring()+"file path extension upload file" + path);
riversRef.putFile(Uri.fromFile(new File(path)))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
umpref.setUri(String.valueOf(id), path);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.d(TAG, "file uploaded" + downloadUrl);
ChatMessageRealm cmr = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, msg, mykey, timestamptime, timestampdate, filetype, String.valueOf(id), "1", String.valueOf(downloadUrl),path);
ChatHelper.addChatMesgRealmMedia1(cmr, getApplicationContext(), mykey, otheruserkey);
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_SUCCESS).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmediaurl", String.valueOf(downloadUrl)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_FAILED).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
exception.printStackTrace();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", progress + " ").putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
}
});
}
The chatadapter code is :
public class ChatAdapter1 extends RecyclerView.Adapter<ChatAdapter1.MyViewHolder> {
ArrayList<ChatMessageRealm> mList = new ArrayList<>();
private Context context;
private UserSession session;
public static final int SENDER = 0;
public static final int RECIPIENT = 1;
String TAG = "ChatAdapter1";
public ChatAdapter1(ArrayList<ChatMessageRealm> list, Context context) {
this.mList = list;
this.context = context;
session = new UserSession(context);
}
#Override
public int getItemViewType(int position) {
if (mList.get(position).getSenderjid().matches(session.getUserKey())) {
return SENDER;
} else {
return RECIPIENT;
}
}
#Override
public int getItemCount() {
return mList.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (viewType) {
case SENDER:
View viewSender = inflater.inflate(R.layout.row_chats_sender, viewGroup, false);
viewHolder = new MyViewHolder(viewSender);
break;
case RECIPIENT:
View viewRecipient = inflater.inflate(R.layout.row_chats_receiver, viewGroup, false);
viewHolder = new MyViewHolder(viewRecipient);
break;
}
return (MyViewHolder) viewHolder;
}
#Override
public void onBindViewHolder(final ChatAdapter1.MyViewHolder holder, int position) {
final ChatMessageRealm comment = mList.get(position);
holder.setIsRecyclable(false);
// holder.otherSender_sender.setText(comment.getSenderjid());
holder.otherSender_Timestamp.setText(comment.getSendertime() + "," + comment.getSenderdate());
// holder.status.setVisibility(View.GONE);
switch (comment.getMsgtype()) {
case "text":
// holder.btndown.setVisibility(View.GONE);
String decryptedmsg = comment.getMsgstring();
holder.commentString.setText(decryptedmsg);
// holder.photo.setVisibility(View.GONE);
break;
case "photo":
Glide.clear(holder.imgchat);
holder.imgchat.setVisibility(View.VISIBLE);
holder.progress.setVisibility(View.VISIBLE);
if (getItemViewType(position) == SENDER) {
// holder.btndown.setVisibility(View.GONE);
// holder.btnopen.setVisibility(View.VISIBLE);
try {
Glide.with(context).load(comment.getMsglocalurl()).into(holder.imgchat);
}catch (Exception e){
e.printStackTrace();
}
}
break;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView otherSender_Timestamp, commentString,progress;
public ImageView imgchat;
public Button btndown, btnopen;
public MyViewHolder(View itemView) {
super(itemView);
otherSender_Timestamp = (TextView) itemView.findViewById(R.id.meSender_TimeStamp);
commentString = (TextView) itemView.findViewById(R.id.commentString);
progress = (TextView) itemView.findViewById(R.id.mediaprogress);
imgchat = (ImageView) itemView.findViewById(R.id.imgchat);
btndown = (Button) itemView.findViewById(R.id.btndown);
btnopen = (Button) itemView.findViewById(R.id.btnopen);
}
}
}
ChatActivity code is:
public class ChatActivity extends ToadoBaseActivity {
private EditText typeComment;
private ImageButton sendButton, attachment, takephoto;
Intent intent;
private RecyclerView recyclerView;
DatabaseReference dbChat;
private String otheruserkey;
LinearLayoutManager linearLayoutManager;
private MarshmallowPermissions marshmallowPermissions;
private ArrayList<String> mResults = new ArrayList<>();
private ActionMode actionMode;
UploadFileService uploadFileService;
boolean mServiceBound = false;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm aa");
private ChatAdapter1 mAdapter;
LinkedHashSet<ChatMessageRealm> uniqueStrings = new LinkedHashSet<ChatMessageRealm>();
private ArrayList<ChatMessageRealm> chatList = new ArrayList<>();
private ArrayList<String> chatListIds = new ArrayList<>();
String username, mykey;
private UserSession session;
String receiverToken = "nil";
boolean clicked;
LinearLayout layoutToAdd;
LinearLayout commentView;
private ChildEventListener dbChatlistener;
ImageButton photoattach, videoattach;
Uri videoUri;
public String dbTableKey;
EncryptUtils encryptUtils = new EncryptUtils();
private ImageButton imgdocattach;
private ImageButton locattach;
private LinearLayout spamView;
TextView tvTitle;
ImageView imgprof;
private ArrayList<String> imagesPathList;
private final int PICK_IMAGE_MULTIPLE = 199;
private ProgressBar progressBar;
UserMediaPrefs umprefs;
private Boolean mBounded;
private String TAG = "ChatActivity";
// AbstractXMPPConnection connection;
Realm mRealm;
Boolean chatexists;
private String otherusername;
private String profpic;
private MyXMPP2 myxinstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
session = new UserSession(this);
mykey = session.getUserKey();
// connection = MyXMPP2.getInstance(this,).getConn();
mRealm = Realm.getDefaultInstance();
checkChatRef(otheruserkey);
clicked = false;
layoutToAdd = (LinearLayout) findViewById(R.id.attachmentpopup);
marshmallowPermissions = new MarshmallowPermissions(this);
spamView = (LinearLayout) findViewById(R.id.spamView);
umprefs = new UserMediaPrefs(this);
//get these 2 things from notifications also
intent = getIntent();
otheruserkey = intent.getStringExtra("otheruserkey");
otherusername = intent.getStringExtra("otherusername");
profpic = intent.getStringExtra("profpic");
System.out.println("recevier token chat act oncreate" + otheruserkey);
imgprof = (ImageView) findViewById(R.id.icon_profile);
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvTitle.setText(otherusername);
commentView = (LinearLayout) findViewById(R.id.commentView);
progressBar = (ProgressBar) findViewById(R.id.progress);
typeComment = (EditText) findViewById(R.id.typeComment);
sendButton = (ImageButton) findViewById(R.id.sendButton);
attachment = (ImageButton) findViewById(R.id.attachment);
takephoto = (ImageButton) findViewById(R.id.takephoto);
photoattach = (ImageButton) findViewById(R.id.photoattach);
imgdocattach = (ImageButton) findViewById(R.id.docattach);
videoattach = (ImageButton) findViewById(R.id.videoattach);
locattach = (ImageButton) findViewById(R.id.locationattach);
myxinstance = MyXMPP2.getInstance(ChatActivity.this, getString(R.string.server), mykey);
mAdapter = new ChatAdapter1(chatList, this);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(mAdapter);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(mykey + " chat created " + otheruserkey);
ChatMessageRealm cm = null;
if (!typeComment.getText().toString().matches("")) {
cm = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, typeComment.getText().toString(), mykey, GetTimeStamp.timeStampTime(), GetTimeStamp.timeStampDate(), "text", String.valueOf(GetTimeStamp.Id()), "1");
}
if (cm != null)
myxinstance.sendMessage(cm);
loadData();
typeComment.setText("");
}
});
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (layoutToAdd.getVisibility() == View.VISIBLE)
layoutToAdd.setVisibility(View.GONE);
else
layoutToAdd.setVisibility(View.VISIBLE);
}
});
takephoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
dispatchTakePictureIntent();
} catch (ActivityNotFoundException anfe) {
anfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
mykey = session.getUserKey();
username = session.getUsername();
loadData();
}
private void loadData() {
Sort sort[] = {Sort.ASCENDING};
String[] fieldNames = {"msgid"};
RealmResults<ChatMessageRealm> shows = mRealm.where(ChatMessageRealm.class).equalTo("chatref", mykey + otheruserkey).findAllSorted(fieldNames, sort);
if (shows.size() > 0) {
Log.d(TAG, shows.size() + "LOAD DATA CALLED " + shows.get(shows.size() - 1).getMsgstring());
for (ChatMessageRealm cm : shows) {
if (!chatList.contains(cm)) {
chatList.add(cm);
}
if (!chatListIds.contains(cm.getMsgid())) {
chatListIds.add(cm.getMsgid());
}
mAdapter.notifyDataSetChanged();
}
mAdapter.notifyDataSetChanged();
recyclerView.scrollToPosition(chatList.size() - 1);
}
}
private void checkChatRef(String otheruserkey) {
RealmQuery<ActiveChats> query = mRealm.where(ActiveChats.class);
query.equalTo("otherkey", otheruserkey);
RealmResults<ActiveChats> result1 = query.findAll();
if (result1.size() == 0) {
chatexists = false;
} else {
chatexists = true;
}
System.out.println(result1.size() + "chat exists chatactivity" + chatexists);
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(this.reloadData, new IntentFilter("reloadchataction"));
}
#Override
protected void onStop() {
super.onStop();
if (reloadData != null)
unregisterReceiver(reloadData);
}
private void dispatchTakePictureIntent() throws IOException {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "request code chatactivity" + requestCode);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
Log.d(TAG, "crop activity");
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
final String imguri = result.getUri().toString();
try {
final File file = createImageFile();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
InputStream in = null;
OutputStream out = null;
try {
in = getContentResolver().openInputStream(Uri.parse(imguri));
out = new FileOutputStream(file);
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
String s = file.getAbsolutePath();
Log.d(TAG, "image cropped uri chatact22" + file.getAbsolutePath());
Intent intent = new Intent(ChatActivity.this, ImageComment.class);
intent.putExtra("URI", s);
intent.putExtra("comment_type", "photo");
startImageComment(intent);
} catch (Exception ex) {
Log.e("Something went wrong.", ex.toString());
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName = "pic-" + GetTimeStamp.timeStamp() + ".jpg";
File image = OpenFile.createFile(this, imageFileName);
// Save a file: path for use with ACTION_VIEW intents
Log.d(TAG, "file createimagefile: " + image.getAbsolutePath());
return image;
}
private void startImageComment(Intent intent) {
Log.d(TAG, "image comment sending" + intent.getStringExtra("URI"));
intent.putExtra("username", username);
intent.putExtra("otheruserkey", otheruserkey);
intent.putExtra("receiverToken", receiverToken);
intent.putExtra("mykey", mykey);
startActivity(intent);
}
BroadcastReceiver reloadData = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra("reloadchat") != null) {
Log.d(TAG, " reloading data broadcast receiver" + intent.getStringExtra("reloadchat"));
loadData();
mAdapter.notifyDataSetChanged();
} else if (intent.getStringExtra("reloadchatmediastatus") != null) {
if (intent.getStringExtra("reloadchatmediastatus").matches(MEDIA_STARTING))
loadData();
Log.d(TAG, " reloading data status " + intent.getStringExtra("reloadchatmediastatus"));
Log.d(TAG, " reloading data media id " + intent.getStringExtra("reloadchatmediaid"));
if (!intent.getStringExtra("reloadchatmediastatus").matches(MEDIA_FAILED)) {
final String msgid = intent.getStringExtra("reloadchatmediaid");
String fileprogress = intent.getStringExtra("reloadchatmediastatus");
int ind1 = chatListIds.indexOf(msgid);
Log.d(TAG, ind1 + "chat list broadcast progress " + fileprogress);
Log.d(TAG, "chat list broadcast" + chatListIds.size());
try {
// View ve = linearLayoutManager.findViewByPosition(ind1);
// View v = recyclerView.findViewHolderForAdapterPosition(ind1).itemView;
View v = recyclerView.findViewHolderForLayoutPosition(ind1).itemView;
ChatAdapter1.MyViewHolder holder = (ChatAdapter1.MyViewHolder) recyclerView.getChildViewHolder(v);
holder.commentString.setVisibility(View.VISIBLE);
holder.commentString.setText("file prog " + fileprogress);
mAdapter.notifyDataSetChanged();
Log.d(TAG, holder.getItemViewType() + "," + holder.getLayoutPosition() + "," + holder.commentString.getText().toString() + " VIEW HOLDER? " + v);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (intent.getStringExtra("reloadchatmediaurl") != null)
Log.d(TAG, " reloading data media url " + intent.getStringExtra("reloadchatmediaurl"));
}
};
}
I am trying to update my recyclerview dynamically in the broadcast receiver- reloadData in ChatActivity.
My logs tell me that i am receiving correct data from the sendbroadcast in the UploadFileService, the problem is in following code inside the broadcast receiver on ChatActivity, it is getting correct data but the data is not showing on the recycler view:
try {
View v = recyclerView.findViewHolderForLayoutPosition(ind1).itemView;
ChatAdapter1.MyViewHolder holder = (ChatAdapter1.MyViewHolder) recyclerView.getChildViewHolder(v);
holder.commentString.setVisibility(View.VISIBLE);
holder.commentString.setText("file prog " + fileprogress);
mAdapter.notifyDataSetChanged();
Log.d(TAG, holder.getItemViewType() + "," + holder.getLayoutPosition() + "," + holder.commentString.getText().toString() + " VIEW HOLDER? " + v);
} catch (Exception e) {
e.printStackTrace();
}
I get correct values , such as:
08-03 19:31:25.240 705-705/com.app.toado D/ChatActivity: 0,30,file prog 34 VIEW HOLDER? android.widget.LinearLayout{ff24ae0 V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
08-03 19:31:26.346 705-705/com.app.toado D/ChatActivity: 0,30,file prog 100 VIEW HOLDER? android.widget.LinearLayout{e8a33ce V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
08-03 19:31:26.347 705-705/com.app.toado D/ChatActivity: 0,30,file prog upload success VIEW HOLDER? android.widget.LinearLayout{e8a33ce V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
I have tried using View ve = linearLayoutManager.findViewByPosition(ind1); and View v = recyclerView.findViewHolderForAdapterPosition(ind1).itemView; but they are also not working. Also tried adding notifydatasetchanged to it.
The try catch is also not throwing any error in the logs.
Can someone please help in figuring out why are the changes not showing on the recycler view but are showing in logs?
Are you sure you're updating the RecyclerView's Adapter from the UI Thread? Whenever you try to update the ViewHolder, you have to be certain you're doing so on the UI or it will not behave as expected.
When the modification to the ViewHolder is changed, check that Looper.myLooper().equals(Looper.getMainLooper());. If it returns false, it means you aren't updating on the UI Thread, the necessary place for all graphical updates to be made.
If this is the case, you just need to make sure that you can synchronize your changes on the UI, using Activity.runOnUiThread(Runnable r);.

How to wait for an activity to finish in asynctask

I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}

Message is displayed two times after using notifyDataSetChanged

I am working on an instant chat application.My problem is that when i am sending message through my chat application,Message is displayed two times instead of one.Screen shot is given below :
As you can see in the acreenshot that the message hiii is displayed two times but i have sent only once.
1.Adapter_Message.java
public class Adapter_Message extends BaseAdapter {
private Context context;
private List<Bean_Message> messagesItems;
public Adapter_Message(Context context, List<Bean_Message> navDrawerItems) {
this.context = context;
this.messagesItems = navDrawerItems;
}
#Override
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Bean_Message m = messagesItems.get(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// Identifying the message owner
if (messagesItems.get(position).isSelf()) {
// message belongs to you, so load the right aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_right, null);
} else {
// message belongs to other person, load the left aligned layout
convertView = mInflater.inflate(R.layout.list_item_message_left, null);
}
TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
txtMsg.setText(m.getMessage());
lblFrom.setText(m.getFromName());
return convertView;
}
}
2.Chat_Activity.java
public class ChatActivity extends FragmentActivity implements
EmojiconGridFragment.OnEmojiconClickedListener, EmojiconsFragment.OnEmojiconBackspaceClickedListener {
public static final String TAG = ChatActivity.class.getSimpleName();
// EditText edMessage;
EmojiconEditText edMessage;
Button sendMessage;
private Socket mSocket;
String sID, lID, md5StringRoomID, message, friendName, loggedInUser;
String frndID;
int smallerID, largerID;
//AlmaChatDatabase almaChatDatabase;
// Chat messages list adapter
private Adapter_Message adapter;
private List<Bean_Message> listBeanMessages;
private ListView listViewMessages;
boolean isSelf; // to check whether the message is owned by you or not.true means message is owned by you .
Bean_Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
SharedPreferences preferences;
HashMap<String, Integer> emoticons;
// instance initialization block
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
Log.e("Socket", String.valueOf(mSocket));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
sendMessage = (Button) findViewById(R.id.btnSendMessage);
preferences = getApplicationContext().getSharedPreferences(Prefs_Registration.prefsName, Context.MODE_PRIVATE);
//Handling emoticons
/* emoticons = new HashMap<String,Integer>();
emoticons.put(":-)",R.drawable.s1);*/
String id = preferences.getString(Prefs_Registration.get_user_id, null);
// Converting String id to integer
loggedInUserID = Integer.parseInt(id);
//loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listBeanMessages = new ArrayList<Bean_Message>();
adapter = new Adapter_Message(getApplicationContext(), listBeanMessages);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
listViewMessages.setAdapter(adapter);
// Getting the ID of the friend from the previous screen using getExtras
Bundle bundle = getIntent().getExtras();
frndID = bundle.getString("ID");
Log.e("FriendID", frndID);
final int friendID = Integer.parseInt(frndID);
friendName = bundle.getString("name");
Log.e("FriendName", friendName);
loggedInUser = preferences.getString(Prefs_Registration.get_user_name, null);
//loggedInUser = almaChatDatabase.getUserName(); // Name of logged in user
Log.e("LoggedInUser", loggedInUser);
// Converting first lowercase letter of every word in Uppercase
final String loggedInUpper = upperCase(loggedInUser);
//To find the current time
Date d = new Date();
final long time = d.getTime();
// Comparing the loggedInUserId and friendID
if (friendID < loggedInUserID) {
smallerID = friendID;
largerID = loggedInUserID;
} else {
smallerID = loggedInUserID;
largerID = friendID;
}
sID = String.valueOf(smallerID);
lID = String.valueOf(largerID);
String combinedID = sID + lID;
Log.e("combined ID", combinedID);
md5StringRoomID = convertPassMd5(combinedID); // Encrypting the combinedID to generate Room ID
Log.e("md5StringRoomID", md5StringRoomID);
// Using the API for loading old chat messages
apiConfiguration = new APIConfiguration();
String api_message = apiConfiguration.getApi_message(); // Getting the API of messages
URL_FEED_Message = api_message + md5StringRoomID; // md5String is the encrypted room ID here
Log.e("URL_FEED_MESSAGE", URL_FEED_Message);
Log.e("Network request", "Fresh Request");
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(URL_FEED_Message);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONArray(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL_FEED_Message, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("JsonArray", String.valueOf(jsonArray));
if (jsonArray != null) {
parseJsonFeed(jsonArray);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ErrorResponse", String.valueOf(volleyError));
}
}
);
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
edMessage = (EmojiconEditText) findViewById(R.id.edtMessage);
//Listening on Events
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectionError);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on("send:notice", onReceive); // Listening event for receiving messages
mSocket.connect(); // Explicitly call connect method to establish connection here
mSocket.emit("subscribe", md5StringRoomID);
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = edMessage.getText().toString().trim();
Log.e("Sending", "Sending data-----" + message);
if (!message.equals("")) {
edMessage.setText(" ");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("room_id", md5StringRoomID);
jsonObject.put("user", loggedInUpper);
jsonObject.put("id", friendID);
jsonObject.put("message", message);
jsonObject.put("date", time);
jsonObject.put("status", "sent");
} catch (JSONException e) {
e.printStackTrace();
}
isSelf = true; // Boolean isSelf is set to be true as sender of the message is logged in user i.e. you
attemptToSend(loggedInUpper, message, isSelf);
mSocket.emit("send", jsonObject); // owner i.e LoggedIn user is sending the message
} else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Please enter some text", Toast.LENGTH_LONG).show();
}
});
}
}
});
setEmojiconFragment(false);
}
/* public Spannable getSmiledText(String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
if (emoticons.size() > 0) {
int index;
for (index = 0; index < builder.length(); index++) {
if (Character.toString(builder.charAt(index)).equals(":")) {
for (Map.Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > builder.length())
continue;
if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
builder.setSpan(new ImageSpan(getApplicationContext(), entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
}
}
return builder;
}*/
private void setEmojiconFragment(boolean useSystemDefault) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.emojicons, EmojiconsFragment.newInstance(useSystemDefault))
.commit();
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
// Playing sound when the message is sent by the owner
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
// encrypting string into MD5
public static String convertPassMd5(String pass) {
String password = null;
MessageDigest mdEnc;
try {
mdEnc = MessageDigest.getInstance("MD5");
mdEnc.update(pass.getBytes(), 0, pass.length());
pass = new BigInteger(1, mdEnc.digest()).toString(16);
while (pass.length() < 32) {
pass = "0" + pass;
}
password = pass;
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
return password;
}
// Converting first lowercase letter of every word in Uppercase
String upperCase(String source) {
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
return res.toString().trim();
}
// Event Listeners
private Emitter.Listener onConnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Socket", "Connected");
}
};
private Emitter.Listener onConnectionError = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Error", "Error in connecting server");
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.e("Disconnect", "Socket Disconnected");
}
};
// Event Listener for receiving messages
private Emitter.Listener onReceive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
Log.e("Receive", "Bean_Message received");
runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
Log.e("DATA", String.valueOf(data));
try {
JSONArray ops = data.getJSONArray("ops");
for (int i = 0; i < ops.length(); i++) {
JSONObject object = ops.getJSONObject(i);
String roomID = object.getString("room_id");
Log.e("RoomID", roomID); // Getting room ID from JSON array
Log.e("Md5RoomID", md5StringRoomID); // Getting room id which we have created using logged in user ID and room id of the user through which chat has to be done
//Comparing the room IDs
if (md5StringRoomID.equals(roomID)) {
String senderName = object.getString("user");
Log.e("Sender Name", senderName);
String senderID = object.getString("id");
Log.e("SenderID", senderID);
// JSONObject message = object.getJSONObject("message");
String messageReceived = object.getString("message");
Log.e("Bean_Message Received", messageReceived);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(senderName)) {
isSelf = true;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
// Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Bean_Message(senderName, messageReceived, isSelf);
listBeanMessages.add(msg);
Log.e("List Elements", String.valueOf(listBeanMessages));
adapter.notifyDataSetChanged();
playBeep();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Playing sound when the message is sent by other
public void playBeep() {
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Parsing JSon Array which corresponds to the old chat messages
public void parseJsonFeed(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String roomID = jsonObject.getString("room_id");
Log.e("RoomID", roomID);
Log.e("Md5RoomID", md5StringRoomID);
// If Room ID(created using id of logged in user and id of friend) matches with the room id obtained from JSON String
if (md5StringRoomID.equals(roomID)) {
String userName = jsonObject.getString("user");
Log.e("Name", userName);
String loggedInUSerNAme = preferences.getString(Prefs_Registration.get_user_name, null);
//String loggedInUSerNAme = almaChatDatabase.getUserName();
Log.e("LoggedInUSer", loggedInUSerNAme);
//If the message is sent by the owner to other from webapp ,then we need to check whether the sender is the loggedinUSer in the App or not and we will right align the messages .
if (loggedInUSerNAme.equalsIgnoreCase(userName)) {
String message = jsonObject.getString("message");
Log.e("message", message);
isSelf = true;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Bean_Message(userName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
#Override
public void onEmojiconBackspaceClicked(View view) {
EmojiconsFragment.backspace(edMessage);
}
#Override
public void onEmojiconClicked(Emojicon emojicon) {
EmojiconsFragment.input(edMessage, emojicon);
}
}
3.Bean_Message.java
public class Bean_Message {
private String fromName, message;
private boolean isSelf; // isSelf is used to check whether the message is owned by you or not
public Bean_Message() {
}
public Bean_Message(String fromName, String message, boolean isSelf) {
this.fromName = fromName;
this.message = message;
this.isSelf = isSelf;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSelf() {
return isSelf;
}
public void setSelf(boolean isSelf) {
this.isSelf = isSelf;
}
}
On clicking "Send Message" button ,message is sent to he server and the following code is used:
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Bean_Message(senderName, message, isSelf);
listBeanMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
}
Message is stored in the Bean and Bean is added in the ArrayList .Now i am notifying my adapter that the ArrayList is updated using adapter.notifyDataSetChanged() method.But the problem is List view is displaying my sent message two times.Please help me to solve the issue .

Transaction ID set correctly, but displayed only a submit later

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);

Quickblox android sdk groupchat

I'm using quickblox sdk group chat.
This is my code. But I still wrong. Can anybody guide me, please?
UserListForGroupActivity.java
public class UserListForGroupActivity extends Activity implements QBCallback {
private ListView usersList;
private ProgressDialog progressDialog;
private Button btnChat;
private SimpleAdapter usersAdapter;
private ArrayList<Friend_Users> friends= new ArrayList<Friend_Users>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list_for_group);
usersList = (ListView) findViewById(R.id.usersList);
btnChat=(Button)findViewById(R.id.btnstartGroupChat);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading fiends list");
progressDialog.show();
// ================= QuickBlox ===== Step 4 =================
// Get all users of QB application.
QBUsers.getUsers(this);
}
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
if (progressDialog != null) {
progressDialog.dismiss();
}
// Cast 'result' to specific result class QBUserPagedResult.
QBUserPagedResult pagedResult = (QBUserPagedResult) result;
final ArrayList<QBUser> users = pagedResult.getUsers();
System.out.println(users.toString());
// Prepare users list for simple adapter.
ArrayList<Map<String, String>> usersListForAdapter = new ArrayList<Map<String, String>>();
for (QBUser u : users) {
Map<String, String> umap = new HashMap<String, String>();
umap.put("userLogin", u.getLogin());
umap.put("chatLogin", QBChat.getChatLoginFull(u));
usersListForAdapter.add(umap);
}
// Put users list into adapter.
usersAdapter = new SimpleAdapter(this, usersListForAdapter,
android.R.layout.simple_list_item_multiple_choice,
new String[]{"userLogin", "chatLogin"},
new int[]{android.R.id.text1, android.R.id.text2});
usersList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
usersList.setAdapter(usersAdapter);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checked= usersList.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
{
QBUser friendUser = users.get(position);
String login, password;
int id;
id=friendUser.getId();
login=friendUser.getLogin();
password=friendUser.getPassword();
friends.add(new Friend_Users(id,login, password));
}
}
Friend_Users_Wrapper wrapper= new Friend_Users_Wrapper(friends);
Log.e("UserListForGroupAcitvity friend list pass intent=>", friends.size()+ friends.get(0).getLogin());
Bundle extras = getIntent().getExtras();
Intent intent=new Intent(UserListForGroupActivity.this, GroupChatActivity.class);
intent.putExtra("friends", wrapper);
intent.putExtras(extras);
startActivity(intent);
}
});
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Error(s) occurred. Look into DDMS log for details, " +
"please. Errors: " + result.getErrors()).create().show();
}
}
#Override
public void onComplete(Result result, Object context) { }
}
GroupChatActivity.java
public class GroupChatActivity extends Activity {
private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
private QBUser me;
private GroupChatController groupChatController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
// Load QBUser objects from bundle (passed from previous activity).
Bundle extras = getIntent().getExtras();
Friend_Users_Wrapper wrapper= (Friend_Users_Wrapper) getIntent().getSerializableExtra("friends");
ArrayList<Friend_Users> friendArray= wrapper.getFriend_Users();
me = new QBUser();
me.setId(extras.getInt("myId"));
me.setLogin(extras.getString("myLogin"));
me.setPassword(extras.getString("myPassword"));
System.out.println("user login =>"+extras.getString("myLogin"));
QBUser friends= new QBUser();
for (Friend_Users friend_Users : friendArray) {
friends.setId(friend_Users.getId());
friends.setLogin(friend_Users.getLogin());
friends.setPassword(friend_Users.getPassword());
}
// UI stuff
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
sendMessageButton.setOnClickListener(onSendMessageClickListener);
messageText = (EditText) findViewById(R.id.messageEdit);
// ================= QuickBlox ===== Step 5 =================
// Get chat login based on QuickBlox user account.
// Note, that to start chat you should use only short login,
// that looks like '17744-1028' (<qb_user_id>-<qb_app_id>).
String chatLogin = QBChat.getChatLoginShort(me);
// Our current (me) user's password.
String password = me.getPassword();
if (me != null && friends != null) {
// ================= QuickBlox ===== Step 6 =================
// All chat logic can be implemented by yourself using
// ASMACK library (https://github.com/Flowdalic/asmack/downloads)
// -- Android wrapper for Java XMPP library (http://www.igniterealtime.org/projects/smack/).
groupChatController = new GroupChatController(chatLogin, password);
groupChatController.setOnMessageReceivedListener(onMessageReceivedListener);
// ================= QuickBlox ===== Step 7 =================
// Get friend's login based on QuickBlox user account.
// Note, that for your companion you should use full chat login,
// that looks like '17792-1028#chat.quickblox.com' (<qb_user_id>-<qb_app_id>#chat.quickblox.com).
// Don't use short login, it
String friendLogin = QBChat.getChatLoginFull(friends);
groupChatController.startChat(friendLogin);
}
}
private void sendMessage() {
if (messageText != null) {
String messageString = messageText.getText().toString();
groupChatController.sendMessage(messageString);
messageText.setText("");
showMessage(me.getLogin() + " (me) : "+messageString, true);
}
}
private GroupChatController.OnMessageReceivedListener onMessageReceivedListener = new GroupChatController.OnMessageReceivedListener() {
#Override
public void onMessageReceived(final Message message) {
String messageString = message.getBody();
showMessage(messageString, false);
}
};
private void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(GroupChatActivity.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
#Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
private View.OnClickListener onSendMessageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
};
}
GroupChatController.java
public class GroupChatController {
// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();
private XMPPConnection connection;
private ConnectionConfiguration config;
private Chat chat;
// Multi-User Chat
private MultiUserChat muc2;
private String chatLogin;
private String password;
private String friendLogin;
private ChatManager chatManager;
public GroupChatController(String chatLogin, String password) {
this.chatLogin = chatLogin;
this.password = password;
}
public void startChat(String buddyLogin) {
this.friendLogin = buddyLogin;
new Thread(new Runnable() {
#Override
public void run() {
// Chat action 1 -- create connection.
Connection.DEBUG_ENABLED = true;
config = new ConnectionConfiguration(CHAT_SERVER);
connection = new XMPPConnection(config);
try {
connection.connect();
connection.login(chatLogin, password);
// Chat action 2 -- create chat manager.
chatManager = connection.getChatManager();
// Chat action 3 -- create chat.
chat = chatManager.createChat(friendLogin, messageListener);
// Set listener for outcoming messages.
chatManager.addChatListener(chatManagerListener);
// Muc 2
if(connection != null){
muc2 = new MultiUserChat(connection, "2389_chat1#muc.chat.quickblox.com");
// Discover whether user3#host.org supports MUC or not
// The room service will decide the amount of history to send
muc2.join(chatLogin);
muc2.invite(friendLogin, "Welcome!");
Log.d("friendLogin ->",friendLogin);
// Set listener for outcoming messages.
//chatManager.addChatListener(chatManagerListener);
muc2.addMessageListener(packetListener);
addListenerToMuc(muc2);
//chat1#muc.chat.quickblox.com
}
Message message = new Message(friendLogin + "#muc.chat.quickblox.com");
message.setBody("Join me for a group chat!");
message.addExtension(new GroupChatInvitation("2389_chat1#muc.chat.quickblox.com"));
connection.sendPacket(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
/*** muc */
private void addListenerToMuc(MultiUserChat muc){
if(null != muc){
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Log.i("processPacket", "receiving message");
}
});
}
}
PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message)packet;
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
//System.out.println("got message " + message.toXML());
}
};
private PacketInterceptor packetInterceptor = new PacketInterceptor() {
#Override
public void interceptPacket(Packet packet) {
System.out.println("Sending message: " + packet.toString());
Message message = muc2.createMessage();
message.setBody("Hello from producer, message " +
" ");
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
/***/
private ChatManagerListener chatManagerListener = new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
// Set listener for incoming messages.
chat.addMessageListener(messageListener);
muc2.addMessageListener(packetListener);
}
};
public void sendMessage(String message) {
try {
if (chat != null) {
chat.sendMessage(message);
}
if (muc2 != null) {
muc2.sendMessage(message);
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
private MessageListener messageListener = new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
// 'from' and 'to' fields contains senders ids, e.g.
// 17792-1028#chat.quickblox.com/mac-167
// 17744-1028#chat.quickblox.com/Smack
String from = message.getFrom().split("#")[0];
String to = message.getTo().split("#")[0];
System.out.println(String.format(">>> Message received (from=%s, to=%s): %s",
from, to, message.getBody()));
if (onMessageReceivedListener != null) {
onMessageReceivedListener.onMessageReceived(message);
}
}
};
public static interface OnMessageReceivedListener {
void onMessageReceived(Message message);
}
// Callback that performs when device retrieves incoming message.
private OnMessageReceivedListener onMessageReceivedListener;
public OnMessageReceivedListener getOnMessageReceivedListener() {
return onMessageReceivedListener;
}
public void setOnMessageReceivedListener(OnMessageReceivedListener onMessageReceivedListener) {
this.onMessageReceivedListener = onMessageReceivedListener;
}
}
public void startChat(String buddyLogin) {
...
List<String> usersLogins= new ArrayList<String>();
for(String userLogin: usersLogins){
muc2.invite(userLogin, "Welcome!");
}
...
}

Categories

Resources