How do I refresh my cursor from another activity?
In my main activity I start a cursor to query phone contacts and display in a listview.
In this main activity I also have a menu, 'Add new Contact', which starts the add new contact activity. A new contact gets added correctly (I can see it in other Contacts apps on my phone), but it is not visible in my listview when the user goes back to main activity.
Is there a way to refresh the cursor from 'add new contact' activity, so the user can see it in the listview when they go back to main activity?
I use AsyncTask in my main activity, if that's any useful info. I read about swapcursor and changecursor but it didn't work when I tried to use them. Here's my 'add new contact' code :
(I call changecursor before the "Contact Saved" toast, but I'm sure it's not done correctly.
package com.example.chris.contactlistcustomlistview;
import android.content.ContentProviderOperation;
import android.content.OperationApplicationException;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Chris on 06/05/2016.
*/
public class AddContact extends AppCompatActivity {
EditText nameofcontact;
EditText numberofcontact;
public String contactname;
public String contactnumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addcontact);
nameofcontact = (EditText) findViewById(R.id.edittextname);
numberofcontact = (EditText) findViewById(R.id.edittextnumber);
}
public void createButton(View view) {
contactname = nameofcontact.getText().toString();
contactnumber = numberofcontact.getText().toString();
if (contactname.length() == 0) {
Toast.makeText(this, "Please enter a name",
Toast.LENGTH_LONG).show();
return;
}
ArrayList<ContentProviderOperation> contentProviderOperations = new ArrayList<ContentProviderOperation>();
//insert raw contact using RawContacts.CONTENT_URI
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
//insert contact display name using Data.CONTENT_URI
Log.d("ffff","wwww");
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,contactname ).build());
//insert mobile number using Data.CONTENT_URI
contentProviderOperations.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactnumber).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
try {
//apply the changes
getApplicationContext().getContentResolver().
applyBatch(ContactsContract.AUTHORITY, contentProviderOperations);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
// SelectContactAdapter.changeCursor(cursor);
Toast.makeText(this, "Contact saved",
Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
//This clears the edittext next time user starts the application, rather than
// having the same numbers there, which the user probably doesn't want anymore
protected void onResume() {
final EditText editText = (EditText) findViewById(R.id.edittextname);
super.onResume();
editText.setText("");
}
}
And here's my MainActivity code :
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends Activity implements PopupMenu.OnMenuItemClickListener {
// ArrayList
ArrayList<SelectContact> selectContacts;
List<SelectContact> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
// Cursor phones, email;
Cursor pCur;
// Pop up
// ContentResolver resolver;
SearchView search;
SelectContactAdapter adapter;
String phoneContactId;
String name;
String phoneNumber;
CharSequence nameofcontact;
// String phoneNumber;
// *****18-04-2016***
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
// String contactid;
// *****
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectContacts = new ArrayList<SelectContact>();
// resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
LoadContact loadContact = new LoadContact();
loadContact.execute();
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
if (cursor != null) {
cursor.moveToFirst();
}
try {
// get a handle on the Content Resolver, so we can query the provider,
cursor = getApplicationContext().getContentResolver()
// the table to query
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
// Null. This means that we are not making any conditional query into the contacts table.
// Hence, all data is returned into the cursor.
// Projection - the columns you want to query
null,
// Selection - with this you are extracting records with assigned (by you) conditions and rules
null,
// SelectionArgs - This replaces any question marks (?) in the selection string
// if you have something like String[] args = { "first string", "second#string.com" };
null,
// display in ascending order
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
// get the column number of the Contact_ID column, make it an integer.
// I think having it stored as a number makes for faster operations later on.
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
// get the column number of the DISPLAY_NAME column
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
// get the column number of the NUMBER column
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
cursor.moveToFirst();
// We make a new Hashset to hold all our contact_ids, including duplicates, if they come up
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
// get a handle on the contactid, which is a string. Loop through all the contact_ids
String contactid = cursor.getString(Idx);
// if our Hashset doesn't already contain the contactid string,
// then add it to the hashset
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
// get a handle on the display name, which is a string
name = cursor.getString(nameIdx);
// get a handle on the phone number, which is a string
phoneNumber = cursor.getString(phoneNumberIdx);
// String image = cursor.getString(photoIdIdx);
// System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->" + contactid + " Name--->" + name);
System.out.println("Id--->" + contactid + " Number--->" + phoneNumber);
SelectContact selectContact = new SelectContact();
// selectContact.setThumb(bit_thumb);
selectContact.setName(name);
selectContact.setPhone(phoneNumber);
// selectContact.setEmail(id);
// selectContact.setCheckedBox(false);
selectContacts.add(selectContact);
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
// if (cursor != null) {
// }
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//into each inflate_listview, put a name and phone number, which are the details making
// our SelectContact, above. And SelectContacts is all these inflate_listviews together
// This is the first property of our SelectContactAdapter, a list
// The next part, MainActivity.this, is our context, which is where we want the list to appear
adapter = new SelectContactAdapter(selectContacts, MainActivity.this);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nameofcontact = ((TextView)view.findViewById(R.id.name)).getText();
// }
// Creates a new Intent to edit a contact
Intent intent = new Intent(Intent.ACTION_EDIT);
startActivity(intent);
listView.setFastScrollEnabled(true);
}
});
}}
//the is the arrow image, it opens the activity for edit or new contact
public void EditorCreateContact(View v) {
}
#Override
protected void onStop() {
super.onStop();
}
// this is for the settings menu
public void settingsPopUp(View view) {
PopupMenu popup = new PopupMenu(this,view);
popup.setOnMenuItemClickListener(MainActivity.this);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_actions, popup.getMenu());
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// from the popup_actions.xml, identify the New_contact id and make it
// open the AddContact class
case R.id.New_contact:{
Intent intent = new Intent(this, AddContact.class);
startActivity(intent);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(intent);
// finish(); // Call once you redirect to another activity
}
// Toast.makeText(getBaseContext(), "You slected New Contact",Toast.LENGTH_SHORT).show();
//
return true;
}
return false;
}
}
First of all declare the line
final EditText editText = (EditText) findViewById(R.id.edittextname);
in OnCreate() ... as it is a bad practice to initialize the view every time at on resume of activity.
and query the data in OnResume of your activity. Thats a better way to refresh the data as you come back to your activity.
You can refresh your contacts in onResume() method as i mentioned in comments, for that you can do the following in onResume() itself
LoadContact loadContact = new LoadContact();
loadContact.execute();
you can remove the above from onCreate() as it would be redundant to call as onResume() will be called every time as the Activity LifeCycle.
If you use this approach just clear ArrayList selectContacts by doing selectContacts.clear() in doInBackground() at the first line, other wise it will list contacts twice and thrice and so onn...
Also apart from these, as mentioned in another answer in same thread you can use, startActivityForResult() and in onActivityResult() method you can update contact list.
You could use startActivityForResult() instead of startActivity and override onActivityResult() to requery your cursor on success. After the toasting, setResult() to RESULT_OK and finish the AddContact activity.
setResult(RESULT_OK);
finish();
Related
I created my own Android project and cut and pasted the code from this exercise:
http://androidexample.com/Show_Phone_Contacts_In_AutoComplete_Suggestions_-_Android_Example%20/index.php?view=article_discription&aid=106&aaid=128#
When I build the project I get no errors or warnings. When I run the project I get this window with an error:
Annoyingly, I can't make the window any smaller, so I can't click any of the buttons. I just cick the 'X' at the top, to close it.
Here's my project structure:
Where is it getting 'AutocompleteMain' from? (note the small c) My class is named AutoCompleteMain. Thanks for any help.
And I do have the activity included in my Android Manifest, in case you're wondering:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.autocompleteedittext"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.chris.dialler.AutoCompleteMain"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
And here's the code of my class, AutoCompleteMain.java :
(one thing I notice, in this class, is that phoneNumber.toString() and name.toString() are highlighted, saying they're redundant. Don't know if that's the cause of the problem)
package com.example.chris.dialler;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import com.androidexample.autocompleteedittext.R;
public class AutoCompleteMain extends Activity implements OnItemClickListener, OnItemSelectedListener {
// Initialize variables
AutoCompleteTextView textView=null;
private ArrayAdapter<String> adapter;
// Store contacts values in these arraylist
public static ArrayList<String> phoneValueArr = new ArrayList<String>();
public static ArrayList<String> nameValueArr = new ArrayList<String>();
EditText toNumber=null;
String toNumberValue="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.autocomplete_main);
final Button Send = (Button) findViewById(R.id.Send);
// Initialize AutoCompleteTextView values
textView = (AutoCompleteTextView) findViewById(R.id.toNumber);
//Create adapter
adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>());
textView.setThreshold(1);
//Set adapter to AutoCompleteTextView
textView.setAdapter(adapter);
textView.setOnItemSelectedListener(this);
textView.setOnItemClickListener(this);
// Read contact data and add data to ArrayAdapter
// ArrayAdapter used by AutoCompleteTextView
readContactData();
/********** Button Click pass textView object ***********/
Send.setOnClickListener(BtnAction(textView));
}
private OnClickListener BtnAction(final AutoCompleteTextView toNumber) {
return new OnClickListener() {
public void onClick(View v) {
String NameSel = "";
NameSel = toNumber.getText().toString();
final String ToNumber = toNumberValue;
if (ToNumber.length() == 0 ) {
Toast.makeText(getBaseContext(), "Please fill phone number",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), NameSel+" : "+toNumberValue,
Toast.LENGTH_LONG).show();
}
}
};
}
// Read phone contact name and phone numbers
private void readContactData() {
try {
/*********** Reading Contacts Name And Number **********/
String phoneNumber = "";
ContentResolver cr = getBaseContext()
.getContentResolver();
//Query to get contact name
Cursor cur = cr
.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
null);
// If data data found in contacts
if (cur.getCount() > 0) {
Log.i("AutocompleteContacts", "Reading contacts........");
int k=0;
String name = "";
while (cur.moveToNext())
{
String id = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//Check contact have phone number
if (Integer
.parseInt(cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
//Create query to get phone number by contact id
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { id },
null);
int j=0;
while (pCur
.moveToNext())
{
// Sometimes get multiple data
if(j==0)
{
// Get Phone number
phoneNumber =""+pCur.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Add contacts names to adapter
adapter.add(name);
// Add ArrayList names to adapter
phoneValueArr.add(phoneNumber.toString());
nameValueArr.add(name.toString());
j++;
k++;
}
} // End while loop
pCur.close();
} // End if
} // End while loop
} // End Cursor value check
cur.close();
} catch (Exception e) {
Log.i("AutocompleteContacts","Exception : "+ e);
}
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
//Log.d("AutocompleteContacts", "onItemSelected() position " + position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
// Get Array index value for selected name
int i = nameValueArr.indexOf(""+arg0.getItemAtPosition(arg2));
// If name exist in name ArrayList
if (i >= 0) {
// Get Phone Number
toNumberValue = phoneValueArr.get(i);
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// Show Alert
Toast.makeText(getBaseContext(),
"Position:"+arg2+" Name:"+arg0.getItemAtPosition(arg2)+" Number:"+toNumberValue,
Toast.LENGTH_LONG).show();
Log.d("AutocompleteContacts",
"Position:"+arg2+" Name:"+arg0.getItemAtPosition(arg2)+" Number:"+toNumberValue);
}
}
protected void onResume() {
super.onResume();
}
protected void onDestroy() {
super.onDestroy();
}
}
phoneNumber and name are already Strings so there it is, and unnecessary, to try and convert them to Strings. In regards to your main question, I have had annoying problems like this in the past and I would either try syncing gradle or rebooting Android Studio.
Can you provide the code of that class? Does it extend any type of Activity? From the looks of your manifest, it is set as your launching activity. You have to make sure it isn't just a plain Java class. It needs to be a type of activity (FragmentActivity, Activity, CombatActivity, etc....) Let me know if this helps!
I am developing one android application.i want to display a data which is selected from database and display it in listview.first of all i had used static data for display Trainee(user) data. which is static. then after For same functionality i have use sqlite Database and register the Trainee(user) and now i want to display registered trainne's name in listview. i have just done below code. can anyone help me how to display trainee names in listview.
AddTraineeActivity.java
This file works basic function of create trainee database and insert values of trainee:
package com.example.gymapp;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTraineeActivity extends Activity implements OnClickListener
{
EditText fn;
EditText ln;
EditText un;
EditText pwd;
EditText pno;
EditText age;
Button btnAdd;
SQLiteDatabase db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_managetrainee);
fn = (EditText) findViewById(R.id.etfirstname);
ln = (EditText) findViewById(R.id.etlastname);
age = (EditText) findViewById(R.id.edage);
pno = (EditText) findViewById(R.id.etphoneno);
un = (EditText) findViewById(R.id.ettraineeun);
pwd = (EditText) findViewById(R.id.etpwdtrainee);
btnAdd = (Button) findViewById(R.id.btnsavedata);
db=openOrCreateDatabase("mydb", MODE_PRIVATE, null);
db.execSQL("create table if not exists trainee(firstname text, lastname text,age varchar,phoneNumber varchar,userTrainee varchar,passwordTrainee varchar)");
btnAdd.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
public void show(String str)
{
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v== btnAdd)
{
String firstname = fn.getText().toString();
String lastname = ln.getText().toString();
String Age = age.getText().toString();
String phoneNumber = pno.getText().toString();
String usernameTrainee = un.getText().toString();
String passwordTrainee = pwd.getText().toString();
if(firstname==null||firstname==""||firstname.length()<3)
{
show("Please Enter Correct Name.");
}
else if(lastname==null||lastname==""||lastname.length()<2)
{
show("Please Enter Correct Name.");
}
else if(Age==null||Age==""||Age.length()>3)
{
show("Please Enter Correct Age.");
}
else if(phoneNumber==null||phoneNumber==""||phoneNumber.length()<10)
{
show("Please Enter Correct mobile number.");
}
else if(usernameTrainee==null||usernameTrainee==""||usernameTrainee.length()<4)
{
show("Please Enter valid User name.");
}
else if(passwordTrainee==null||passwordTrainee==""||passwordTrainee.length()<6)
{
show("Please Enter Strong Password.");
}
else
{
db.execSQL("insert into trainee values('"+firstname+"','"+lastname+"','"+Age+"','"+phoneNumber+"','"+usernameTrainee+"','"+passwordTrainee+"')");
//i=new Intent(this,Welcome.class);
//startActivityForResult(i, 500);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
db.close();
finish();
}
}
}
}`
UserListActivity.java
This file contain the code which display the trainee names in listview. but this file display static users for example,trainee1,trainee2,trainee3....trainee13.
package com.example.gymapp;
import com.tss.constant.Constant;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.Context;
import android.database.sqlite.*;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import com.example.gymapp.AddTraineeActivity;
import com.example.gymapp.dao.DBfitguidehelper;
public class UserListActivity extends Activity {
private ListView listViewUser;
private String loggedInType ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
//SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
//queryBuilder.setTables(DBfitguidehelper.)
listViewUser = (ListView)findViewById(R.id.listViewUser);
String[] values = new String[]{"trainee", "trainee1", "trainee2", "trainee3", "trainee4", "trainee5", "trainee6", "trainee7", "trainee8", "trainee9", "trainee10", "trainee11", "trainee12", "trainee13"};
ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listViewUser.setAdapter(userAdapter);
listViewUser.setOnItemClickListener(new ListViewListner());
if(savedInstanceState!=null){
Bundle extras = getIntent().getExtras();
loggedInType = extras.getString("loggedInType");
System.out.println("loggedInType - " + loggedInType);
}
}
private class ListViewListner implements OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "selected user is " + listViewUser.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
Constant.Selected_Trainee = ""+listViewUser.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(),TrainerActivity.class);
intent.putExtra("loggedInType", loggedInType);
Toast.makeText(getApplicationContext(), "loggedInType"+loggedInType, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
now i want to display name of trainees which is stored in database. can anyone help me??
If you want to see how a Cursor loader can work for you, you can review the following project that I have uploaded to github: GPS Distance Tracking
I got an activity that is called from main activity. In the activity, i got database connections established and i fill a spinner according to db data. When a user selects one of the spinner items and press the button, the activity finishes and returns a value to the main activity (activity on result). But the button in the activity doesnt work, so the activity never returns a value to main activity. Here is the code:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class mySpinnerClass extends Activity implements
OnItemSelectedListener {
private VeriTabani veritabani;
private SQLiteDatabase db;
Spinner spinner;
Button btnAdd;
String dataBaseName;
int selectedValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
dataBaseName = "";
selectedValue = -1;
Intent i = getIntent();
dataBaseName = i.getStringExtra("dataBaseName");
veritabani = new VeriTabani(this);
db = veritabani.getWritableDatabase();
// Spinner element
spinner = (Spinner) findViewById(R.id.mySpinner);
// add button
btnAdd = (Button) findViewById(R.id.addButton);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (dataBaseName == "phoneOrientation") {
Intent intent = getIntent();
intent.putExtra("phoneOrientation", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName== "phonePosition") {
Intent intent = getIntent();
intent.putExtra("phonePosition", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName =="Label"){
Intent intent=getIntent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
private void loadSpinnerData() {
// Spinner Drop down elements
List<String> lables = getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + dataBaseName;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(cursor.getColumnIndex("isim")));
} while (cursor.moveToNext());
}
// closing connection
// returning lables
return labels;
}
public int returnID(String item) {
int toBereturnedID;
Cursor myCursor = db.rawQuery("SELECT _id from " +dataBaseName+ " WHERE isim="+"'"+item+"'", null);
myCursor.moveToFirst();
toBereturnedID = myCursor.getInt(0);
return toBereturnedID;
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String label = parent.getItemAtPosition(position).toString();
selectedValue = returnID(label);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
You are calling loadSpinnerData(); method in onCreate() of activity so dataBaseName is always going to be empty, so you want to have value of spinner at time click you need to call that with on onClick() method of button, which will give you correct dataBaseName and use dataBaseName.equals("phoneOrientation") instead of dataBaseName == "phoneOrientation"
Try creating a new Intent instead of getIntent().
Intent intent=new Intent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
Hope it helps.
I newbie in this field.
my application have 6 buttons with different category. when i click on one of the button it will go to another page for displaying listView for particular category in my database.
my problem is, I don't know how do switch case for this method.
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
I want to include getCategoryHall, getCategoryFacilty,and getCategoryAdmin in this QSFacultyLocation.java. so that, i no need to create another activity merely to get getCategoryHall, getCategoryFacilty,and getCategoryAdmin (listView).Because it just using same coding.
below is my full code for:
QSFacultyLocation.java
package com.example.ukmlocationsearching;
import java.util.ArrayList;
import java.util.List;
import com.example.ukmlocationsearching.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class QSFacultyLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qs_faculty_location);
final Intent c = new Intent(QSFacultyLocation.this, QSLocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
/*SearchKategori searchKategori = new SearchKategori();
UkmLocation selectedKategori = searchKategori.getSelectedKategori();
List<UkmLocation> locationList = null;*/
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
//------------------------------------------------------------------
// Determine list POI with category
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
//------------------------------------------------------------------
// Closing db (if any)
// db.close();
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
QuickSearchMenu.java
package com.example.ukmlocationsearching;
import java.io.IOException;
import com.example.ukmlocationsearching.R;
import com.example.ukmlocationsearching.R.id;
import com.example.ukmlocationsearching.R.layout;
import com.example.ukmlocationsearching.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearchMenu extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//---------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search_menu);
View faculty = findViewById(R.id.button2);
faculty.setOnClickListener(this);
View researchInstitute = findViewById(R.id.button1);
researchInstitute.setOnClickListener(this);
View college = findViewById(R.id.button3);
college.setOnClickListener(this);
View admin = findViewById(R.id.button4);
admin.setOnClickListener(this);
View facility = findViewById(R.id.button5);
facility.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search_menu, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Intent b1 = new Intent(this, QSResearch.class);
startActivity(b1);
break;
case R.id.button2:
Intent b2 = new Intent(this,QSFacultyLocation.class);
startActivity(b2);
break;
/*case R.id.button3:
Intent b3 = new Intent(this,QuickSearchCollege.class);
startActivity(b3);
break;
case R.id.button4:
Intent b4 = new Intent(this,QuickSearchFaculty.class);
startActivity(b4);
break;
case R.id.button5:
Intent b5 = new Intent(this,QuickSearchCollege.class);
startActivity(b5);
break;*/
}
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
/*Log.d("Initiate", "Kategori Count: " + myDbHandler.getKategoriCount());
Log.d("Initiate", "KategoriPoi Count: " + myDbHandler.getKategoriPoiCount());*/
myDbHandler.close();
}
//------------------------------------------------------------------------------
}
please do help me solve this. thank you
First,pass a query or simply any key value such as department id or department name as an intent with each button click using
intentname.putExtra(keyname_used_to_retrieve_value,value_to_be_passed_to_next_activity);
case R.id.button1:
String query="select * from table_name where something='xyz'";
Intent b1 = new Intent(this, QSResearch.class);
b1.putExtra("myextrakey",query);
startActivity(b1);
Then, receive the intent in the onCreate method of list activity as follows,initialise database and call user defined mylist() and setuplist() functions
Intent i=getIntent();
String x=i.getStringExtra("myextrakey");//this assigns the query to string x
//open database here
mylist();//call myList function which i have defined in the following lines
setUpList();//call setUpList function which i have defined in the following lines
This is the myList function:
private void myList() {
myownlist= new ArrayList<String>();
Cursor myCursor = database.rawQuery(x,null);
myCursor.moveToFirst();
if(!myCursor.isAfterLast()) {
do {
//selects data in column 2 to be displayed on list
String listitem= myCursor.getString(2);
myownlist.add(listitem);
} while (myCursor.moveToNext());
}
myCursor.close();
}
This is the setUpList() function:
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myownlist));
ListView lv = getListView();
}
I have got the code where through content provider i am retrieving the phone contacts and displaying them in list format.
I want to display the phone no and name of the particular person in next activity when i click on the list format contacts from first activity. I am getting errors in this its not able to perform click operation and display it on to next activity Please help me with this.
Here is the first Activity through i am display the contacts through content provider.
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MsatActivity extends ListActivity
{
TextView ContactsTV;
ListView lv;
Cursor c;
public static final Uri CONTENT_URI =
Uri.parse("content://com.android.contacts/contacts/1557");
public void onListItemClick(View v)
{
Intent outData = new Intent(this,Full.class);
// setResult(Activity.RESULT_OK, outData);
startActivity(outData);
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri myContacts = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
c = getContentResolver().query(myContacts, new String[]
{ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER}
, null, null, null);
String[] columns = new String[]
{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
int[] to = new int[] {R.id.text1,R.id.text2};
SimpleCursorAdapter mAdapter = new
SimpleCursorAdapter(this,R.layout.listitems, c, columns, to);
setListAdapter(mAdapter);
lv.setOnItemSelectedListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
{
int rowId = c.getInt(c.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone._ID));
Uri outURI = Uri.parse(CONTENT_URI.toString() + "/" + rowId);
Intent outData = new Intent();
outData.setData(outURI);
setResult(Activity.RESULT_OK, outData);
finish();
}
});
}
}
Here is the second activity.......
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
public class Full extends Activity
{
private static final int CONTACT_PICKER_RESULT = 1001;
String name;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
Button getContacts = (Button)findViewById(R.id.button1);
getContacts.setOnItemClickListener(new View.OnItemClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACT_PICKER_RESULT);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case CONTACT_PICKER_RESULT:
try {
Uri result = data.getData();
String id = result.getLastPathSegment();
//Get Name
cursor = getContentResolver().query(result, null, null, null, null);
if (cursor.moveToFirst())
{
name =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
catch (Exception e)
{
}
}
}
}
}
I really can't figure out your code at all. The first activity seems to be creating an Intent to start the Full Activity, but it has two "onclick" methods and it does a setResult() and finish() even though it never did getIntent()!
The second activity creates an ACTION_PICK Intent for the entire Phone table, and handles the return by doing a query on the result, which should be the contact ID of the contact whose # the user picked. I don't think it's the entire URI, though; you should verify that through debug. You then try to get the DISPLAY_NAME for this contact.
Fine, but I don't see why you need the first Activity at all.
I posted some instructions on using the Contacts Provider somewhere else on Stackoverflow; just search for android and ContactsContract.