dataSource.getItemId(position) returns null - android

I'm trying to get the database id of a ListView member so that I can pass it to a new activity but the .getItemId(position) method of SimpleCursorAdapter is returning null, instead of the _id from the database. It was my understanding that this should return the _id field grabbed by the cursor, but it's not working out for me. Would love some suggestions
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("myDb", fields, null, null, null, null, null);
dataSource = new SimpleCursorAdapter(this, R.layout.row, data, fields, new int[] {R.id.idText, R.id.castName, R.id.castDescription});
data.moveToFirst();
final ListView view = getListView();
view.setHeaderDividersEnabled(true);
view.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));
setListAdapter(dataSource);
database.close();
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// Prepare intent
Intent newActivity = new Intent(getApplicationContext(), ItemIdTester.class);
newActivity.putExtra("itemId",dataSource.getItemId(position));
// start activity
startActivity(newActivity);
}
});

The adapter was returning null because of the headers added by
view.setHeaderDividersEnabled(true);
view.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));
I also started getting my data directly from the cursor. Here is the full onItemClickListener that fixed the issue
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Cursor cursor = (Cursor) dataSource.getItem(position-1);
Long itemId = cursor.getLong(0);
// Prepare intent
Intent newActivity = new Intent(getApplicationContext(), CastrRecorder.class);
newActivity.putExtra("itemId",itemId.toString());
// start activity
startActivity(newActivity);
}
});

Related

How to get data and View from a ListView

Hi everyone:
I hope someone can help me here,The Cursor generated by a Query populate the ListView with the Layout defined by simple_list_item_2.
To create the Intent i need the first string of the clicked View but in the String to Go i have something like
android.widget.TextView#411fbfb8
Now the code.
I can't understand where is the error.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, columns, ids, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
final ListView myList=(ListView)findViewById(R.id.listView1);
myList.setAdapter(adapter);
myList.setClickable(true);
/*
* Click Listener
*/
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id)
{
Log.v("io", "start");
Intent intent = new Intent(MainActivity.this, WorkActivity.class);
View buff = myList.getChildAt(position);
String toGo = buff.findViewById(android.R.id.text1).toString();
Log.v("io",toGo);
intent.putExtra("dname", toGo);
startActivity(intent);
}
} );
try:
String toGo = ((TextView)buff.findViewById(android.R.id.text1)).getText().toString()
inside your onItemClick you can retrieve data linked to your adapter through the AdapterView argument. Calling getItemAtPosition(int) you can access data associated with the selected item
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id)
{
Log.v("io", "start");
Intent intent = new Intent(MainActivity.this, WorkActivity.class);
View buff = myList.getChildAt(position);
String toGo = l.getItemAtPosition(position);
Log.v("io",toGo);
intent.putExtra("dname", toGo);
startActivity(intent);
}
} );
//
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id)
{
Log.v("io", "start");
Intent intent = new Intent(MainActivity.this, WorkActivity.class);
//View buff = myList.getChildAt(position);
// String toGo = buff.findViewById(android.R.id.text1).toString();
String toGo = (TextView)v.getText();
Log.v("io",toGo);
intent.putExtra("dname", toGo);
startActivity(intent);
}
} );
To get the view do as following:
LinearLayout row = (LinearLayout) ((LinearLayout)v);
Or RelativeLayout instead of LinearLayout if that your case
then apply the follwing code to get the text of TextView based on its order:
TextView column = (TextView)row.getChildAt(0);
String text = column.getText().toString();
Hope this help

Android load data from SQLite Database into next activity

I have a listView which loads data from SQLite database and right now I would want to implement an onclicklistener to the list. When users click on the list, it should bring them to the next activity and load the corresponding data into TextView. My question is how would I pass the data of the list for example it is a list of "Topics" and user click on the topic "My Home". I want to pass the topic "My Home" to the next activity so that I know which corresponding data to be retrieved respectively.
How do I go about it? Do I "putExtras" to the new Intent? or there is another way. Below are part of my codes which display the listview:
ListView listContent = (ListView) findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[] { SQLiteAdapter.KEY_CONTENT };
int[] to = new int[] { R.id.text };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
//Onclick ListView setlistener
listContent.setTextFilterEnabled(true);
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
EDITED:
This part is on the next activity.
Intent i = getIntent();
extraTopic = i.getStringExtra("SummTopic");
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic = \" " + extraTopic + " \" " , null);
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
I got an error while retrieving from database:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
Please help.
Thank you.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
Cursor c = (Cursor)parent.getItemAtPosition(position);
summaryIntent.putExtra("SummTopic", c.getString(c.getColumnIndex(SQLiteAdapter.KEY_CONTENT)));
startActivity(summaryIntent);
}
or you can pass id (summaryIntent.putExtra("SummTopicId", id);) of this row and "ask db" in next Activity for Topic with this id
EDIT:
protected void onCreate(Bundle savedInstanceState){
Intent i = getIntent();
String extraTopic = i.getStringExtra("SummTopic");
//or long extraTopic = i.getLongExtra("SummTopic"); if you put id there (which is better)
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
String[] args = new String[] { extraTopic };
//or String[] args = new String[] { Long.toString(extraTopic) }; with id version
Cursor singleRow = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic=?" , args);
//args is better then escaping special chars in query
//and it should be single row so we've changed var name :)
if(singleRow.moveToFirst()){ //we should do moveToFirst before we can use Cursor
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
//setup views and stuff ....
}else{
Toast.makeText(this, "Oops we did not find topic, detail activity was closed", Toast.LENGTH_SHORT).show();
finish();
}
}
After you have used setContentView(...) you need to reference your String and get the text such as...
EditText et = (EditText) findViewById(R.id.my_edit_text);
String theText = et.getText().toString();
To pass it to another Activity you use an Intent. Example...
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", theText);
startActivity(i);
In the new Activity (in onCreate()), you get the Intent and retrieve the String...
public class MyNewActivity extends Activity {
String uriString;
#Override
protected void onCreate(...) {
...
Intent i = getIntent();
uriString = i.getStringExtra("text_label");
}
}
EDITED :
to get String From Listview you can apply below code and get ITEM String and Pass it to Next Activity:
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ITEM=listContent.getItemAtPosition(position);
//Intent summaryIntent = new Intent(DocumentListActivity.this, // ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
You can use Intent for this.
Intent intent= new Intent(context,classname.class);
intent.putExtra("name",string);
You can get it in the target class name using intent.getextra().
I guess you are using an adapter to fill your list with some data. So you need to override getItem(int position) method in your adapter:
#Override
public Object getItem(int position) {
//Note that return type should be the same you you use to initilise items oof the adapter. E.g. String or some custom Topic class
Object someObject = mObjects[position];
return someObject;
}
Then you need to set an item click listener to you list
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object someObject = adapterView.getItemAtPosition(i);
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", someObject.toString());
startActivity(i);
}
});

In Android how to pass ListAdapter values to onItemClick?

I've got a functioning search interface on my app. Now I'm trying to make each search result list item clickable and display in a new activity. I've got them clickable, but I can't figure out how to pass the ListAdapter values (records) into the onItemClick method.
Here's my code so far:
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_MAKE,
DBAdapter.KEY_YEAR, DBAdapter.KEY_MAKE,
DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rDateTV, R.id.rYearTV,
R.id.rMakeTV, R.id.rModelTV };
final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
DBHelper.close();
// --- Click on list item ---
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//--- here's the problem: how do I pass the ListAdapter values into onItemClick. the below doesn't like .getText()
String sYear = (view.findViewById(R.id.rYearTV)).getText().toString();
String sMake = (view.findViewById(R.id.rMakeTV)).getText().toString();
String sModel = (view.findViewById(R.id.rModelTV)).getText().toString();
// -- then pass these strings to an intent to launch a new activity
}
});
// --- END click on list item ----
}
Any ideas? I'm a rookie here, so if you could show me the code, that would be AWSOME!
In OnItemClickListener.onItemClick call parent.getItemAtPosition(position). That method returns cursor which is set to the given position. Then get your data from that cursor. Don't close cursor inside OnItemClickListener.onItemClick.
for example:
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor)parent.getItemAtPosition(position)
String sMake = c.getString(c.getColumnIndexOrThrow(DBAdapter.KEY_MAKE));//get data from cursor
...
}
});

How to pass the name checked from checkbox to another activity

I am currently having a difficulty in passing the name from the checkbox from one activity to another activity. Actually the name should be inserted into my database table after it is checked and then it will be passed to the activity mentioned earlier. Anyone have any idea on doing it? Any help provided will be greatly appreciated.
For reference, the codes for my project.
BuddyDBAdapter buddyDB = new BuddyDBAdapter(this);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
ListView list = (ListView) findViewById(android.R.id.list);
//ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
Cursor cursor = null;
cursor = (Cursor) parent.getItemAtPosition(position);
Intent intent = new Intent(ContactsList.this, Create_Events.class);
intent.putExtra("name", cursor.getString(cursor.getColumnIndex(buddyDB.KEY_NAME)));
startActivity(intent);
}
});
Uri allContacts = Uri.parse("content://contacts/people");
Cursor c = managedQuery(allContacts, null, null, null, null);
String[] columns = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
int[] views = new int[] {R.id.contactCheckbox};
startManagingCursor(c);
SimpleCursorAdapter friendsAdapter = new SimpleCursorAdapter(this, R.layout.contacts_list, c, columns, views);
this.setListAdapter(friendsAdapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
buddyDB.open();
//long name_id;
super.onListItemClick(l, v, position, id);
Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);
/*TextView contactName = (TextView) v.findViewById(R.id.contactName);
String NameValue = contactName.getText().toString();
name_id = buddyDB.insertNames(NameValue);
Toast.makeText(getBaseContext(),
"Selected: " + buddiesList[position], Toast.LENGTH_SHORT).show();
buddyDB.close();*/
nameCheck = (CheckBox) v.findViewById(R.id.contactCheckbox);
nameCheck.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{
long name_id;
String NameValue = nameCheck.getText().toString();
name_id = buddyDB.insertNames(NameValue);
/*if(isChecked)
{
nameCheck = 1;
}else
{
nameCheck = 0;
}*/
}
});
buddyDB.close();
}
}
Again, any help from anyone will be greatly appreciated. Thanks a lot!
this may helps you
To pass the name values from oneActivity
Intent n = new Intent(actA.this , actB.class);
n.putExtra("name", NameValue);
startActivity(n);
To get the given values
Intent igetlist = getIntent();
String singleid = igetlist.getExtras().getString("name");
use this code where you want to pass parameter to another activity.
Intent n = new Intent(actA.this , actB.class);
n.putExtra("name", NameValue);
startActivity(n);

Passing data from ListView to other Activity

I have a ListView where each ListItem has 2 TextViews in it's layout. I'd like to pass the values of those TextViews to another activity when the ListItem is clicked. All my attempts have failed, so i ask you how can i do that? How can i pass the SQLite ROW_ID, the values of R.id.text1 and R.id.text2?
Cursor cursor = database.getAllNames();
adapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor,
new String[] { Database.KEY_DATE , Database.KEY_NAME },
new int[] {R.id.text1, R.id.text2}, 0);
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(SendingData.this, ReceivingData.class);
intent.putExtra("id", id); //this should pass the SQLite ROW_ID
intent.putExtra("date", date); //this should pass the value of R.id.text1
intent.putExtra("name", name); //this should pass the value of R.id.text2
startActivity(intent);
}
});
Use this to retrieve the data from the SQLLite database.
cursor.getString(c.getColumnIndex(Database.columns[i])) // i is the index of the column whose details you want to fetch
And then you can pass them as parameters in intent.putExtra.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = null;
cursor = (Cursor) parent.getItemAtPosition(position);
Intent intent = new Intent(SendingData.this, ReceivingData.class);
intent.putExtra("id", cursor.getInt(cursor.getColumnIndex(Database.columns[0]))); //assuming that the first column in your database table is the row_id
intent.putExtra("date", cursor.getString(cursor.getColumnIndex(Database.columns[1]))); //assuming that the second column in your database table is the text1
intent.putExtra("name", cursor.getString(cursor.getColumnIndex(Database.columns[2]))); //assuming that the third column in your database table is the text2
startActivity(intent);
}
});
You can do it by taking the data directly from the view without having to access the cursor (and using the row id passed in the onItemClick method as you are already doing).:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text1);
String date = text1.getText().tostring();
String name = text2.getText().tostring();
Intent intent = new Intent(SendingData.this, ReceivingData.class);
intent.putExtra("id", id); //this should pass the SQLite ROW_ID
intent.putExtra("date", date); //this should pass the value of R.id.text1
intent.putExtra("name", name); //this should pass the value of R.id.text2
startActivity(intent);
}
});

Categories

Resources