Move to another activity by click on listview item, android - android

I tried to make an android app, that populate some data from sqlite database to a list view
using ArrayAdapter.
The list where I store data is like this:
private String[] allUserColumns = { MySQLiteHelper.COLUMN_USERID,
MySQLiteHelper.COLUMN_USERNAME };
I want to move to another activity passing the ID related to user name by click at a listview item.
I know that I should use setOnItemClickListener method
but actually I don't know how to do that.
I mean how to get the ID, and how to set the setOnItemClickListener Method to make such task.
please any one can help me with a specific code ?

i have done this with this way
first fire query like
public Cursor columnValues() throws SQLException{
Cursor mCursor = db.query(Player_Table,
new String[] {Player_Name,_id},null,null, null, null, null);
//Cursor mCursor = mDb.rawQuery("Select",null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
then receive like this
ArrayList<String> first = new ArrayList<String>();
ArrayList<String> id_list = new ArrayList<String>();
cursor = dbm.columnValues();
cursor.moveToFirst();
startManagingCursor(cursor);
for(int i=0;i<cursor.getCount();i++){
// Received values of player name
// from player table
String reciv = cursor.getString(cursor.getColumnIndex(DBManager.Player_Name));
String P_id= cursor.getString(cursor.getColumnIndex(DBManager._id));
first.add(reciv);
id_list.add(P_id);
cursor.moveToNext();
}
//ARRAY OF ID
String[] _id = id_list.toArray(new
String[id_list.size()]);
player.setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1 , first));
player.setOnItemClickListener(Activity.this);
and then the click listener
#Override
public void onItemClick(AdapterView arg0, View arg1, int position,
long id) {
i = new Intent(Add_Modify_Delete_Player.this,
ModifyDeletePlayer.class);
System.out.println(_id[position]);
i.putExtra("Id", _id[position]);
startActivity(i);
}

Related

click row item but return all the rows in cursor used to build the list

I use SimpleCursorAdapter build a list. And I want to start another activity when I click one of the rows. code as following:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list);
listView = (ListView) findViewById(R.id.user_list);
db.open();
fillData();
.......
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor selectedItem = (Cursor) listView.getAdapter().getItem(position);
Log.d("#####", selectedItem.getCount() +"");
// return total number of the cursor using to build the list.
selectedItem.moveToFirst();
.......
}
});
}
private void fillData() {
Cursor c = db.fetchAllSenders();
startManagingCursor(c);
String[] from = new String[] {PeerContract.KEY_NAME};
int[] to = new int[] {R.id.user_list_row_name};
adapter = new SimpleCursorAdapter(this, R.layout.user_list_row, c, from, to, 0);
listView.setAdapter(adapter);
}
But int the LogCat Log.d("#####", selectedItem.getCount() +""); always return the total number of rows in cursor used to build the list. For example, there are 4 rows in the list, after I click one row in the list, the LogCat will display #####:4. But it supposes to be 1 when I click just one item.
Thanks in advance.
It is coming 4 because there is only one cursor reference with the adapter. the method getAdapter().getItem(position) will return you the same cursor object but it will move the cursor to the position for which you requested getItem().
So whenever you call getItem(position), it will not give you a new cursor object, it will give you the same cursor object, moving it to the current position

SQLite delete not actually deleting

I have a SQLite database that I am saving user selected data to. This data will be visible in a listview and if you long click on the data it will delete that item. This is working as I see the item disappear from the listview, but when I restart the application and all the listview items are brought back in from the database, everything that was deleted is coming back. I am using this statement:
public void deleteAlarmEntry(int pos){
Log.i("Deleting item from pos: ", String.valueOf(pos));
db.delete(MySQLHelper.TABLE_NAME, MySQLHelper.ID_COL + "='" + pos + "'", null);
}
I can see the statement being called in the logs. Is there a better way to make sure that the statement is executing correctly? Is something wrong here?
Here is my removeItem method called in the MainActivity on long click of the listview item:
public void removeItem(int position) {
alarmItemArray.remove(position);
dataSource.deleteAlarmEntry(position);
alarmAdapter.notifyDataSetChanged();
}
The dataSource.deleteAlarmEntry() calls the above database remove.
Also, on application startup I am bringing the entries into a temp arraylist and then parsing the time to get the adapter arraylist like so:
dataSource = new WeatherDataSource(this);
dataSource.open();
ArrayList<AlarmEntry> alarmEntries = (ArrayList<AlarmEntry>) dataSource.getAllWeatherEntries();
alarmItemArray = getTimeFromEntries(alarmEntries);
alarmAdapter = new ArrayAdapter<String>(this,
R.layout.activity_alarm_item, R.id.time, alarmItemArray);
lv = (MyListView) findViewById(R.id.listview);
lv.setAdapter(alarmAdapter);
Here is the database's getAllWeatherEntries:
public List<AlarmEntry> getAllWeatherEntries(){
List<AlarmEntry> weatherEntry = new ArrayList<AlarmEntry>();
Cursor cursor = db.query(MySQLHelper.TABLE_NAME, cols, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
AlarmEntry m = cursorToEntry(cursor);
weatherEntry.add(m);
Log.i("Get all weather entries", m.getTime());
cursor.moveToNext();
}
cursor.close();
return weatherEntry;
}
You're just passing everything from that item to your query.
In OnContextMenuItemSelected you will need to do something similar to the below; you will need to change the parameters of your deleteAlarmEntry to receive a string instead of an int.
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String selectedID;
// adapter is the Adapter from creating the listview
selectedID = String.valueOf(adapter.getItemId(info.position));
deleteAlarmEntry(selectedID);
}
You will also need to modify the db.delete to return a number, ie int result = db.delete() per the function. http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
EDIT:
you may want to use OnItemLongClickListener instead of OnLongClickListener
http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String id = String.valueOf(alarmAdapter.getItemId(position);
removeItem(id);
}
});
SECOND EDIT:
Try this for cursoradapter, i'd recommend using a simple cursor adapter:
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
String[] from = new String[]{"time"}; //enter your time column name here
int[] to = new int[]{R.id.time};
Cursor cursor = db.query(MySQLHelper.TABLE_NAME, cols, null, null, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.activity_alarm_item, cursor, from, to);
lv.setAdapter(adapter);
use,
public void deleteAlarmEntry(int pos) {
db.delete(MySQLHelper.TABLE_NAME, MySQLHelper.ID_COL + "=?", new String[]{pos + ""});
}

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().

setOnItemClickListener on ListView how to show database values

I have a ListView with Contact info(name, phone number) so i want when i click in the contact name i want to show its name and phone number in a dialog box (which a have a code for it already) which is:
public void ShowMessage(String titulo,String msg){
AlertDialog.Builder dialogo = new AlertDialog.Builder(this);
dialogo.setMessage(msg);
dialogo.setTitle(titulo);
dialogo.setNeutralButton("OK", null);
dialogo.show();
}
Then i have seen about the setOnItemClickListener but when i try to put this up in my .java file it doens't even suggest the code, does anyone know why or how to do it?
EDIT:
//LISTVIEW database CONTATO
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
Cursor c = db.query( "contatos", campos, null, null, null, null, null);
c.moveToFirst();
String lista = "";
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);
that is the code of my listview/adapter
OBS: better if you can explain (no tuts link (better if possible))
(I see that you are processing a Cursor yourself and using an ArrayAdapter, understand that a SimpleCursorAdapter does this for you. See my note below.)
Anyway, change your Cursor into a class variable and try adding this in onCreate():
user.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
c.moveToPosition(position);
String nome = c.getString(c.getColumnIndex("nome"));
String telefone = c.getString(c.getColumnIndex("telefone"));
showMessage(nome, telefone);
}
});
You aren't specific on how the title and message correlate to the contact's name, so I made that part up.
A class variable is simply a variable defined in a place that makes it visible to the entire class. For example this turns c into a class variable so you can use it in onItemClick():
public class MyActivity extends Activity {
Cursor c;
public void onCreate(...) {
...
c = db.query( "contatos", campos, null, null, null, null, "nome");
...
}
}
Understand that you can simplify how you read your contacts:
list = new ArrayList<String>();
Cursor c = db.query("contatos", campos, null, null, null, null, "nome");
int nameIndex = c.getColumnIndex("nome");
while(c.moveToNext()) {
list.add(c.getString(nameIndex));
}
I made a couple changes:
You only need to fetch the index of the "nome" column once, it won't change unless you change the Cursor.
moveToFirst() returns true if there is data to read and false if not.
This is faster to write and faster to run than your existing method.
A SimpleCursorAdapter is the standard adapter to bind data from your Cursor to a ListView. This will give you the same results as your original method, but with much less code.
How to use a SimpleCursorAdapter:
Cursor c = db.query("contatos", campos, null, null, null, null, "nome");
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c,
new String[] {"nome"}, new int[] {android.R.id.text1});
user.setAdapter(adapter);
Assuming the adapter used in your ListView has a custom type (I'll call it ContactInfo), the following should work.
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Get String provided to this particular row
ContactInfo info = getListView().getAdapter().getItem(position);
// Construct title, message etc from information within info
showMessage("Contact Info", info);
}
});

onListItemClick, what statement do I need to get the value?

i can add to a db and list as a listview.
When I click a list item using onListItemClick, what statement do I
need to get the value?
Thanks in advance.
public class Main extends ListActivity {
private static String[] FROM = { _ID, DESCRIPTION, UN };
private static String ORDER_BY = DESCRIPTION + " ASC";
private static int[] TO = {R.id.itemrowid, R.id.itemdescription, R.id.itemun };
private EventsData events;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
events = new EventsData(this);
try {
Cursor cursor = getEvents();
showEvents(cursor);
} finally {
events.close();
}
**public void onListItemClick(ListView parent, View v, int position, long id) {
// What statement to put here to get the value of _ID,DESCRIPTION, UN
// selected**?
}
private Cursor getEvents() {
// Perform a managed query. The Activity will handle closing
// and re-querying the cursor when needed.
SQLiteDatabase db = events.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null,
null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
private void showEvents(Cursor cursor) {
// Set up data binding
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
First, you need to obtain item at clicked position:
Cursor cursor = getListAdapter().getItem(position);
Then you can get data from this cursor (I don't know what types do you use, so just for example it will be int and String):
int id = cursor.getInt(cursor.getColumnIndex(_ID));
String description = cursor.getString(cursor.getColumnIndex(DESCRIPTION));
See documentation for Cursor's available methods.
Adding to sergey answer you can also directly see what View was clicked and use findViewById() to find the components, therefore, the values you want.
This is just an alternative being the method Sergey much less 'patchy'

Categories

Resources