Android - Passing ID from SQLite into a new activity using .putExtra - android

I am writing a note taking app within android eclipse. My app currently selects all the notes from within the SQLite database and uses them to populate a ListView. This ListView is clickable, and currently redirects the user to the EditNote activity.
However, I would like to be able to populate the EditTexts within the EditNote activity based on the ID of the ListView note that is clicked.
(So that if I clicked the first ListView Item and it's ID was 2 then the value 2 would be passed through to EditNote)
This would require obtaining the ID of the ListView Item that was clicked, and then passing it through using .putExtra(); to the EditNote activity.
So my question is: how would I obtain the ID and then pass it through to the EditNote activity? So that I can then use the ID to make additional querys on that activity.
Thank you very much for your time.
Any additional questions I will answer to the best of my ability.
Initialising things
DatabaseHelper dbh;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
Context mCtx;
ListView lv;
onCreate method with onClickListeners
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
refreshData();
mCtx = this;
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Intent i = new Intent(mCtx, EditNote.class);
i.putExtra("ID", listItems.get(position));
startActivity(i);
}
});
refreshData method (used to populate the ListView)
public void refreshData(){
dbh = new DatabaseHelper(this);
dbh.open();
adapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);
ArrayList<String[]> searchResult = new ArrayList<String[]>();
//EditText searchTitle = (EditText) findViewById(R.id.searchC);
listItems.clear();
searchResult = dbh.fetchNotes("");
//searchResult = dbh.fetchNotes(searchTitle.getText().toString());
String title = "", note = "", id = "";
for (int count = 0 ; count < searchResult.size() ; count++) {
note = searchResult.get(count)[2];
title = searchResult.get(count)[1];
id = searchResult.get(count)[0];
listItems.add(title);
}
adapter.notifyDataSetChanged();
}
/*private void setID(String setID) {
this.id = setID;
}
private String getID(){
return id;
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
DatabaseHelper activity - fetchNotes - used to query the database
public ArrayList<String[]> fetchNotes(String title) throws SQLException {
ArrayList<String[]> myArray = new ArrayList<String[]>();
int pointer = 0;
Cursor mCursor = mDb.query(TABLE_NAME, new String[] {"_id", "title",
"note"}, null, null,
null, null, "_id");
int idColumn = mCursor.getColumnIndex("_id");
int titleColumn = mCursor.getColumnIndex("title");
int noteColumn = mCursor.getColumnIndex("note");
if (mCursor != null){
//If possible move to the first record within the cursor
if (mCursor.moveToFirst()){
do {
//for each record add a new string array to our Array List
myArray.add(new String[3]);
//
myArray.get(pointer)[0] = mCursor.getString(idColumn);
//Save the note into the string array
myArray.get(pointer)[1] = mCursor.getString(titleColumn);
//Save the title into the string array
myArray.get(pointer)[2] = mCursor.getString(noteColumn);
//increment our pointer variable.
pointer++;
} while (mCursor.moveToNext()); // If possible move to the next record
} else {
myArray.add(new String[3]);
myArray.get(pointer)[0] = "";
myArray.get(pointer)[1] = "";
myArray.get(pointer)[2] = "";
}
}
return myArray;
}
Also here's my create table, just in case
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_NAME + " (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT NOT NULL, " +
"note TEXT NOT NULL); ";

I will try to help you also i think your code can be more optimized ...
in your fetchNotes() just return the cursor instead of creating ArrayList if suppose you created ArrayList here and it occupies 100 entries again in the caller function you are using the listItems ArrayList... i know android has garbage collector but why to employ it if there is option to avoid ?
your myArray is String[] ArrayList but your listItems is not hence you can only access the titles coz this is wat you are storing here listItems.add(title);
a. So you can either use listItems directly in fetchNotes() like MainActivity.listitems (supposing listItem is declared in MainActivity class ) use after declaring ArrayList<String[]> listItems=new ArrayList<String[]>(); as public static ArrayList<String[]> listItems=new ArrayList<String[]>();
or
b. you can simply return the cursor only and do exactly like the myArray type of operation on listItems.
Now you can access the "id" by refering the index you stored the id in listItems.
listItems.get(position)[2] ( supposing you stored the id at index 2 ).
I tried to keep it as simple as possible and expect that it will help you ...

Not sure I understand this completely. Are you not passing the "title" already and your database helper can fetch results using "title"? Is this not working or do you want to optimize it by passing the ID? Even if you want to pass the ID, you can do that using the same mechanism.

Related

Displaying the sum value of a SQLite query in a textview

I am building a budget database and I can get all the transactions into the listview and displayed on the screen. I have created a textview to hold the sum of all the transaction values but can't figure out how to get it to display in the textview. I get the following error:
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory)' on a null
object reference.
Here is the code I am trying to get to work:
SQLiteDatabase database = mDbHelper.getReadableDatabase();
public int cmIncomeSum() {
int total = 0;
Cursor sumQuery = database.rawQuery("SELECT SUM(income) FROM transactions WHERE income >=0 AND expense ISNULL AND strftime('%m',date)=strftime('%m',date('now')) AND strftime('%Y',date)=strftime('%Y',date('now'))", null);
if (sumQuery.moveToFirst()) {
total = sumQuery.getInt(0);
}
return total;
}
and the textview:
TextView cmIncomeSumTextView = (TextView) findViewById(R.id.cm_income_sum_text_view);
cmIncomeSumTextView.setText(sum);
and here is the entire activity:
public class CMIncomeTransactionsActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
/** Identifier for the transaction data loader */
private static final int TRANSACTION_LOADER = 0;
/** Adapter for the ListView */
IncomeCursorAdapter mCursorAdapter;
// Database helper object //
private BudgetDbHelper mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cm_income_transactions);
// Setup FAB to open EditorActivity
Button fab = (Button) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CMIncomeTransactionsActivity.this, IncomeEditorActivity.class);
startActivity(intent);
}
});
// Find the ListView which will be populated with the transaction data
ListView incomeListView = (ListView) findViewById(R.id.list);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
incomeListView.setEmptyView(emptyView);
// Setup an Adapter to create a list item for each row of transaction data in the Cursor.
mCursorAdapter = new IncomeCursorAdapter(this, null);
incomeListView.setAdapter(mCursorAdapter);
// Setup the item click listener
incomeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Create new intent to go to {#link EditorActivity}
Intent intent = new Intent(CMIncomeTransactionsActivity.this, IncomeEditorActivity.class);
// Form the content URI that represents the specific transaction that was clicked on,
// by appending the "id" (passed as input to this method) onto the
// {#link BudgetEntry#CONTENT_URI}.
Uri currentTransactionUri = ContentUris.withAppendedId(BudgetEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentTransactionUri);
// Launch the {#link EditorActivity} to display the data for the current transaction.
startActivity(intent);
}
});
// Kick off the loader
getLoaderManager().initLoader(TRANSACTION_LOADER, null, this);
// Define query for the SUM of the current month income and display it on the screen//
TextView cmIncomeSumTextView = (TextView) findViewById(R.id.cm_income_sum_text_view);
cmIncomeSumTextView.setText(cmIncomeSum());
}
SQLiteDatabase database = mDbHelper.getReadableDatabase();
public int cmIncomeSum() {
int total = 0;
Cursor sumQuery = database.rawQuery("SELECT SUM(income) FROM transactions WHERE income >=0 AND expense ISNULL AND strftime('%m',date)=strftime('%m',date('now')) AND strftime('%Y',date)=strftime('%Y',date('now'))", null);
if (sumQuery.moveToFirst()) {
total = sumQuery.getInt(0);
}
return total;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// Define a projection that specifies the columns from the table we care about.
String[] projection = {
BudgetEntry._ID,
BudgetEntry.COLUMN_DATE,
BudgetEntry.COLUMN_DESCRIPTION,
BudgetEntry.COLUMN_INCOME,
BudgetEntry.COLUMN_INCOME_CATEGORY,
BudgetEntry.COLUMN_EXPENSE,
BudgetEntry.COLUMN_STATUS};
// Where clause to only display income transactions //
String selection = "income >=0 AND expense ISNULL AND strftime('%m',date)=strftime('%m',date('now')) AND strftime('%Y',date)=strftime('%Y',date('now'))";
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
BudgetEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor //
selection, // Where selection clause /
null, // selection arguments //
BudgetEntry.COLUMN_DATE); // Default sort order //
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Update {#link IncomeCursorAdapter} with this new cursor containing updated transaction data
mCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// Callback called when the data needs to be deleted
mCursorAdapter.swapCursor(null);
}
}
I have looked at many different posts here and none have been helpful.
Please help!
for example, I want show name of the characters that family is "Heard" or "Carry" or everybody you want who to be saved in a database and saved that in an array list:
in one of a method of the MyDataBaseClass:
public Cursor showName(String family){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery(" SELECT Name FROM "+TBL_NAME+ " WHERE Family==?" , new String[]{family});
return data;
}
and in main scope:
MyDataBaseClass db = new MyDataBaseClass();
Cursor res = db.showName("Heard");
if (res.getCount() == 0) {
//do nothing
} else {
ArrayList<String> list = new ArrayList<>();
while (res.moveToNext()) {
list.add(res.getString(0));
}
}
this answer may not exactly what you want to do but I hope to help you
You have not initialized mDbHelper in CMIncomeTransactionsActivity class, so initialize mDbHelper in onCreate and try.

Get ID from database onClick ListView

I'm using SQLite in my app. I have a listView which is populated with values from the database.
When I click on an item from the listview, I go to another page, and I would like ( with an intent), to transfer the ID FROM THE DATABASE. The problem is that I'm only transfering the ID from the position of my listView, which is wrong. For example, let's say I have :
ID Name
1 David
2 Joseph
My listView will display both names. But if I delete David, the ID i'm getting when i click in Joseph is 1 and not 2 . And that's the problem !
So : I want to retrieve the ID from my database and not from my listView when I click on an item
Here's my method in my helper : UPDATED !
public Cursor getAllCours()
{
String Query = ("select ID as _id, nom from " + TABLE_COURS);
Open();
Cursor cursor = db.rawQuery(Query, null);
return cursor;
}
And how I display it in my Activity :
Cursor cursor = dbhelper.getAllCours();
String[] from = { "nom" }; int[] to = { android.R.id.text1 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from, to, 0);
lv.setAdapter(adapter);
And finally, my listviewClickListener :
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//I THINK THE ERROR IS HERE !
long itemid= lv.getItemIdAtPosition(i);
int id= (int)itemid;
String a =lv.getItemAtPosition(i).toString();
Intent b = new Intent(AffichageCours.this,AffichageNotes.class);
Bundle args = new Bundle();
args.putString("nom_cours",a);
args.putInt("id",id);
b.putExtras(args);
startActivity(b);
}
});
}
My TABLE_COURS columns:
private static final String TABLE_COURS = "cours";
private static final String COLONNE_IDCOURS = "ID";
private static final String COLONNE_COURS = "nom";
private static final String CREATE_COURS ="CREATE TABLE cours " +
"("+COLONNE_IDCOURS+" INTEGER PRIMARY KEY AUTOINCREMENT , "
+COLONNE_COURS+" TEXT NOT NULL)";
How i delete with my Context Menu :
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId())
{
case R.id.supprimer:
dbhelper.deleteCours(lv.getItemAtPosition(info.position).toString());
adapter.remove(adapter.getItem(info.position)); //the error is here..
adapter.notifyDataSetChanged();
return true;
Thank you guys !
I think the problem is that you are asking for the Id of the row in the ListView not the actual data that row is holding up. In the onItemClick method change this:
long itemid= lv.getItemIdAtPosition(i);
For this:
String courId = adapter.getItem(i);
The key here is to try to get the data from the ArrayAdapter not directly from the ListView.
You should have use Java Objects so it will be easy for you.
Suppost you have stored Contacts in dataBase(contains fields: Name, Mobile and Address). So create a POJO for that:
class Contacts{
private String name;
private String mobile;
private String address;
//write getters and setters
}
Then, whenever you are accessing database fetch all contacts you want to show and store in ArrayList<Contacts> mContactList;
And then pass this list in your ListView's adapter to show data in listView.
CustomAdapter adapter = new CustomAdapter(context, layoutResource, mContactList);
Then you can retrieve the object on clicking a particular list item on the basis of position;
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Contacts contact = mContactList.get(i);
// now you can do whatever you want;
}
});
Since you are not using a custom adapter, why dont you try this inside onItemClickListener
String idThatYouWant = listeCours.get(i).getId();

android how to sync onitemclicklistener listview id and database id

this is a succesor to this question
At first everything worked fine but after 2 deletes the misery starts. The database entries start with ID 1, then 2 and so on. Lets say I have three database entries. The listview IDs for these three entries are 2,1 and 0.
The database entries are 1,2 and 3. 1 and 2 will be deleted with the onitemclicklistener but since the listview doesn´t have an ID 3, the corresponding database entry will never ever be deleted.
So the question is, how can I "sync" those two IDs?
Listview-Class
public class anzeigen extends AppCompatActivity {
private static final String TAG = anlegen.class.getSimpleName();
private static final String FILENAME = TAG + ".kdf";
private List valueList = new ArrayList<String>();
final VorgangDataSource dataSource = new VorgangDataSource(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anzeigen);
Log.d(TAG,"Die Datenquelle wird geöffnet!");
dataSource.open();
final List<vorgangsdaten> vorgangsdatenList = dataSource.getAllVorgangsDaten();
final ArrayAdapter<vorgangsdaten> VorgangArrayAdapter = new ArrayAdapter<>(
this,
R.layout.mylistlayout,
vorgangsdatenList
);
final ListView lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(VorgangArrayAdapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s_id = String.valueOf(id);
Log.d(s_id,"id_in_onitem");
String p_id = String.valueOf(position);
Log.d(p_id,"position_on_item");
int pos = position;
vorgangsdatenList.remove(pos);
dataSource.deleteRow(id);
VorgangArrayAdapter.notifyDataSetChanged();
}
});
//ActionBar Costumization
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setIcon(R.drawable.search1);
ab.setDisplayShowHomeEnabled(true);
ab.setDisplayUseLogoEnabled(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
dataSource.close();
}
}
deleteRow-Method:
public void deleteRow(long id){
String s_id;
s_id = String.valueOf(id);
Log.d(s_id,"id_value");
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
long deleteID = database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
String s_del = String.valueOf(deleteID);
Log.d(s_del,"delete_row_value");
}
If you need more code just let me know :)
You have no synchronicity between your Database and the ListView items.
When selecting the data, select the ID from the table, and keep it in memory as well.
Since vorgangsdaten looks german or sweden, I am having trouble understanding the meaning of those words. The ListView has its own "id" for each item, to keep a list of them shown, and the rest "hidden". What you must do is have an Object with details that are syncronized with the database, and when a list item is clicked, the "list id" is used to query an Object and delete from the database.
An example would be:
ArrayList<MyObject> arrayListData = new ArrayList<>();
ArrayList<String> arrayListNames = new ArrayList<>();
MyObject stuffs = database.query(); // In here, fetch the data
/* I am simplifing the MyObject to [String name, String aValue, int aNumber] */
for(MyObject s: stuffs){
arrayListData.add(s);
arrayListNames.add(s.name);
}
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
arrayListNames
);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyObject thing = arrayListData.get(position);
database.delete(thing.aNumber);
}
}
);
listView.setAdapter(arrayAdapter);
After trying Bonattis answer and experimenting a little bit I found another answer.
deleteRow-Method
public void deleteRow(long id){
String s_id; //String for long id
s_id = String.valueOf(id); //assign String value of id
String s_rowId = null; //String for rowid
long rowId = 0;
long deleteId = 0;
String s_deleteId = null;
Log.d(s_id,"id_value");
Cursor cursor = database.query(VorgangDbHelper.TABLE_VORGAENGE_LIST,columns,null,null,null,null,null);
if(cursor.moveToFirst()) {
s_rowId = cursor.getString(cursor.getColumnIndex(VorgangDbHelper.COLUMN_ID));
rowId = Long.parseLong(s_rowId);
deleteId = rowId + id;
s_deleteId = String.valueOf(deleteId);
Log.d(s_rowId,"rowID");
Log.d(s_deleteId,"deleteID");
}
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_deleteId});
}
How does it work now?
So the deleteRow-Method(dRM) gets the id of the first database entry (s_rowId) and converts it to long (rowId).
Now I take the long id passed from the listview and add it to rowId which is my deleteId. With this I have the correct database value to what I clicked in the listview and can pass it over to database.delete

How to get String value of an object instead of object values?

I want to populate spinner from sqlite database. After I am retrieving the relevant data it showed junk values. Could you please help me to fix this. I will attach my codes here.
--java File--
public class AddNewMovieActivity extends AppCompatActivity {
private Spinner movieTypes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_movie);
movieTypes = (Spinner) findViewById(R.id.spinMovieType);
loadSpinnerData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_add_new_movie, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void loadSpinnerData() {
// database handler
DBHelper db = new DBHelper(this);
// Spinner Drop down elements
List<MovieType> lables = db.getAllMovieTypes();
// Creating adapter for spinner
ArrayAdapter<MovieType> dataAdapter = new ArrayAdapter<MovieType>(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
movieTypes.setAdapter(dataAdapter);
}
}
-- DBHelper--
public List<MovieType> getAllMovieTypes() {
SQLiteDatabase db = getReadableDatabase();
List<MovieType> lst = new ArrayList<MovieType>();
Cursor cursor = db.query(TABLE_MOVIE_TYPE, null, COLUMN_STATUS + "=?", new String[]{"A"}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String type = cursor.getString(1).toString();
MovieType movieType = new MovieType(type);
movieType.setTypeId(cursor.getInt(0));
lst.add(movieType);
cursor.moveToNext();
}
}
db.close();
return lst;
}
I just want to show the movie types from the database. Please help me. this code returns the object values. but I need the string value of it. I have tried to convert my object to string. but I couldn't find a proper way to fix it. Actually I am very new to Android. so please help me.
What you can do is to Override toString() method in your MovieType class
public class MovieType{
//Whatever fields you have here
//Override toString()
#Override
public String toString() {
return your_field_name;
/***put the field name which you want to show in spinner
Or
You can append multiple fileds
return field1 + field2+......;
***/
}
}
And your all set, you would then see the value of the field in your spinner, what you have set in toString() method.
You can make custom adapter or you can make your list of String type.
As you have mentioned that you just want to show movies type. You can do this in your getAllMovieTypes() function.
public List<String> getAllMovieTypes() {
SQLiteDatabase db = getReadableDatabase();
List<String> lst = new ArrayList<String>();
Cursor cursor = db.query(TABLE_MOVIE_TYPE, null, COLUMN_STATUS + "=?", new String[]{"A"}, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()){
String type = cursor.getString(1).toString();
lst.add(type);
cursor.moveToNext();
}
}
db.close();
return lst;
}
Now, you can display only type.

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

Categories

Resources