Get information from a listItem onClick with _id - android

I have a listview populated by a database. The listview displays some columns of the database. I want to be able to click the listItem and display a new activity that shows that whole record. I am trying to do this by passing the id between through an intent but it is not working. The activity is starting but the textViews aren't being populated. I have included the relevent code snippets here. Would really appreciate some help
MainActivity
public class MainActivity extends ListActivity {
....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
}
private void fillList() {
ListView lv = getListView();
Cursor c = db.getData();
startManagingCursor(c);
CustomCursorAdapter adapter = new CustomCursorAdapter(getApplicationContext(), c);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent k = new Intent(MainActivity.this, ProductDetails.class);
k.putExtra("item_id", id);
startActivity(k);
}
});
}
}
ProdDetails
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new ProdDB(this);
setContentView(R.layout.product_details);
db.open();
long id = getIntent().getLongExtra("item_id", 0);
Cursor cursor = db.getDetails(id);
while(cursor.moveToFirst()){
tv1.setText(cursor.getString(cursor.getColumnIndex(ProdDB.KEY_PRODCODE)));
tv2.setText(cursor.getString(cursor.getColumnIndex(ProdDB.KEY_PRODNAME)));
...
...
}
}
}
DB.getDetails() - from ProdDB
String[] columns = new String[] {KEY_ROWID,
KEY_PRODCODE,
KEY_PRODNAME,
KEY_PRODTYPE,
KEY_PRODCAT,
KEY_PRODPRICE,
KEY_PRODRRP,
KEY_PRODSUPPLIER,
KEY_NOTES};
return db.query(DB_TABLE, columns, KEY_ROWID + " = ?", new String[]{String.valueOf(id)}, null, null, null);

you're having issue cause you're using while(cursor.moveToFirst()){. if you must use the while loop then you should use the .moveToNext() instead. Otherwise, you can just take out the while loop for moveToFirst since i'm assuming you only need the one row. as for why, don't ask me, i couldn't tell you.

Related

ListView with SimpleCursorAdapter does not refresh after changes

I created a kind of contacts application. I am using a ListView and a SimpleCursorAdapter, and the contacts are stored in a SQLite database.
In the main screen, there are two buttons: "Add contacts" and "View contacts". When I view the contacts and I click on one of them, I can edit or delete that contact.
After I do any of these changes, the contacts list displayed should refresh according to the changes made, but it doesn't.
I have read and tried plenty of possible solutions, but every case that I find is different, and apparently some solutions only work in some cases, so I'm very confused.
In the main activity, I call this method:
public void viewContacts(View view){
Intent intent = new Intent(this, Contacts.class);
startActivity(intent);
}
This is the Contacts class:
public class Contacts extends ExampleActivity {
ContactsOpenHelper dbHelper;
SQLiteDatabase db;
SimpleCursorAdapter adapter;
ListView listView;
Cursor c;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.contactslayout);
listView = (ListView) findViewById(R.id.listView);
dbHelper = new ContactsOpenHelper(this);
db = dbHelper.getReadableDatabase();
String[] projection = {Contract.Entry.NAME,Contract.Entry.NUMBER,_ID};
c = db.query(Contract.Entry.TABLE_NAME, projection, null, null, null, null, null);
String[] fromColumns = {Contract.Entry.NAME,Contract.Entry.NUMBER};
int[] toViews = {R.id.textViewName, R.id.textViewNumber};
adapter = new SimpleCursorAdapter(this,R.layout.contactslayoutentry,c,fromColumns,toViews,0);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ContactDialog cd = new ContactDialog(db, id, adapter);
cd.show(getFragmentManager(), "Contactos");
}
});
}
}
The ContactDialog class:
public class ContactDialog extends DialogFragment {
SQLiteDatabase db;
long id;
SimpleCursorAdapter adapter;
public ContactDialog(SQLiteDatabase db, long id, SimpleCursorAdapter adapter) {
this.db = db;
this.id = id;
this.adapter = adapter;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose an action")
.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDialogFragment mdf = new MyDialogFragment(getActivity().getApplicationContext(), db, true, id);
mdf.show(getFragmentManager(), "TAG");
}
})
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selection = Contract.Entry._ID + " LIKE ?";
String[] selectionArgs = {String.valueOf(id)};
db.delete(Contract.Entry.TABLE_NAME, selection, selectionArgs);
adapter.notifyDataSetChanged();
}
});
return builder.create();
}
}
In the MyDialogFragment class I run the line
db.update(Contract.Entry.TABLE_NAME, myValues, Contract.Entry._ID + " LIKE " + id,null);
I don't know if I need the notifySetDataChanged() method, when to execute it, or whether I need another solution.
I would really appreciate some help.
Thank you.
EDIT:
I forgot to point out that the elements are correctly edited or deleted in the database. When I do some changes, I go back to the main screen and click on "View contacts" again, and the list is updated. I guess this is important to know.
Firstly,I suggest you use CursorLoader and LoaderManager,it will be better than your current solution.
If you still want to use this solution,please add cursor.requery() after update your data,like this:
db.update(Contract.Entry.TABLE_NAME, myValues, Contract.Entry._ID + " LIKE " + id,null);
adapter.getCursor().requery();

Add listener to ListView of contacts?

I need some help to add an onItemClickListener to a ListView of contacts. I want to capture some information from the selected contacts like name, phonenumbers and other info and pass it to another activity.
I'm not sure how to add a onListItemListener to my code below and how to capture info from the selected contact? I also wonder how to pass more than one value with an Intent? I use this for one value:
Intent i = new Intent(Activity_1.this, Activity_2.class);
startActivityForResult(i, 1);
Intent intent = new Intent();
intent.putExtra("imageId", imagePath);
setResult(RESULT_OK, intent);
finish();
And here are my code in the activity with the ListView. I got some help here yesterday and I wonder if the while (cursor.moveToNext()){} part of the code is important for the ListView since it works without it?
Preciate some help! Thanks!
public class Activity_3 extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
listView=(ListView)findViewById(R.id.contactList);
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID};
// Get a cursor with all people
Cursor cursor = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,null,null, null);
//Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,null,null, null);
String[] fromColumn = {ContactsContract.Contacts.DISPLAY_NAME};
int[] toView = {R.id.contactItem };
while (cursor.moveToNext())
{
String Name=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String Number=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
startManagingCursor(cursor);
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.activity_3, cursor, fromColumn, toView );
listView.setAdapter(adapter);
}
}
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view , int position,
long id) {
// TODO Auto-generated method stub
do your operations here...
}
});
use this onitemclicklistener to listen to your listview clicks .

How can i convert this code so i can get the row from list view

I want to be able to fetch a row from a list view and populate textViews in a different activity. I want to be able to do this onclick of an item with the list view..
public class CBFilter extends Activity {
ListView RecipeNames;
Cursor cursor;
SimpleCursorAdapter adapter;
CBDataBaseHelper data;
SQLiteDatabase data2;
TextView RecipeText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecipeNames = (ListView) findViewById(R.id.List1);
RecipeNames.setTextFilterEnabled(true);
RecipeText = (TextView) findViewById(R.id.recipeText);
adapter = new SimpleCursorAdapter (this, 0, cursor, null, null);
data = new CBDataBaseHelper(this);
data.open();
cursor = data.query();
startManagingCursor(cursor);
String[] from = {CBDataBaseHelper.KEY_NAME};
int[] to = { R.id.recipeText};
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
RecipeNames.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void CreateNew(View view){
Intent myIntent = new Intent(this, CBCreate.class);
startActivity(myIntent);
}
}
How can i convert this code in order to achieve the required functionality.. thanks Stefan
try like this
public void onListItemClick(ListView parent, View v, int position, long id) {
String string = from[position]); // this depends on your Adapter ...
Intent i = new Intent(CheckData.this,ShowData.class);
i.putExtra("SELECTED", string);
startActivity(i);
i got it from this link , it will be use full for you :
Use of SQLite

Can't figure how to retrieve data of a particular row from a ListView

I am developing an android application pertaining to sms. I have managed to display a listView of all the messages in my android emulator, but i can't figure out what code should i write in the onItemClickListener such that whenever i click any row of my listview i should get the data(here.. message body) associated with it in another screen. What ahould i do about this?
My code is given below:
public class mainmenu extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle SavedInstanceState)
{
super.onCreate(SavedInstanceState);
setContentView(R.layout.main);
super.onStart();
{
final ListView list = (ListView) findViewById(R.id.list);
List<String> msgList = getSMS();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, msgList);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// TODO Auto-generated method stub
}
});
}
}
public List<String> getSMS()
{
List<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null,null,null);
while (cur.moveToNext())
{
String address=cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
return sms;
}
}
Please give me the code that i should write in the OnItemClickListener as per the specifications i mentioned above. It's a bit urgent.
Just use the adapter there as such:
String itemAtClickedIntex = (String)adapter.getItem(position);
Hope this helps your urgent request :) please don't forget to accept as it encourages us to keep contributing.
Best
-serkan

How to click a ListView item in Android

I'm trying to have another activity launch when a list item gets clicked. Below is my code:
public class AvoidForeclosure extends CustomListTitle {
/** Called when the activity is first created. */
private DbAdapter db;
private SimpleCursorAdapter clients;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = getListView();
setContentView(R.layout.main);
this.title.setText("Avoid Foreclosure");
db = new DbAdapter(this);
db.open();
fillData();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
int viewId = view.getId();
TextView theView = (TextView) findViewById(viewId);
String name = theView.getText().toString();
Cursor clientData = db.getClientByName(name);
Intent intent = new Intent();
intent.setClass(view.getContext(), CurrentMarketValue.class);
intent.putExtra("clientId", clientData.getInt(0));
startActivity(intent);
}
});
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = db.fetchAllClients();
startManagingCursor(c);
String[] from = new String[] { DbAdapter.KEY_NAME };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
clients = new SimpleCursorAdapter(this, R.layout.clientsrow, c, from, to);
setListAdapter(clients);
}
}
Yet when I click it, nothing happens at all. Any ideas?
Try switching this line:
ListView list = getListView();
to be after this one:
setContentView(R.layout.main);
Otherwise you'll be getting a handle to the ListActivity's default layout's ListView, rather than R.layout.main's listview (which is the one you really want).

Categories

Resources