is it possible to get all of my users without adding them to through contacts. My problem is that I store users in Firebase and they can have invisible profile. I need to get only users with visible profiles. How can I achieve this?
Thanks
You can use the below method code for getting all the user users .You need to pass the users of set type then you will get the response in if(!TextUtils.isEmpty(response)){
public String postUserDetailsByUserIds(Set<String> userIds) {
try {
HttpRequestUtils httpRequestUtils = new HttpRequestUtils(this);
final String userDetailsUrl = "https://apps.applozic.com/rest/ws/user/detail";
if (userIds !=null && userIds.size()>0 ) {
List<String> userDetailsList = new ArrayList<>();
String response = "";
int count = 0;
for (String userId : userIds) {
count++;
userDetailsList.add(userId);
if( count% 60==0){
UserDetailListFeed userDetailListFeed = new UserDetailListFeed();
userDetailListFeed.setContactSync(true);
userDetailListFeed.setUserIdList(userDetailsList);
String jsonFromObject = GsonUtils.getJsonFromObject(userDetailListFeed, userDetailListFeed.getClass());
Log.i(TAG,"Sending json:" + jsonFromObject);
response = httpRequestUtils.postData(userDetailsUrl + "?contactSync=true", "application/json", "application/json", jsonFromObject);
userDetailsList = new ArrayList<String>();
if(!TextUtils.isEmpty(response)){
List<UserDetail> userDetails = (List<UserDetail>) GsonUtils.getObjectFromJson(response, new TypeToken<List<UserDetail>>() {}.getType());
for (UserDetail userDetail : userDetails) {
//Here you will get the user details
Log.i("UserDeatil","userId:"+userDetail.getUserId()) ;
Log.i("UserDeatil","display name:"+userDetail.getDisplayName()) ;
Log.i("UserDeatil","image link:"+userDetail.getImageLink()) ;
Log.i("UserDeatil","phone number:"+userDetail.getPhoneNumber()) ;
}
}
}
}
if(!userDetailsList.isEmpty()&& userDetailsList.size()>0) {
UserDetailListFeed userDetailListFeed = new UserDetailListFeed();
userDetailListFeed.setContactSync(true);
userDetailListFeed.setUserIdList(userDetailsList);
String jsonFromObject = GsonUtils.getJsonFromObject(userDetailListFeed, userDetailListFeed.getClass());
response = httpRequestUtils.postData(userDetailsUrl + "?contactSync=true", "application/json", "application/json", jsonFromObject);
Log.i(TAG, "User details response is :" + response);
if (TextUtils.isEmpty(response) || response.contains("<html>")) {
return null;
}
if (!TextUtils.isEmpty(response)) {
List<UserDetail> userDetails = (List<UserDetail>) GsonUtils.getObjectFromJson(response, new TypeToken<List<UserDetail>>() {}.getType());
for (UserDetail userDetail : userDetails) {
//Here you will get the user details
Log.i("UserDeatil","userId:"+userDetail.getUserId()) ;
Log.i("UserDeatil","display name:"+userDetail.getDisplayName()) ;
Log.i("UserDeatil","image link:"+userDetail.getImageLink()) ;
Log.i("UserDeatil","phone number:"+userDetail.getPhoneNumber()) ;
} }
}
return response;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Related
I'm a in the process of understanding CouchBase Lite for android application,as far i only know how to create a manager, database, document and view.However i want to load data from the documents and show it in the app but failed after trying several times and following some tutorials.Is there a way i can save and load this data and manipulate it in Listview? The code i used til now is the following:
public class MainActivity extends AppCompatActivity {
final String dbname = "userdils";
private String docId = "2";
private Manager manager;
private Database couchDb;
private TextView tvLogWindow;
private EditText u_id;
private EditText pwd;
Button btn_login,btn_login1;
TextView version;
private String TAG = "CouchBaseLiteLoginPage";
String email;
String password;
private UserDetails ud,udd;
private ArrayList<UserDetails> ud1;
String doc_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//tvLogWindow = (TextView) findViewById(R.id.tv_log_window);
u_id = (EditText) findViewById(R.id.user_id);
pwd = (EditText) findViewById(R.id.password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login1 = (Button) findViewById(R.id.btn_login1);
/*tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nStart Couchbase App!");
if (!Manager.isValidDatabaseName(dbname)) {
tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nBad couchbase db name!");
return;
}*/
createManager();
createCouchdb();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.d(TAG, "Create: " + 1);
login();
}
});
btn_login1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
Log.d(TAG, "View: " + 2);
docView();
// retrieveMovie(manager,couchDb,docId);
}
});
//createDocument(docId);
//Document retrievedDocument = retrieveDocument();
/*updateDocument(retrievedDocument);
deleteDocument(retrievedDocument);*/
//tvLogWindow.setText(tvLogWindow.getText().toString() + "\n\nEnd the App!");
}
public void createManager() {
try {
manager = new Manager(new AndroidContext(getApplicationContext()), Manager.DEFAULT_OPTIONS);
} catch (IOException e) {
return;
}
}
public void createCouchdb() {
try {
couchDb = manager.getDatabase(dbname);
} catch (CouchbaseLiteException e) {
return;
}
}
public Document retrieveDocument(String docId) {
Document retrievedDocument = couchDb.getDocument(docId);
Log.d(TAG, "Retrieved Data:- " + String.valueOf(retrievedDocument.getProperties()));
// Let's find the documents that have conflicts so we can resolve them:
Query query = couchDb.createAllDocumentsQuery();
query.setAllDocsMode(Query.AllDocsMode.ALL_DOCS);
try {
QueryEnumerator result = query.run();
for (Iterator<QueryRow> it = result;
it.hasNext(); ) {
QueryRow row = it.next();
Object movieObj = row.getDocument().getProperties().get("user_det");
Gson gson = new Gson();
String jsonString = gson.toJson(movieObj, Map.class); //Convert the object to json string using Gson
UserDetails movie = gson.fromJson(jsonString, UserDetails.class); //convert the json string to Movie object
if(movie.getUser_pwd().equals("000000")) {
Log.i("getMovieFromDocument", "movie>>>" + movie.getUser_nm());
}
Log.d(TAG, "Document Data ID:- " + row.getDocumentId());
}
}
catch (CouchbaseLiteException e) {
}
// Log.d(TAG, "User Name:- " +(String)retrievedDocument.getProperty("user_det"));
return retrievedDocument;
}
public void login() {
Log.d(TAG, "validate: " + 4);
email = u_id.getText().toString().trim();
password = pwd.getText().toString().trim();
Log.d(TAG, "login: " + 5);
btn_login.setEnabled(false);
ud = new UserDetails();
udd = new UserDetails();
ud1 = new ArrayList<UserDetails>();
ud.setUser_nm(email);
ud.setUser_pwd(password);
udd.setUser_nm("NAME_007");
udd.setUser_pwd("PWD_007");
ud1.add(ud);
ud1.add(udd);
createDocument(docId,ud1);
}
public void createDocument(String docId,ArrayList<UserDetails> ud) {
// create some dummy data
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Calendar calendar = GregorianCalendar.getInstance();
String currentTimeString = dateFormatter.format(calendar.getTime());
//Movie movie = new Movie("Star War", "The force awakens!", 120);
// put those dummy data together
Map<String, Object> docContent = new HashMap<String, Object>();
docContent.put("message", "Hey Couchbase Lite");
docContent.put("creationDate", currentTimeString);
docContent.put("user_det", ud);
//docContent.put("movie", movie);
Log.d(TAG, "userDetails: " + String.valueOf(docContent));
// create an empty document, add content and write it to the couchDb
//Document document = new Document(couchDb,docId);
//Document document = couchDb.createDocument();
Document document = new Document(couchDb,docId);
try {
document.putProperties(docContent);
//doc_id = document.getId();
// Document retrieveDoc = retrieveDocument(docId);
Log.d(TAG, "Document Count couchDb : " + couchDb.getDocumentCount());
} catch (CouchbaseLiteException e) {
}
}
public void docView() {
// Document retrievedDocument = retrieveDocument(docId);
Document retrievedDocument = retrieveDocument(docId);
}
private void retrieveMovie(Manager manager, Database couchDb, String docId) {
Document retrievedDocument = couchDb.getDocument(docId); // Retrieve the document by id
Object movieObj = retrievedDocument.getProperties().get("user_det");
Gson gson = new Gson();
String jsonString = gson.toJson(movieObj, Map.class); //Convert the object to json string using Gson
UserDetails movie = gson.fromJson(jsonString, UserDetails.class); //convert the json string to Movie object
Log.i("getMovieFromDocument", "jsonString>>>" + jsonString);
Log.i("getMovieFromDocument", "movie>>>" + movie.getUser_nm());
}
}
Not clear what tutorials you followed and what errors you observed. Anyways, check out this blog that discusses how you can load documents within a RecyclerView with Couchbase Lite as a data source. The recommended pattern can be easily applied to ListView or just use a RecyclerView instead of a ListView in your app.
I want to save the ArrayList thatt is formed using getter and setter when I run my AsyncTask first time. It fetches json data and I uses that via getter and setter.
Now I have three sorting buttons. I want when first time date is populated it gets stored and I can apply sorting on array list and pass that sorted list to post execute.
What I did - used a boolen var to know if it's first run and modify it accordingly. I globally defined my array list and model.
Following is doInBackground()
protected List<service_detail_model> doInBackground(String... strings) {
serviceModelList = new ArrayList<>();
if (!dataSet) {
dataSet=true;
ServiceURL = ServiceURL + "type=" + type + "&city=" + city + "&orderby=" + orderby + "&origin=" + origin;
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(ServiceURL);
Log.e("kkkk", jsonStr);
if (jsonStr != null) {
try {
JSONArray listArray = new JSONArray(jsonStr);
for (int i = 0; i < listArray.length(); i++) {
JSONObject serviceObject = listArray.getJSONObject(i);
serviceModel = new service_detail_model();
serviceModel.setName(serviceObject.getString("name"));
serviceModel.setPhone(serviceObject.getString("phone"));
serviceModel.setImage(serviceObject.getString("img"));
serviceModel.setPer(serviceObject.getString("per"));
serviceModel.setPrice(serviceObject.getInt("price"));
serviceModel.setRating(serviceObject.getInt("rating"));
serviceModel.setDist(serviceObject.getInt("dist"));
serviceModelList.add(serviceModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
else{
if (orderby.equals("location")) {
Log.e("ll", String.valueOf(serviceModelList.get(0).getDist()));
Collections.sort(serviceModelList, new Comparator<service_detail_model>() {
#Override
public int compare(service_detail_model o1, service_detail_model o2) {
return o1.getDist() - o2.getDist();
}
});
}
else if (orderby.equals("price")) {
Collections.sort(serviceModelList, new Comparator<service_detail_model>() {
#Override
public int compare(service_detail_model o1, service_detail_model o2) {
return o1.getPrice() - o2.getPrice();
}
});
}
else if (orderby.equals("rating")) {
Collections.sort(serviceModelList, new Comparator<service_detail_model>() {
#Override
public int compare(service_detail_model o1, service_detail_model o2) {
return (int) (o1.getRating()*100 - o2.getRating()*100);
}
});
}
}
return serviceModelList;
}
When I did debugging I found that list size is 0.
I am trying to implement multiple concurrent file uploads using IntentService for which I am using ThreadExecutor. I am iterating through a map and one-by-one and I am fetching the information and instantiating a workerthread. Inside the loop I have executor which is executing those threads. Below is my code.
#Override
protected void onHandleIntent(Intent intent) {
Debug.print("Called handleIntent");
mFileMap = (HashMap<String, Integer>) intent.getSerializableExtra("pdf_info");
mMapSize = mFileMap.size();
Log.e("pdf", mFileMap.toString());
mExecutor = Executors.newFixedThreadPool(2);
mTotalFileSize = getTotalFileSize();
Log.e("total_file_size", mTotalFileSize + "");
ArrayList<UploadWorker> uploadWorkerArrayList = new ArrayList<>();
Iterator it = mFileMap.entrySet().iterator();
for(Map.Entry<String, Integer> entry : mFileMap.entrySet())
{
String filePath = (String) entry.getKey();
Log.e("map_path: ", filePath);
int categoryId = (int) entry.getValue();
Log.e("map_no: ", categoryId + "");
// uploadWorkerArrayList.add(new UploadWorker(filePath, categoryId));
UploadWorker worker = new UploadWorker(filePath, categoryId);
mExecutor.submit(worker);
}
mExecutor.shutdown();
Log.e("workerlist: ", uploadWorkerArrayList.toString());
}
Below is my UploadWorker code.
class UploadWorker implements Runnable {
String filePath;
int categoryId;
public UploadWorker(String filePath, int categoryId) {
this.filePath = filePath;
this.categoryId = categoryId;
}
#Override
public synchronized void run() {
mFile = new File(filePath);
Log.e("uploadworker", filePath);
mParams = new LinkedHashMap<>();
mParams.put("file_type", 2 + "");
mParams.put("file_name", mFile.getName());
mParams.put("category_id", categoryId + "");
notificationId++;
mNotificationMap.put(filePath, notificationId);
createNotification(notificationId, mFile.getName());
int response = uploadPDF(filePath);
if (response == 1) {
JSONObject jObject = null;
String status = null;
try {
jObject = new JSONObject(mServerResponse);
status = jObject.getString("status");
int id = mNotificationMap.get(filePath);
updateNotification(100, id);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("<><>", status);
} else {
Log.e("<><>", "Upload fail");
}
}
}
However it happens that if say my maplist has 2 entries, then the iterator is first fetching both the entries and the executor is uploading only the final entry, that too twice. Please help.
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 .
I am working on an instant messaging android application . I have successfully implemented the chat between my application and web application .I have used compile 'io.socket:socket.io-client:0.6.2' library to implement this. But when i installed the same app on another mobile phone, device to device communication did not work. I think i am missing something here. What i have to implement in my app now. Broadcast Receiver or GCM(Google Cloud Messaging). My code is as below:
1. ChatActivity.java
public class ChatActivity extends Activity {
public static final String TAG = ChatActivity.class.getSimpleName();
EditText 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 MessagesListAdapter adapter;
private List<Message> listMessages;
private ListView listViewMessages;
boolean isSelf = false; // to check whether the message is owned by you or not.true means message is owned by you .
Message msg;
int loggedInUserID;
private String URL_FEED_Message = "";
APIConfiguration apiConfiguration;
{
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);
almaChatDatabase = new AlmaChatDatabase(getApplicationContext());
loggedInUserID = almaChatDatabase.getUserID(); // Getting ID of the Logged in user from the database
Log.e("UserID", "Id of Logged in user " + loggedInUserID);
listMessages = new ArrayList<Message>();
adapter = new MessagesListAdapter(getApplicationContext(), listMessages);
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 = 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 = (EditText) 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) {
//mSocket.emit("subscribe", md5String);
message = edMessage.getText().toString().trim();
Log.e("message", 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();
}
});
}
}
});
}
//Adding message in the arrayList
public void attemptToSend(String senderName, String message, boolean isSelf) {
msg = new Message(senderName, message, isSelf);
listMessages.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", "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 = message.getString("text");
Log.e("Message Received", messageReceived);
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 Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
playBeep();
} else {
isSelf = false;
msg = new Message(senderName, messageReceived, isSelf);
listMessages.add(msg);
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 = 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 Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
//playBeep();
} else {
JSONObject jsonMessage = jsonObject.getJSONObject("message");
String message = jsonMessage.getString("text");
isSelf = false;
msg = new Message(userName, message, isSelf);
listMessages.add(msg);
adapter.notifyDataSetChanged();
// playBeep();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// notify data changes to list adapter
//adapter.notifyDataSetChanged();
}
}
}
2.Constants.java
public class Constants {
public static final String CHAT_SERVER_URL = "http://192.168.2.250:3000/";
}
Everything is working her except device to device communication. I am able to send messages from my app to web app and also receiving messages from web App. But device to device communication is not working. Please help me to fix the issue.