make phone call when specific notification arrive [duplicate] - java

This question already has answers here:
Android: Make phone call from service
(2 answers)
Closed 6 months ago.
i'm trying to make a phone call, when a specific notification arrive,
i use Notification Service Listener to read incoming notificaion,
public void onNotificationPosted(StatusBarNotification sbn) {
// if(if this is my notificaion..){
String name = sbn.getNotification().extras.getCharSequence(Notification.EXTRA_TITLE));
List<String> numbers = getPhoneNumbers(name);
Log.d(TAG, "i have all this numbers - " + numbers.toString());
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + numbers.get(1)));
startActivity(intent);
}
the "getPhoneNumbers" method is this one
public List<String> getPhoneNumbers(String name) {
List<String> numbers = new ArrayList<String>();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + name + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// Get all phone numbers.
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
numbers.add(number);
}
phones.close();
}
cursor.close();
return numbers;
}
all work fine, ( i used break points to cheak everything...)
the "if this is my notification" work perfect, i get the name from the sbn extras, the 'numbers' arraylist include all the contact numbers after the "getPhoneNumbers" method used, but when i start the intent nathing happend..
what is my problem? :/

Let's clarify:
Problem
Your onNotificationPosted method does not launch a phone call when calling startActivity(intent);.
Why
NotificationListenerService is not an activity.
Solution
Make your MainActivity call the startActivity(intent);.
How
Define an attribute activity in NotificationListenerService and define a constructor that accepts an activity:
NotificationListenerService.java
// define attribute activity:
MainActivity activity;
public NotificationListenerService(MainActivity activity) {
this.activity = activity;
}
MainActivity.java
// create a NotificationListenerService sending itself as reference
NotificationListenerService nls = new NotificationListenerService(this);
Then inside the onNotificationPosted you will see the attribute, so you can:
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ numbers.get(1)));
activity.startActivity(intent);

Related

Send String from Edittext on 1st Activity to the Edittext on the 2nd Activity

I have some string that i write into the Edittext on my first activity and im trying to send it to the Edittext on the other activity by pressing Button, but my code does not work, nothing happen and i dont know what else can i do here maybe somebody could help me out
My onClick method at 1st activity:
public void calendarOR(View v, AdapterView<?> parent, int position, long id) {
String data = cala.getText().toString();
Intent intent = new Intent(getApplicationContext(), calendar.class);
intent.putExtra("id",data);
startActivity(intent);
My second activity code:
Bundle extras = getIntent().getExtras();
if (extras != null) {
userId = extras.getLong("id");
}
if (userId > 0) {
userCursor = db.rawQuery("select * from " + dbelper.TABLE + " where " + dbelper.COLUMN_ID + "=?", new String[]{String.valueOf(userId)});
userCursor.moveToFirst();
date.setText(userCursor.getString(1));
userCursor.close();
}
You are putting a String data type and trying to get a long. Change the second activity to get the "id" as a string.
userId = extras.getString("id");
then
if (userId != null) {
userCursor = db.rawQuery("select * from " + dbelper.TABLE + " where " + dbelper.COLUMN_ID + "=?", new String[]{userId});
userCursor.moveToFirst();
date.setText(userCursor.getString(1));
userCursor.close();
}
You may also want to print log messages if userId is null or the data is not in the database to help with debugging.
Unrelated, but you may want to change your intent to not use the application context, like this, to launch the calendar activity.
Intent intent = new Intent(this, calendar.class);
do this in second activity code:
String data =getIntent().getStringExtra("id");

How to get the numeric value from intent extra String

I'm using intent to pass the string value to next Activity where I use getStringExtra to get the Value. The value is is User Contact no. in 10 digit which is in numeric value. when I setText in textview then It display the correct format but when I use intent on onclicklistener to open dialpad then instead of no, some random no. appears and in 4 digit also
Here I use to pass string
intent.putExtra(MOBILE, g.getSellermobile());
and I receive it by
tutor_mobile = intent.getStringExtra(MOBILE);
when I set it in textview as
TextView contact = (TextView) findViewById(R.id.tutor_near);
contact.setText(tutor_mobile);
It display correct format eg 9868336847
but when I use intent to open dialpad as
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
I'm using below code to get the mobile no.
etMobile = (EditText) findViewById(R.id.user_mobile);
String sellermobile = etMobile.getText().toString();
and In class file I have
package com.nepalpolice.filmyduniya.maincategory;
public class location {
public String sellermobile;
// public Uri uri;
public location( String sellermobile) {
this.sellermobile = sellermobile;
// this.uri = uri;
}
public String getSellermobile() { return sellermobile;}
}
}
Then in activity I have
public static final String MOBILE = "other_mobile";
and
intent.putExtra(MOBILE, g.getSellermobile());
and in next activity I have
tutor_mobile = intent.getStringExtra(MOBILE); and
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
Then random no. in 4 digit appears.
Then in activity I have
Please Help.
Your tutor_mobile is a String value, but thr you rearrange it toString:
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
May be it's not a error, but it's strange. And what do you want to display in dialpad?
try {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + "string format number"));
startActivity(callIntent);
} catch (Exception e) {
Log.d("Response", e.toString());
}

Recyclerview Adapter's notifyDataSetChanged not updating RecyclerView

I have a RecyclerView for chat app with firebase realtime database and local SQLite database. I am saving message into local database (SQLite) then calling adapter.notifyDataSetChanged().
If the message is already in the database (message unique id) then SQLite will return 0 on database insertOrThrow method. I am checking the availability like this.
if (id == 0) {
Log.d(TAG,"Database Already Has Value Of This Random Id ");
adapter.notifyDataSetChanged();
} else {
Chat_Wrapper chat_wrapper = new Chat_Wrapper(Chat_Msg, null, null, null, null, null, null, Chat_TimeStamp, UserPhone_Intent, UserImage_Intent, Chat_FROM, null,null,id);
message.add(chat_wrapper);
adapter.notifyDataSetChanged();
}
However, even the else statement is being called, my RecyclerView screen is not updated, but in the background, if I type or receive any message it saves into the local database but doesn't show on screen.
Chat RecyclerView works in following cases
When I clear app from recent app
Stop Fetching data from the local database
First Launch of Chat screen
I am facing this issue when I come directly to chat screen from notification.
That's How I load chat fragment normally.
getFragmentManager().beginTransaction().add(R.id.Navigation_Drawer, chatFragment).commit();
Loading Fragment from Notification using Asynctask
((Navigation_Drawer)context).getFragmentManager().beginTransaction().replace(R.id.Navigation_Drawer, chatFragment).commit();
That's how i launches ChatFragment from notification.
public class FireBase_Messaging_Service extends FirebaseMessagingService {
public static final String TAG="###FireBase MSG###";
public static final int NOTIFICATION=5;
String UserName;
String ID;
String Msg;
Map<String,String> data;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG,"From "+remoteMessage.getFrom());
if (remoteMessage.getData().size()>0){
data = remoteMessage.getData();
Log.d(TAG,"Message Data "+remoteMessage.getData());
data = remoteMessage.getData();
UserName = data.get("name");
ID = data.get("ID");
Msg = data.get("Message");
showNotification(Msg,ID,UserName);
}
if (remoteMessage.getNotification()!=null){
Log.d(TAG,"Message Notification Body "+remoteMessage.getNotification().getBody());
// Toast.makeText(this, "Notification "+remoteMessage.getNotification().getBody(), Toast.LENGTH_LONG).show();
}
}
private void showNotification(String Message,String ID,String UserName) {
Log.d(TAG,"Show Notification "+Message+" "+ID);
Intent intent=new Intent(this, Navigation_Drawer.class);
intent.putExtra("Type","Text");
//intent.putExtra("Type",MsgType);
intent.putExtra("ID",ID);
intent.putExtra("uname",UserName);
intent.putExtra("Message",Msg);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(this,NOTIFICATION,intent,PendingIntent.FLAG_UPDATE_CURRENT);
int color = getResources().getColor(R.color.black);
String ChannelID = "Message";
notificationChannel(ChannelID,"Chat");
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),ChannelID)
.setSmallIcon(R.drawable.default_x)
.setColor(color)
.setContentTitle(UserName)
.setContentText(Message)
.setChannelId(ChannelID)
.setTicker("My App")
.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.FLAG_SHOW_LIGHTS)
.setLights(0xff00ff00, 1000, 500) // To change Light Colors
.setStyle(new NotificationCompat.BigTextStyle().bigText(Message))//For Expandable View
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(NOTIFICATION,builder.build());
}
#Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
private void notificationChannel (String ChannelID, String channelName) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(ChannelID,channelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.setLightColor(Color.GREEN);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
}
I also noticed by logging that after adding data to list message.add(chat_wrapper) it first showing an increase in size but when while loop is over, it shows the last size of the ArrayList.
Here's the ChatFragment class.
public class Chat_Screen_Fragment extends Fragment implements View.OnClickListener, ChildEventListener{
public static final String TAG = "###CHAT SCREEN###";
List<Chat_Wrapper> message = new ArrayList<>();
Chat_Adapter adapter;
RecyclerView recyclerView;
LinearLayoutManager layoutManager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.chat_screen_main_fragment,container,false);
setRetainInstance(true);
// GET INTENT VALUES FROM USER PROFILE CLASS
UserName_Intent = getArguments().getString("Get_Name");
UserImage_Intent = getArguments().getString("Get_Image");
UserPhone_Intent = getArguments().getString("Get_Phone");
UserID_Intent = getArguments().getString("Get_ID");
FirebaseToken_Intent = getArguments().getString("Get_Token"); //Firebase Token of other person
Room_Name_Intent = getArguments().getString("Get_Other"); // Room Name of chat
UserLastSeen_Intent=getArguments().getString("LastSeen");
//Sender_FCMToken = Session.getFirebaseID();
// RECYCLER VIEW
recyclerView = v.findViewById(R.id.Chat_Screen_Message_List);
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
databaseReference = FirebaseDatabase.getInstance().getReference().child(Room_Name_Intent);
databaseReference.addChildEventListener(this);
adapter = new Chat_Adapter(getActivity(), message);
recyclerView.setAdapter(adapter);
// FETCH OLD MESSAGE FROM DATABASE
chatDatabase();
return v;
}
// FIREBASE REAL TIME DATABASE WHICH FETCH ALL MESSAGES (SYNC) FROM ONLINE DATABASE
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
append_chat_conversation(dataSnapshot);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
private synchronized void append_chat_conversation(DataSnapshot dataSnapshot) {
iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
// GETTING DATA FROM FIREBASE DATABASE
Chat_Msg = (String) ((DataSnapshot) iterator.next()).getValue();
Chat_FROM = (String) ((DataSnapshot) iterator.next()).getValue();
Chat_FROM_ID = (String) ((DataSnapshot) iterator.next()).getValue();
Chat_TO = (String) ((DataSnapshot) iterator.next()).getValue();
Chat_TimeStamp = (String) ((DataSnapshot) iterator.next()).getValue();
Chat_Type= (String) ((DataSnapshot) iterator.next()).getValue();
Random_ID=(String) ((DataSnapshot) iterator.next()).getValue();
Chat_FCM_FROM= (String) ((DataSnapshot) iterator.next()).getValue();
Chat_FCM_TO= (String) ((DataSnapshot) iterator.next()).getValue();
Log.d(TAG, "Chat Items " + Chat_Msg + " " + Random_ID);
Chat_Database tempChatDatabase = new Chat_Database(getActivity());
boolean hasValue = tempChatDatabase.CheckValueExist(Random_ID);
Log.d(TAG,"DATABASE ALREADY HAS VALUE OF TIMESTAMP= "+hasValue);
if (!hasValue) {
Log.d(TAG,"DATABASE DON'T HAVE SAME ENTRY FOR TIME STAMP. ENTERED INTO HAS VALUE");
Log.d(TAG,"Chat Message "+Chat_Msg);
if (Chat_Type.equals("Typed_Message")) {
Log.d(TAG, "VIEW TYPE IS Message " + Chat_Msg);
long id = chat_database.Insert_Chat(Session.getUserID(),Room_Name_Intent, UserID_Intent, "Text", Chat_Msg, Chat_FROM, Chat_TO, Chat_TimeStamp, Chat_FCM_FROM, Chat_FCM_TO, Session.getPhoneNO(), UserPhone_Intent,Random_ID,UserImage_Intent,UserLastSeen_Intent,Chat_FROM_ID);
//Adding Chat Data Into Database
Log.d(TAG,"Database Entry ID "+id);
if (id == 0) {
Log.d(TAG,"Database Already Has Value Of This Random Id ");
adapter.notifyDataSetChanged();
continue;
} else {
Log.d(TAG,"Database Don't Has Value Of This Random Id ");
Log.d(TAG,"Message Size "+message.size());
Chat_Wrapper chat_wrapper = new Chat_Wrapper(Chat_Msg, null, null, null, null, null, null, Chat_TimeStamp, UserPhone_Intent, UserImage_Intent, Chat_FROM, null,null,id);
message.add(chat_wrapper);
Log.d(TAG,"Message Size "+message.size());
adapter.notifyDataSetChanged();
Log.d(TAG,"Adapter Notified Data Set "+adapter.getItemCount());
recyclerView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Moving to Bottom");
recyclerView.smoothScrollToPosition(adapter.getItemCount());
}
});
}
}
Log.d(TAG, "MESSAGE ARRAY SIZE " + message.size());
chat_database.isDatabaseClose();
}
private void chatDatabase(){
//Database Init and Filling Adapter
Log.d(TAG,"Chat Database Function");
chat_database=new Chat_Database(getActivity());
chatCursor=chat_database.getUserChat(UserID_Intent);
boolean checkDB_Exist=functions.DatabaseExist(getActivity(),"CHAT_DATABASE.DB");
boolean chatItemsCounts=chatCursor.getCount()>0;
chatCursor.moveToFirst();
Log.d(TAG,"Value At Chat Database "+ checkDB_Exist+" "+chatItemsCounts);
if (checkDB_Exist && chatCursor.getCount()>0 && chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_USER_ID")).equals(UserID_Intent)){
Log.d(TAG,"Database Exist Chat Database");
message.clear();
chatCursor.moveToFirst();
do {
database_rowID=chatCursor.getInt(chatCursor.getColumnIndex("ID"));
database_userID=chatCursor.getString(chatCursor.getColumnIndex("USER_ID"));
database_RoomName =chatCursor.getString(chatCursor.getColumnIndex("ROOM_NAME"));
database_ReceiverID=chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_USER_ID"));
database_MessageType=chatCursor.getString(chatCursor.getColumnIndex("MESSAGE_TYPE"));
database_Message=chatCursor.getString(chatCursor.getColumnIndex("USER_MESSAGE"));
database_MsgFrom=chatCursor.getString(chatCursor.getColumnIndex("SENDER_NAME"));
database_MsgTo=chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_NAME"));
database_TimeStamp=chatCursor.getString(chatCursor.getColumnIndex("TIME_STAMP"));
database_FCMfrom=chatCursor.getString(chatCursor.getColumnIndex("SENDER_TOKEN"));
database_FCMto=chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_TOKEN"));
database_LocalPath=chatCursor.getString(chatCursor.getColumnIndex("DOWNLOADED_AT"));
database_PhoneFrom=chatCursor.getString(chatCursor.getColumnIndex("MY_PHONE"));
database_PhoneTo=chatCursor.getString(chatCursor.getColumnIndex("OTHER_PHONE"));
Log.d(TAG,"Value Of Database Message String = "+database_Message);
Log.d(TAG,"Row ID of Database "+database_rowID);
// Check Message Type
Log.d(TAG,"Message Type Is Text");
Chat_Wrapper text = new Chat_Wrapper(database_Message, null, null, null, null, null, null, database_TimeStamp, database_PhoneTo, UserImage_Intent, database_MsgFrom,null,null,database_rowID);
message.add(text);
}
while(chatCursor.moveToNext());
Room_Name_Intent = database_RoomName;
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter.notifyDataSetChanged();
chatCursor.close();
boolean value = chat_database.isDatabaseClose();
recyclerView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Moving to Bottom");
recyclerView.smoothScrollToPosition(message.size()-1);
}
});
Log.d(TAG,"Value Of Database Close or Not "+value);
}
}
}
I think you need to implement the LoaderCallbacks here and to listen to the changes done in the database to update the RecyclerView accordingly. I have created a repository in Github here which shows the database read, write and update and making the changes in the database to have the proper effect in corresponding RecyclerView with registering a content observer to the database.
The whole idea is to have an observer attached to your database table which will notify you of any change in the table. When a change is detected the database read query will be generated automatically and on reloading the data again from your table will trigger the RecyclerView update inside onLoadFinished function.
I have a demo implementation in my Github project, which shows a list of users to be shown in a RecyclerView and updating the RecyclerView automatically without calling notifyDataSetChanged. Please check the adapter which controls the data to be shown in the RecyclerView again. This is the simplest implementation that you might have in your case avoiding any complexity.
Hope that helps.
Update
After going through the code, I have come up with some fixes that you should do. It is pretty difficult to understand why it is not working as you expected it to be because the code given is not very well formatted and complete. However, I can suggest you some key fixes here which might help.
In the append_chat_conversation function, you do not have to call notifyDataSetChanged each time you find a new chat message and add that to the message. I would like to suggest that, do not add the chat messages in your message list. You might get rid of the following if-else block. Just updating the chat database and inserting new chat messages into it is fine. So I would suggest you remove the following section.
if (id == 0) {
Log.d(TAG,"Database Already Has Value Of This Random Id ");
adapter.notifyDataSetChanged();
continue;
} else {
Log.d(TAG,"Database Don't Has Value Of This Random Id ");
Log.d(TAG,"Message Size "+message.size());
Chat_Wrapper chat_wrapper = new Chat_Wrapper(Chat_Msg, null, null, null, null, null, null, Chat_TimeStamp, UserPhone_Intent, UserImage_Intent, Chat_FROM, null,null,id);
message.add(chat_wrapper);
Log.d(TAG,"Message Size "+message.size());
adapter.notifyDataSetChanged();
Log.d(TAG,"Adapter Notified Data Set "+adapter.getItemCount());
recyclerView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Moving to Bottom");
recyclerView.smoothScrollToPosition(adapter.getItemCount());
}
});
}
Call chatDatabase function before this line to load messages from the database.
// FETCH MESSAGE FROM DATABASE
chatDatabase();
Log.d(TAG, "MESSAGE ARRAY SIZE " + message.size());
chat_database.isDatabaseClose();
Now fix your chatDatabase function. You are creating a new LinearLayoutManager and assigning it to your RecyclerView each time you are calling the chatDatabase function. I would suggest removing it as well.
Modify your chatDatabase function like the following.
private void chatDatabase() {
//Database Init and Filling Adapter
Log.d(TAG, "Chat Database Function");
chat_database = new Chat_Database(getActivity());
chatCursor = chat_database.getUserChat(UserID_Intent);
boolean checkDB_Exist = functions.DatabaseExist(getActivity(), "CHAT_DATABASE.DB");
boolean chatItemsCounts = chatCursor.getCount() > 0;
chatCursor.moveToFirst();
Log.d(TAG, "Value At Chat Database " + checkDB_Exist + " " + chatItemsCounts);
if (checkDB_Exist && chatCursor.getCount() > 0 && chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_USER_ID")).equals(UserID_Intent)) {
Log.d(TAG, "Database Exist Chat Database");
message.clear();
chatCursor.moveToFirst();
do {
database_rowID = chatCursor.getInt(chatCursor.getColumnIndex("ID"));
database_userID = chatCursor.getString(chatCursor.getColumnIndex("USER_ID"));
database_RoomName = chatCursor.getString(chatCursor.getColumnIndex("ROOM_NAME"));
database_ReceiverID = chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_USER_ID"));
database_MessageType = chatCursor.getString(chatCursor.getColumnIndex("MESSAGE_TYPE"));
database_Message = chatCursor.getString(chatCursor.getColumnIndex("USER_MESSAGE"));
database_MsgFrom = chatCursor.getString(chatCursor.getColumnIndex("SENDER_NAME"));
database_MsgTo = chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_NAME"));
database_TimeStamp = chatCursor.getString(chatCursor.getColumnIndex("TIME_STAMP"));
database_FCMfrom = chatCursor.getString(chatCursor.getColumnIndex("SENDER_TOKEN"));
database_FCMto = chatCursor.getString(chatCursor.getColumnIndex("RECEIVER_TOKEN"));
database_LocalPath = chatCursor.getString(chatCursor.getColumnIndex("DOWNLOADED_AT"));
database_PhoneFrom = chatCursor.getString(chatCursor.getColumnIndex("MY_PHONE"));
database_PhoneTo = chatCursor.getString(chatCursor.getColumnIndex("OTHER_PHONE"));
Log.d(TAG, "Value Of Database Message String = " + database_Message);
Log.d(TAG, "Row ID of Database " + database_rowID);
// Check Message Type
Log.d(TAG, "Message Type Is Text");
Chat_Wrapper text = new Chat_Wrapper(database_Message, null, null, null, null, null, null, database_TimeStamp, database_PhoneTo, UserImage_Intent, database_MsgFrom, null, null, database_rowID);
message.add(text);
} while (chatCursor.moveToNext());
Room_Name_Intent = database_RoomName;
adapter.setChatMessages(message); // Add a public function in your adapter to set the chat messages
adapter.notifyDataSetChanged();
chatCursor.close();
boolean value = chat_database.isDatabaseClose();
recyclerView.post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Moving to Bottom");
recyclerView.smoothScrollToPosition(message.size() - 1);
}
});
Log.d(TAG, "Value Of Database Close or Not " + value);
}
}
The setChatMessages function in your adapter will look something like this.
public void setChatMessages(ArrayList<Message> messageList) {
this.message = messageList;
}
I solved this issue by digging bit into android lifecycle. As i mentioned above i am facing this issue only when i enter ChatFragment from notification. I was only activity state issue. Code was working. What i was doing i always recreate activity on notification tap ( In Firebase Code ).
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
After digging lots of code and changing multiple flags in Intent. Only android:launchMode="singleTask" solves my issue. Which only create activity if it's not exist. Now its not calling activity onDestroy method when tapping on notification. It's start activity from onStart which avoid activity to recreate.
I add this flag in AndroidManifest's NavigationDrawer activity tag.
<activity
android:name=".Navigation_Drawer"
android:launchMode="singleTask"
android:theme="#style/AppTheme"/>
These kind of issue is really headache for developers but i don't know that with this single line of code i can solve this issue. Thanks everyone for help.

How to add Recent queries to another activity

I am creating searchable dictionary and I want to display the most recent queries that user does in SearchView to other activity. just Like Recent option in android dictionaries.
private void handleIntent(Intent inent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
// handles a click on a search suggestion; launches activity to show word
Intent wordIntent = new Intent(this, WordActivity.class);
wordIntent.setData(intent.getData());
startActivity(wordIntent);
finish();
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// handles a search query
String query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions=new SearchRecentSuggestions(this, MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
showResults(query);
}
}
The ShowResult shows the query suggestions in the search activity, i want to show the recent queries into an other activity, how can i do this?
May be this code will help you with Shared Preference .
SharedPreferences sPreferences = getSharedPreferences("tushar", Context.MODE_PRIVATE);
Editor sEditor = sPreferences.edit();
Set<String> setName = new HashSet<String>();
setName.add("tushar");
setName.add("pandey");
setName.add("Ram");
setName.add("Shiva");
sEditor.putStringSet("ko", setName);
sEditor.commit() ;
Log.i("hello","tushar:pandey") ;
Set<String> setName_ = sPreferences.getStringSet("tushar", setName);
Log.i(setName_.toString(),"tushar:pandey") ;
Is possible to access saved queries through ContentResolver:
ContentResolver contentResolver = getApplicationContext().getContentResolver();
String contentUri = "content://" + MySuggestionProvider.AUTHORITY + '/' + SearchManager.SUGGEST_URI_PATH_QUERY;
Uri uri = Uri.parse(uriStr);
Cursor cursor = contentResolver.query(uri, null, null, new String[] { null }, null);
Now with received cursor populate a ListView. Create another activity using showResults() code.

Android - How to get a contact from call log?

I am trying to get contacts from call log. I can get the contact numbers from main contacts using this code :
public void getContacts(View view) {
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intentContact, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0)
{
try {
to.setText(getContactInfo(intent));
} catch(NullPointerException e) {
// Do nothing ;)
}
}
}
protected String getContactInfo(Intent intent)
{
String phoneNumber = to.getText().toString();
Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
if(phoneNumber.endsWith(">"))
phoneNumber += ", "+name;
else
phoneNumber += name;
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if ( hasPhone.equalsIgnoreCase("1"))
hasPhone = "true";
else
hasPhone = "false" ;
if (Boolean.parseBoolean(hasPhone))
{
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
while (phones.moveToNext())
{ phoneNumber = phoneNumber + " <" + phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))+">";
}
phones.close();
}
}
cursor.close();
return phoneNumber;
}
What this does is when we click a "Contact" button it open a list with all the contacts, the user can select any contact and that selected contact will be added in the "To" field. I want to do the exactly same thing, but instead of displaying all the contacts i want to display only those who were recently used (call log) for selection.
Also it would be nice if you can tell how to do this with groups also.
I got this going using my own version. i used a dialog and handed it the cursor to the call log. Here is the function:
public void getCallLog() {
String[] callLogFields = { android.provider.CallLog.Calls._ID,
android.provider.CallLog.Calls.NUMBER,
android.provider.CallLog.Calls.CACHED_NAME /* im not using the name but you can*/};
String viaOrder = android.provider.CallLog.Calls.DATE + " DESC";
String WHERE = android.provider.CallLog.Calls.NUMBER + " >0"; /*filter out private/unknown numbers */
final Cursor callLog_cursor = getActivity().getContentResolver().query(
android.provider.CallLog.Calls.CONTENT_URI, callLogFields,
WHERE, null, viaOrder);
AlertDialog.Builder myversionOfCallLog = new AlertDialog.Builder(
getActivity());
android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
callLog_cursor.moveToPosition(item);
Log.v("number", callLog_cursor.getString(callLog_cursor
.getColumnIndex(android.provider.CallLog.Calls.NUMBER)));
callLog_cursor.close();
}
};
myversionOfCallLog.setCursor(callLog_cursor, listener,
android.provider.CallLog.Calls.NUMBER);
myversionOfCallLog.setTitle("Choose from Call Log");
myversionOfCallLog.create().show();
}
You can use ContactsContract.Contacts.CONTENT_STREQUENT_URI which will give you both Frequently called and Starred contacts.
From API 21 is possible to use this: https://developer.android.com/reference/kotlin/android/provider/CallLog.Calls#CACHED_LOOKUP_URI
CACHED_LOOKUP_URI added in API level 21 static val CACHED_LOOKUP_URI:
String The cached URI to look up the contact associated with the phone
number, if it exists.
This value is typically filled in by the dialer app for the caching
purpose, so it's not guaranteed to be present, and may not be current
if the contact information associated with this number has changed.

Categories