I have two different apps, AppA and AppB, I am trying to send an int from AppB to AppA, but the getIntExtra() in AppA is always getting the default value 0. Currently in AppA, gameRecords_str is receiving the correct string value, but I keep getting the default value 0 for gameCounter. What went wrong?
AppB:
String query = "SELECT * FROM gameRecord";
Cursor mcursor = database.rawQuery(query, null);
int counter = mcursor.getCount(); // Find out the number of records found in database
System.out.println("Number of record : " + counter);
Intent sendCounter = new Intent();
sendCounter.setAction("com.joy.AppA.LAUNCH_IT");
sendCounter.putExtra("counter", counter);
startActivity(sendCounter);
String gameRecord_str;
int flag;
mcursor.moveToFirst();
if (mcursor != null) {
if (mcursor.moveToFirst()) {
do {
String record = mcursor.getString(mcursor.getColumnIndex("record"));
gameRecord_str = record;
Intent i = new Intent();
i.setAction("com.joy.AppA.LAUNCH_IT");
i.putExtra("gameRecord", gameRecord_str);
startActivity(i);
} while (mcursor.moveToNext());
AppA:
Intent intent = getIntent();
int gameCounter = intent.getIntExtra("counter", 0); //Number of records from game AppB
System.out.println("gameCounter : " + gameCounter);
for (int i=0; i<=gameCounter; i++) {
String gameRecords_str = intent.getStringExtra("gameRecord");
System.out.println("Game record received from AppB : " + gameRecords_str);
Thanks in advance for your help!
Related
I am sending SMS from code & also updating the Systems SMS Sent messages; with :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
{
int subscriptionId = SmsManager.getDefaultSmsSubscriptionId();
SmsManager MySmsManager = SmsManager.getSmsManagerForSubscriptionId(subscriptionId);
ArrayList<String> msgArray = MySmsManager.divideMessage(DefaultMsgTemplate);
MySmsManager.sendMultipartTextMessage(SendSMSTo, null,msgArray, null, null);
CurrentSmsParts = msgArray.size();
Log.d("SMS DETAILS : ", "\nFOUND LOLLIPOP MR1 OR ABOVE...");
Log.d("SMS DETAILS : ", "\nDETECTED DEFAULT SMS SIM..."+subscriptionId);
Log.d("SMS DETAILS : ", "\nSENT MSG USING SIM..."+subscriptionId);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
{
SmsManager MySmsManager = SmsManager.getDefault();
ArrayList<String> msgArray = MySmsManager.divideMessage(DefaultMsgTemplate);
MySmsManager.sendMultipartTextMessage(SendSMSTo, null,msgArray, null, null);
CurrentSmsParts = msgArray.size();
Log.d("SMS DETAILS : ", "\nFOUND BELOW LOLLIPOP MR1...");
Log.d("SMS DETAILS : ", "\nDETECTED DEFAULT SMS SIM WHICHEVER AVAILABLE...");
Log.d("SMS DETAILS : ", "\nSENT MSG USING SIM1 OR SIM2 WHICHEVER IS AVAILABLE...");
}
ContentValues values = new ContentValues();
values.put("address", SendSMSTo);
values.put("body", DefaultMsgTemplate);
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
SMSDone++;
Here SMSDone is my counter to count the today sent SMSs via my application... ; But Users are also able to send SMSs, without my application..!!
So..,
How can i query SMS uri to get todays sent SMS number for both of the SIM cards / Numbers?
I am inserting my SMS in Sent SMS; But how to also insert SIM number via which it has been sent, from my application?
Credits : Mike M
Followed his instructions and by having basics of earlier uri querying this is the final answer i have implemented....
Log.d("Executing :", "from here....\n");
try
{
Calendar c1 = Calendar.getInstance();
c1.setTime(new Date());
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
long TodayStartedAt = c2.getTimeInMillis();
Log.d("Today started at ", "here" + TodayStartedAt);
final Uri SMS_INBOX = Uri.parse("content://sms/sent");
Cursor cursor = getContentResolver().query(SMS_INBOX, null, "date>=" + TodayStartedAt, null, null);
List < String > items = new ArrayList < String > ();
int counter = 0;
while (cursor.moveToNext())
{
String Date = cursor.getString(cursor.getColumnIndex("date"));
String SmsBody = cursor.getString(cursor.getColumnIndex("body"));
String PhoneNumber = cursor.getString(cursor.getColumnIndex("address"));
String FromSIM = cursor.getString(cursor.getColumnIndex("sub_id"));
Log.d("Counter : ", counter + "\n");
Log.d("Date : ", Date + "\n");
Log.d("PhoneNumber : ", PhoneNumber + "\n");
Log.d("FromSIM : ", FromSIM + "\n");
Log.d("SmsBody : ", SmsBody + "\n");
counter++;
}
cursor.close();
}
catch (Exception e)
{
Log.e("exception :", "is", e);
}
Thanks #Mike M. And Posted as it may help others in future...
I'm searching to get a little useful option to my app, the basics are simple, I have a list of questions (in listView) when we click in the question, we have another activity with details of questions and the answer that is setting ( true or false), if the answer is right, I want to color the question in the listview in green, red if false:
My code to generate questions:
public void showQuest(View view){
ModelHelper md = new ModelHelper(this);
db = openHelper.getWritableDatabase();
Spinner s = (Spinner) findViewById(R.id.spn_ques);
Integer para = 2;
para = Integer.parseInt( s.getSelectedItem().toString()) ;
ArrayList<String> lstQ = md.getOnlyQuestions(para);
ArrayAdapter lstad = new ArrayAdapter(this, android.R.layout.simple_list_item_1,lstQ);
lst.setAdapter(lstad);
The listView OnclickListener:
String quest = (String) parent.getAdapter().getItem(i);
int pos = lst.getCheckedItemPosition();
Intent inte = new Intent(view.getContext(),Reponse.class);
cursor = db.rawQuery("SELECT * FROM "+ ModelHelper.TABLE_QUESTION + " WHERE " + ModelHelper.KEY_QUESTION + " = ? ",new String[] {quest});
if (cursor != null)
if (cursor.getCount() > 0) {
cursor.moveToFirst();
final Intent intent = getIntent();
String matr= intent.getStringExtra("id");
String repA = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_WAITEDANSWER));
String cible = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFILE));
String plan = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PLAN));
int ID = cursor.getInt(cursor.getColumnIndex(ModelHelper.KEY_ID_QUESTION));
inte.putExtra("Question", quest);
inte.putExtra("answ", repA);
inte.putExtra("ID", ID);
inte.putExtra("pos", pos);
inte.putExtra("position", i);
inte.putExtra("matr", matr);
Toast.makeText(new.this, "" + ID, Toast.LENGTH_SHORT).show();
startActivity(inte);
}
}
});
The answer is selected in another activity, in the first one I have only the questions' list.
Thanks.
When you are rendering the item in the listview set the background color based on the logic you described.
This code seems fine. I have researched in many Websites, but when I run the code, only the first number in contact list comes to the text view. But I want desired contact number to be shown in the edit text view.
private void importContact() {
Intent importContactIntent = new Intent(Intent.ACTION_PICK);
importContactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(importContactIntent, PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
//Uri contactData = data.getData();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
cursor.moveToNext();
String name = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
destinationPhoneNumber = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//
enterPhoneNumber.setText(destinationPhoneNumber);
Toast.makeText(this,
name + " has number " + destinationPhoneNumber,
Toast.LENGTH_LONG).show();
cursor.close();
}
}
}
You can query like this to get all the numbers of a particular contact:
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
image_uri = cur
.getString(cur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//System.out.println("name : " + name + ", ID : " + id);
// NOW query all numbers of that particulat contact using contact_Id
Cursor pCur = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
// you can store phone in a arrayList
phone = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//System.out.println("phone" + phone);
}
pCur.close();
}
I have a program that will fetch several String from database (announcementId, and announcementTitle),
then for every string fetched from the database, I want to compare each of them (Compare all the fetched announcementId),
if the string (announcementId) has different value then it will create a new Button using the announcementTitle as it's(the button) value fetch from database.
I tried to learn how, and found out that bubble sort algorithm can be used in this case, but there is some error in the program.. Index out of bound exception..
Then I tried some code and tried to change the array, but it still didnt work.
Could you please take a look at my code and tell me where is the error and the best way to fix the error
This is my code :
myDb = new Database(ViewAllAnnouncement.this);
myDb.open();
totalAnnouncement = myDb.countHowManyAnnouncement(username);
String temp = Integer.toString(totalAnnouncement);
//Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show();
String[] announcementTitle = myDb.fetchMyAnnouncement(username);
String[] announcementId = myDb.fetchAnnouncementId(username);
for (int i = 0; i < totalAnnouncement; i++) {
for (int j = 0; j < totalAnnouncement - i; j++) {
if (j > 0 || j < totalAnnouncement-i) {
if (!announcementId[j].equals(announcementId[i])) {
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
}
}
}
}
myDb.close();
And this is my method to return the announcementId
public String[] fetchAnnouncementId(String Username) {
// TODO Auto-generated method stub
int i = 0;
String Query = "SELECT b." + ANNOUNCEMENT_ID + " FROM "
+ MS_GROUP_DETAIL + " a, " + MS_ANNOUNCEMENT_DETAIL + " b, "
+ MS_ANNOUNCEMENT + " c WHERE a." + GROUP_ID + " = b."
+ GROUP_ID + " AND b. " + ANNOUNCEMENT_ID + " = c."
+ ANNOUNCEMENT_ID + " AND a." + MEMBER_USERNAME + " =? ORDER BY b." +ANNOUNCEMENT_ID;
Cursor c = ourDatabase.rawQuery(Query, new String[] { Username });
String temp[] = new String[c.getCount()];
int iArray = c.getColumnIndex(ANNOUNCEMENT_ID);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
temp[i] = c.getString(iArray);
i++;
}
c.close();
return temp;
}
If bubble sort is the answer you must have misunderstood the question. I strongly recommend you just add
ORDER BY announcementId
to the end of your query. That way the database will sort by your column for you.
Edit
You could use
ORDER BY 1
to sort by the first column (and omit the name). And, then your code should look something like
for (int i = 0; i < totalAnnouncement - 1;) {
int j = i + 1;
for (; j < totalAnnouncement; j++) {
if (!announcementId[j].equals(announcementId[i])) {
break;
}
}
// j is the first value where the announcementId changes
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
i = j; // <-- assign j to i.
}
I'm using "Calls.CONTENT_URI" content provider. I already retrived column names, but now i would like to get let's say, ALL names from column name "name" in this content provider.
I have code below:
uri = Calls.CONTENT_URI;
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
cursor.moveToFirst();
for(int x=0; x<cursor.getCount(); x++){
s = cursor.getString(x);
Log.i("TUTORIAL", ""+s);
//cursor.moveToNext();
}
But this retrives only one name. I would like to have list of all names saved in my phone like:
John
Peter
Mark
Suzy
.
.
X
But now i got just one name like:
Peter.
Hope i've been clear enough.
What's the problem? Thanks for help in advance.
I think this would help you
ArrayList<String> nameList = new ArrayList<String>();
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
if(cursor.moveToFirst()) {
do {
nameList.add(cursor.getString(0));
//your code
//s = cursor.getString(x);
Log.i("TUTORIAL", ""+cursor.getString(0));
}while(cursor.moveToNext());
}
you can try this one , it's working for me :
public void readContacts() {
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
}
cur.close();
}
This is the code.
public class MainActivity extends AppCompatActivity {
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.lv_layout,
null,
new String[] { "name","photo","details"},
new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String nickName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
//String photoPath="" + R.drawable.blank;
byte[] photoByte=null;
String homeEmail="";
String workEmail="";
String companyName="";
String title="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting EMails
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Email.TYPE_HOME :
homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK :
workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting Organization details
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
}
// Getting Photo
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
if(photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the contact image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// photoPath = tmpFile.getPath();
}
}
}while(dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if(homePhone != null && !homePhone.equals("") )
details = "HomePhone : " + homePhone + "\n";
if(mobilePhone != null && !mobilePhone.equals("") )
details += "MobilePhone : " + mobilePhone + "\n";
if(workPhone != null && !workPhone.equals("") )
details += "WorkPhone : " + workPhone + "\n";
if(nickName != null && !nickName.equals("") )
details += "NickName : " + nickName + "\n";
if(homeEmail != null && !homeEmail.equals("") )
details += "HomeEmail : " + homeEmail + "\n";
if(workEmail != null && !workEmail.equals("") )
details += "WorkEmail : " + workEmail + "\n";
if(companyName != null && !companyName.equals("") )
details += "CompanyName : " + companyName + "\n";
if(title != null && !title.equals("") )
details += "Title : " + title + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,null,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}