Android load data from SQLite Database into next activity - android

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

Related

Is it possible to get data from my listview onclick

Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method

Android Studio ListView - null pointer exception when trying to extract text from selected item

I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);

How to select only one column in simplecursoradapter and pass it another activity?

I have a cursor in my main activity to query two columns of the database and display them using a simple cursor adapter.
private Cursor doQuery() {
return(db.getReadableDatabase().rawQuery("SELECT RestaurantID AS _id, RestaurantName, StoreNo "
+ "FROM RestaurantList ORDER BY RestaurantName", null));
}
public void onPostExecute() {
SimpleCursorAdapter adapter;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
adapter=new SimpleCursorAdapter(this, R.layout.activity_all_restaurants,
doQuery(), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore },
new int[] { R.id.title, R.id.value },
0);
}
else {
adapter=new SimpleCursorAdapter(this, R.layout.activity_all_restaurants,
doQuery(), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore },
new int[] { R.id.title, R.id.value });
}
setListAdapter(adapter);
}
What I want to do is that when the users click on a particular item, another activity will pop up giving the users more information, which means I need to display the data stored in many other columns of the same item too. My question is how I can do that. I thought I should use onListItemClick, but I don't know how to associate the item selected in the main activity to the new activity.
Also, in the main activity, I have two textviews in the list that display colRestaurantName and colRestaurantStore respectively. When I use onListItemClick, how can I just retrieve colRestaurantName?
I can do the following to retrieve the position, but I don't know how I can use it in the new activity:
#Override
public void onListItemClick(ListView parent, View v, int position,
long id){
Cursor c = ((SimpleCursorAdapter)parent.getAdapter()).getCursor();
selection = String.valueOf(c.getPosition());
Intent i = new Intent(AllRestaurants.this, RestaurantsInfo.class);
i.putExtra("restaurantSelection", selection);
startActivity(i);
}
Thanks.
implement onListItemClick for listview and get textview text and send it to next activity as:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
TextView tv = (TextView)v.findViewById(R.id.title);
String strcolRestaurantName=tv.getText().toString();
Intent intent =new Intent(CurrentActivity.this,NextActivity.class);
Bundle bundle = new Bundle();
bundle.putString("RestaurantName",strcolRestaurantName);
intent.putExtras(bundle);
startActivity(intent);
}}
and in NextActivity get Intent as in onCreate :
Intent i = getIntent();
Bundle extras = i.getExtras();
String strRestaurantName = extras.getString("RestaurantName");

How to get the index of a clicked item into another activity?

I have a activity (Contato) that shows a ListView of the contacts i have in my database(banco > contatos > nome, telefone (database>table>rows)). When a Contact Info is clicked a Dialog comes up and shows me the info and 3 button (OK/Alterar/Delete) when i hit Alterar it sends me to another activity(Alterarcontato) which i have 2 Edit Texts and 1 Button.
So when i get send to the Alterarcontato activity i still want to have the index o the Contact i clicked so I can change it's values ( with db.update).
Contato.java code ListView that shows the dialog and has it's index.
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
c = db.query( "contatos", campos, null, null, null, null, null);
c.moveToFirst();
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
user.setAdapter(adapter);
user.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
reg = position;
c.moveToPosition(reg);
String nome = c.getString(c.getColumnIndex("nome"));
String telefone = c.getString(c.getColumnIndex("telefone"));
ShowMessage(nome, telefone);
}
});
Alterarcontato.java code that has the editTexts and button to then alter the values.
EditText nomeA = (EditText) findViewById(R.id.etNomeAlter);
EditText telefoneA = (EditText) findViewById(R.id.etTelefoneAlter);
final String nomeB = nomeA.getText().toString();
final String telefoneB = telefoneA.getText().toString();
String where = "id=?";
String[] whereArgs = {"nome", "telefone"};
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("nome", nomeB);
dataToInsert.put("telefone", telefoneB);
db.update("contatos", dataToInsert, where, whereArgs);
But as shown in Contato.java code i don't have any ID for the contacts, so the String where = "id=?"; is kinda of invalid, so how do i get the index already from Contact.java to get shown in the Alterarcontato.java so when i put some writing in it and hit the button, the values change in the database?
Thank you.
setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
reg = position;
c.moveToPosition(reg);
String nome = c.getString(c.getColumnIndex("nome"));
String telefone = c.getString(c.getColumnIndex("telefone"));
ShowMessage(nome, telefone);
/// The above method will show the dialog with contact info right..? SO from the dialog you are launching the activity to edit the info. While starting the activity you have to pass the index. Like below :
Intent intent = new Intent(getApplicationContext(), Alterarcontato.class);
// the index is the variable which contains the index of the selected contact in your dialog.
intent.putExtra("key", index);
startActivity(intent);
<-- Alterarcontato.java -->
public class Alterarcontato extends Activity {
private Integer mIndex;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIndex = getIntent().getExtras().getInt("key");
}
}
You can try the given link, i hope this may help you
Contacts Contract API
Have a look at this description on the Android Developers' site. It provides good step-by-step instructions. Essentially, you have to create an Intent and use the putExtra() method to pass the data.
Edit: Also, have a look at this answer to a similar question about getting the row ID in the ListActivity using onListItemClick().

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

Categories

Resources