Quickblox android sdk groupchat - android

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!");
}
...
}

Related

Android Pusher Singleton channel subscription

Hello I have implemented pusher for realtime chat and subscribing to pusher channel , but I have many activities and fragments where i want to listen to pushr events . I have added this code in every activity/fragment but the problem is that it creates multiple subscriptions for every id . I know that i have to use Singleton for this can anyone point me in the right direction to achieve this ?
Here is the code i am writing in every activity/fragment
private PusherOptions options;
private Channel channel;
private Pusher pusher;
options = new PusherOptions();
options.setCluster("ap2");
pusher = new Pusher("afbfc1f591fd7b70190f", options);
pusher.connect();
profile_id = Global.shared().preferences.getString("PROFILE_ID", " ");
channel = pusher.subscribe(profile_id);
channel.bind("message",
new SubscriptionEventListener() {
#Override
public void onEvent(String s, String s1, final String data) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject result = new JSONObject(data);
String message = result.getString("message");
String time = result.getString("time");
String reId = result.getString("recieverId");
new_message = message;
getConvoData(k, message);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("DATA ====>>" + data);
}
});
}
});
okay so after trying for a while i figured it out my self i created a global class and just added pusher code to it so that it maintains just one connection for the entire lifecycle of the app
public class Global extends MultiDexApplication {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences preferences = sharedInstance.getSharedPreferences(sharedInstance.getString(R.string.shared_preferences), Context.MODE_PRIVATE);
sharedInstance.preferences = preferences;
connectTopusher();
}
public void connectTopusher() {
PusherOptions options;
Channel channel;
Pusher pusher;
options = new PusherOptions();
options.setCluster("ap2");
pusher = new Pusher("afbfc1f591fd7b70190f", options);
pusher.connect();
String profile = Global.shared().preferences.getString("PROFILE_ID", "");
channel = pusher.subscribe(profile);
channel.bind("message",
new SubscriptionEventListener() {
#Override
public void onEvent(String s, String s1, final String data) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
try {
JSONObject result = new JSONObject(data);
String message = result.getString("message");
String time = result.getString("time");
String reId = result.getString("recieverId");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("DATA ====>>" + data);
}
});
}
});
channel.bind("status_change", new SubscriptionEventListener() {
#Override
public void onEvent(String s, String s1, final String data) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
try {
JSONObject result = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("DATA ====>>" + data);
}
});
}
});
}
You can expose channel in your Global class. That will allow you to call bind and unbind in your fragments, when they are in the foreground.
connectToPusher should just create a channel and subscribe to it.
In Global.java:
private Channel channel;
public void connectTopusher() {
PusherOptions options;
Pusher pusher;
options = new PusherOptions();
options.setCluster("ap2");
pusher = new Pusher("afbfc1f591fd7b70190f", options);
pusher.connect();
String profile = Global.shared().preferences.getString("PROFILE_ID", "");
this.channel = pusher.subscribe(profile);
}
public Channel getChannel(){
return this.channel;
}
And then in your activity/fragment you can bind/unbind your listeners to when they are resumed/paused - just keep a reference to it like this:
YourActivity.java (could also be your Fragment)
private SubscriptionEventListener messageListener = new SubscriptionEventListener(){
#Override
public void onEvent(String channel, String event, String data) {
//TODO: do something with events
}
}
//Bind when the listener comes into the foreground:
#Override
protected void onResume() {
super.onResume();
((Global) getActivity().getApplication()).getChannel().bind("message", messageListener);
}
//Make sure to unbind the event listener!
#Override
protected void onPause() {
super.onPause();
((Global) getActivity().getApplication()).getChannel().unbind("message", messageListener);
}
I hope this helps :)

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 .

E/AndroidRuntime(31678): java.lang.IllegalArgumentException: Can only push to a query for Installations

I am new to parse ,i am able to store data to its database and also to retrieve some information like object-id from database but when I try to send push notification i usually get the above mentioned error.Query which i am using to send push notification with object-id corresponding to the given Friend-id.
public class MainActivity extends Activity {
private RadioButton genderFemaleButton;
private RadioButton genderMaleButton;
private Button getObjectId,sndpush;
private EditText ageEditText, frndidEditText, objectidEditText;
private RadioGroup genderRadioGroup;
private String FrndTextString, ageTextString, objectid;
private ParseObject sid;
public static final String GENDER_MALE = "male";
public static final String GENDER_FEMALE = "female";
protected static final String ParseIntallation = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(this, "c7fOlMSS4S8rxI53m0u49maP1Kab8PWVWSNwVu3s", "0xOUq1uoDb2NIi1jYZHWANZ9PP4X4W7vDfcA1UOw");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.saveInBackground();
// Track app opens.
ParseAnalytics.trackAppOpened(getIntent());
getObjectId = (Button) findViewById(R.id.get_button);
genderFemaleButton = (RadioButton) findViewById(R.id.gender_female_button);
genderMaleButton = (RadioButton) findViewById(R.id.gender_male_button);
ageEditText = (EditText) findViewById(R.id.age_edit_text);
genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
frndidEditText = (EditText) findViewById(R.id.frndid_edit_text);
sndpush = (Button) findViewById(R.id.send_push);
sndpush.setEnabled(true);
sndpush.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JSONObject obj;
try {
obj =new JSONObject();
obj.put("alert","erwerwe");
obj.put("action","com.parse.pushnotifications.UPDATE_STATUS");
obj.put("customdata","My string");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("objectId",objectidEditText.getText().toString() );
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
// vk
objectidEditText = (EditText) findViewById(R.id.objectid_edit_text);
getObjectId.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getObjectId();
}
});
}
#Override
public void onStart() {
super.onStart();
// Display the current values for this user, such as their age and gender.
displayUserProfile();
refreshUserProfile();
}
// Save the user's profile to their installation.
public void saveUserProfile(View view) {
ageTextString = ageEditText.getText().toString();
FrndTextString = frndidEditText.getText().toString();
if (ageTextString.length() > 0) {
sid.put("age",
Integer.valueOf(ageTextString));
}
if (FrndTextString.length() > 0) {
sid.put("FriendId",
FrndTextString);
}
if (ageTextString.length() > 0) {
ParseInstallation.getCurrentInstallation().put("age", Integer.valueOf(ageTextString));
}
if (FrndTextString.length() > 0) {
ParseInstallation.getCurrentInstallation().put("FriendId", Integer.valueOf(FrndTextString));
}
if (genderRadioGroup.getCheckedRadioButtonId() == genderFemaleButton
.getId()) {
sid.put("gender",
GENDER_FEMALE);
} else if (genderRadioGroup.getCheckedRadioButtonId() == genderMaleButton
.getId()) {
sid.put("gender",
GENDER_MALE);
} else {
sid.remove("gender");
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ageEditText.getWindowToken(), 0);
sid.saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast toast = Toast.makeText(
getApplicationContext(),
R.string.alert_dialog_success,
Toast.LENGTH_SHORT);
toast.show();
} else {
e.printStackTrace();
Toast toast = Toast.makeText(
getApplicationContext(),
R.string.alert_dialog_failed,
Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
// Get the user's Id from parse.com.
#SuppressWarnings({ "rawtypes", "unchecked" })
public void getObjectId() {
#SuppressWarnings("rawtypes")
ParseQuery query = new ParseQuery("sid");
query.whereEqualTo("FriendId", FrndTextString);
query.getFirstInBackground(new GetCallback() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("objectId", "The getFirst request failed.");
} else {
String objectid = object.getObjectId();
objectidEditText.setText(objectid);
sndpush.setEnabled(true);
Log.d("objectId", "Retrieved the object.");
}
}
});
}
// Refresh the UI with the data obtained from the current ParseInstallation
// object.
private void displayUserProfile() {
sid =ParseInstallation.create("sid");
String gender = sid.getString(
"gender");
int age = ParseInstallation.getCurrentInstallation().getInt("age");
if (gender != null) {
genderMaleButton.setChecked(gender.equalsIgnoreCase(GENDER_MALE));
genderFemaleButton.setChecked(gender
.equalsIgnoreCase(GENDER_FEMALE));
} else {
genderMaleButton.setChecked(false);
genderFemaleButton.setChecked(false);
}
if (age > 0) {
ageEditText.setText(Integer.valueOf(age).toString());
}
}
private void refreshUserProfile() {
ParseInstallation.getCurrentInstallation().refreshInBackground(
new RefreshCallback() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
displayUserProfile();
}
}
});
}
}
Please help me in solving this issue as I googled a lot but haven’t found anything good solution.Any help will be appreciated.
Thanks.

List ImageView repeating same image when shared

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.

Android TextView doesn't update

I am developing an Android app. Please see the Java code below. Can you please explain why textView doesn't update at specific lines in code but updates at others. I have them commented in the code.
I have updated the code see below.
The idea is to get a facebook profile from a server. When profiling_status equals 2 means that the profile is not ready, so I'll just ping the server until I get profiling_status != 2..
I tried the progress dialog thingy but gave up cause I put my activity in a thread, but then I couldn't get some information because I should have run it in nonUIThread.. Tried that but I failed and I lost patience.. so decided that while I ping the server I should just print "Loading profile. Please wait." No mess, no fuss! Only as said, textView doesn't update. Interestingly enough.. System.out.println("Here"); gets executed. I am running it only on AVD at the moment cause the server is not on the wireless network so I can't use a mobile phone to test it.
public class SelectionFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView userNameView;
private UiLifecycleHelper uiHelper;
private static final int REAUTH_ACTIVITY_CODE = 100;
private TextView textView;
private String username = null;
Context context;
JSONObject json = null;
JSONObject json_facebook = null;
int time = 0;
int time_interval = 3000;
int profiling_status = 2;
String logincode;
String usermessage = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void deleteProfile() throws JSONException {
IDThiefHTTPRequest.deleteProfile();
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
//Facebook logout
Session session2 = Session.getActiveSession();
if (session2 != null) {
session2.close();
}
else {
session2 = new Session(context);
Session.setActiveSession(session2);
session2.close();
}
}
private String readRiskScoreArray(JSONArray json_riskscore) throws NumberFormatException, JSONException{
//get the risk score with only two digits
double risk_score = Double.valueOf(json_riskscore.get(0).toString());
String risk_score2digits = new DecimalFormat("##.##").format(risk_score);
String usermessage = "Your risk score is: ";
usermessage = usermessage + risk_score2digits;
usermessage = usermessage + " which is ranked as: ";
usermessage = usermessage + json_riskscore.get(2).toString();
JSONArray json_reasons = json_riskscore.getJSONArray(1);
for (int i = 0; i < json_reasons.length(); i++){
JSONArray json_reason = json_reasons.getJSONArray(i);
JSONArray json_reasondetails = json_reason.getJSONArray(1);
usermessage = usermessage + "\n\nReason: ";
usermessage = usermessage + json_reasondetails.get(0);
usermessage = usermessage + "\n\nIDThief suggests you to: ";
usermessage = usermessage + json_reasondetails.get(1);
usermessage = usermessage + "\n\nFix it through this link:\n";
usermessage = usermessage + json_reasondetails.get(2);
}
return usermessage;
}
private void displayProfileInfo() throws JSONException {
Session session = Session.getActiveSession();
if (session.isOpened()) {
System.out.println(session.getAccessToken());
}
if (username != null) {
System.out.println("Login stage: Getting profile info for user:" + username);
logincode = username + "!" + session.getAccessToken();
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
System.out.println(json.toString(4));
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
if (profiling_status == 2) {
try {
while (profiling_status == 2 && time < 100000) {
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText("Loading profile. Please wait.");
System.out.println("Here");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
}
if (time >= 100000) {
System.out.println("Time is out");
textView.setText("Server is not responding. Please try again later.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
JSONArray json_riskscore = json_facebook.getJSONArray("risk_score");
System.out.println(json_riskscore.toString(4));
usermessage = readRiskScoreArray(json_riskscore);
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText(usermessage);
}
else System.out.println("username is null");
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection,
container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button deletebutton = (Button) view.findViewById(R.id.ImageButton2);
deletebutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
deleteProfile();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Button button = (Button) view.findViewById(R.id.ImageButton1);
textView = (TextView) view.findViewById(R.id.profiletext);
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setMovementMethod(LinkMovementMethod.getInstance());
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
displayProfileInfo();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
// Check for an open session
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
return view;
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
username = user.getUsername();
//System.out.println("Log in=====================================");
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
makeMeRequest(session);
}
else if (session != null && session.isClosed()) {
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
}
I thing your username is a string . Normally it will be so use !username.equals() dont use != in string comparison. that code may not get executed
if (username != null || !username.equals("")) {
//to do
}
Try out as below to compare the string do not use == use equalsIgnoreCase() or equals() method.
if (profiling_status.equalsIgnoreCase("2")) {
//would not update here either
try {
while (profiling_status.equalsIgnoreCase("2") && time < 100000) {
textView.setText("Loading profile. Please wait.");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
e.printStackTrace();
}

Categories

Resources