OnItemClickListener / SimpleDateFormat - java

I am working on a messaging app, and have made the conversation list show up fine, but am having trouble with my listview onitemclicklistner. I would like it to retrieve a textview (id=lblID), convert it to a string, then show the conversations list (with that string as the id) and display it in my listview.
Am I doing this correctly?
Solved the simplecursoradapter inside the onitemclicklistener wont let me use "this" as the context, what should I use instead?
I would like to use SimpleDateFormat, how would I do this between the cursor and adapter?
Solved I am now getting an error, does anyone no how to fix this?:
10-10 07:45:54.926 24231-24231/? E/AndroidRuntime: FATAL EXCEPTION: main
10-10 07:45:54.926 24231-24231/? E/AndroidRuntime: Process: com.example.wq.myapp, PID: 24231
10-10 07:45:54.926 24231-24231/? E/AndroidRuntime: android.database.sqlite.SQLiteException: near "*": syntax error (code 1): , while compiling: SELECT * FROM (SELECT DISTINCT date * 1 AS normalized_date, NULL AS * FROM sms WHERE (thread_id = 37 AND (type != 3)) UNION SELECT DISTINCT date * 1000 AS normalized_date, NULL AS * FROM pdu LEFT JOIN pending_msgs ON pdu._id = pending_msgs.msg_id WHERE (thread_id = 37 AND msg_box != 3 AND (msg_box != 3 AND (m_type = 128 OR m_type = 132 OR m_type = 130))) ORDER BY normalized_date desc) ORDER BY normalized_date desc
Here is my code:
#Override
public void onClick(View v) {
if (v == btnSMS) {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://mms-sms/conversations");
// Get Content Resolver object, which will deal with Content Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor a = cr.query(inboxURI, new String[] {"*"}, null, null, "normalized_date desc");
// Attach Cursor with adapter and display in listView
adapter1 = new SimpleCursorAdapter(this, R.layout.row, a,
new String[]{ "body", "date", "address","_id"},
new int[]{ R.id.lblMsg, R.id.lblDate, R.id.lblNumber, R.id.lblID }, 0);
lvMsg.setAdapter(adapter1);
lvMsg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView TVConvID = (TextView)findViewById(R.id.lblID);
String ConvID = TVConvID.getText().toString();
Uri ConvURI = Uri.parse("content://mms-sms/conversations/"+ConvID);
Cursor b = getContentResolver().query(ConvURI, new String[]{"*"}, null, null, "normalized_date desc");
adapter2 = new SimpleCursorAdapter(getApplicationContext(), R.layout.convrow, b,
new String[]{ "body", "date", "address" },
new int[]{ R.id.msglblMsg, R.id.msglblDate, R.id.msglblNumber }, 0);
lvMsg.setAdapter(adapter2);
}
});
}
Any help or extra knowledge would be greatly appreciated. :)

For 2:
SimpleCursorAdapter wants 'Context' as first Parameter. If you call 'this' in your OnItemClick method, your context is your OnItemClick.
If you are in a fragment, use getActivity(), or do this in your onCreate() method:
Context mContext = getActivity();
and use mContext as new SimpleCursorAdapter(mContext, .....);
In an activity, you can assign the variable mContext in onCreate like this:
Context mContext = this;
There are other methods like getApplicationContext() which you can try.

Related

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.

Get data from sqlite on android

I an trying to fetch data from my SQLite database on Android. However, when I run the code and see the Android Monitor, I get this message:
04-14 15:27:27.737 11177-11177/com.example.daniel.toto E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 6 rows, 5 columns.
This is the method in the database helper class I use to get the data from the database:
public ArrayList<String> getAllSales() {
ArrayList<String> array_list = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res;
res = db.rawQuery( "select * from sales", null );
if (res != null) {
res.moveToFirst();
while (res.isAfterLast() == false) {
array_list.add(res.getString(res.getColumnIndex(SALES_TABLE_NAME)));
res.moveToNext();
}
return array_list;
} else {
array_list = null;
}
return array_list;
}
This is where I call it in onCreate method the activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales);
mydb = new SalesDBHelper(this.getBaseContext());
array_list = mydb.getAllSales();
}
Thank you for deciphering the error message. Indeed the part of the error message column -1means: there is no such column.
Thank you a lot for pointing it out, it finally solved my problem!

passing data from one activity and displaying the database from the Main Activity

new to Java here :)
The problem I'm facing is that I am unable to display the database from the Main Activity with a click of a button. The data in the database is being passed from another activity, would like to know if I'm missing anything or how would I go about fixing this. Thanks :)
(Method being used in the Main Activity after the onCreate)
MainActivity
public void displayDataInTable() {
roomDatabase myOpenHelper;
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
String roomValue =bundle.getString("roomValue");
//List for the name of the players and their scores
List<String> roomNumber = new ArrayList<String>();
List<String> roomStatus = new ArrayList<String>();
//The data being read from the database
myOpenHelper = new roomDatabase(this, DATABASE_NAME, null, VERSION_NUMBER);
SQLiteDatabase db = myOpenHelper.getReadableDatabase();
Cursor cursor = db.query(roomDatabase.TABLE_NAME, null, null, null, null, null,null,null);
//The name and the score is printed on the row of the list
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String roomValueA = cursor.getString(cursor.getColumnIndex("roomValue"));
String statusA = cursor.getString(cursor.getColumnIndex("status"));
roomNumber.add(roomValueA);
roomStatus.add(" Recipe Ordered " + statusA);
}
//The items to de displayed are sent to the AdapterB
if ((roomNumber != null) && (roomStatus != null)) {
AdapterB adapter = new AdapterB(this, roomNumber, roomStatus);
setListAdapter(adapter);
}
}
LogsActivity
public class LogsActivity extends ListActivity{
roomDatabase myOpenHelper;
final String DATABASE_NAME = "roomstatus.db";
final int VERSION_NUMBER = 1;
ContentValues values1 = new ContentValues();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//variables are extracted from the bundle
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String status = bundle.getString("status");
String roomValue = bundle.getString("roomValue");
myOpenHelper = new roomDatabase(this, DATABASE_NAME, null, VERSION_NUMBER);
SQLiteDatabase db = myOpenHelper.getWritableDatabase();
values1.put("status", status);
values1.put("roomValue", roomValue);
Toast.makeText(LogsActivity.this, status, Toast.LENGTH_LONG).show();
//Data is entered into the table
db.insert(roomDatabase.TABLE_NAME, null, values1);
Intent newIntentBundle = new Intent(LogsActivity.this, MainActivity.class);
Bundle bundleA = new Bundle();
bundle.putString("status", status);
bundle.putString("roomValue", roomValue);
newIntentBundle.putExtras(bundle);
startActivity(newIntentBundle);
}
}
NOTE - I am aware this may not be right way to do as it would mean creating a new database in the Main Activity and trouble with the adapter, so any help would be appreciated. :)
These are the methods to save and fetch in RoomDatabase class:-
public boolean addDetails(String status,String roomValue){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_STATUS,status);
values.put(KEY_ROOMVALUE,roomValue);
db.insert(TABLE_NAME,null,values);
db.close();
return true;
}
public List<String> getAllDetail(){
List<String> detailList=new ArrayList<>();
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("select * from "+TABLE_NAME,null);
String status,roomValue;
if(cursor.moveToFirst()){
do{
status=cursor.getString(cursor.getColumnIndex(KEY_STATUS));
roomValue=cursor.getString(cursor.getColumnIndex(KEY_ROOMVALUE));
detailList.add(status);
detailList.add(roomValue);
}while (cursor.moveToNext());
}
return detailList;
}
In your activity where you have to save in db:
RoomDatabase roomDatabase=new RoomDatabase(getContext());
roomDatabase.addDetails(status,roomValue);
In your activity where you have to retrieve from db:
RoomDatabase roomDatabase=new RoomDatabase(getContext());
List<String> detailList=db.getAllDetail();
in detailList you can get the values.
Create a separate class for Database. Here are some links to how to create SQLite database in android.
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
https://developer.android.com/training/basics/data-storage/databases.html

make phone call when specific notification arrive [duplicate]

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);

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.

Categories