Can't get selected item text from ListView - android

I'm simply trying to get the text being displayed in the ListView for the row the user clicks.
List view and adapter
ListView listCurrent = (ListView)findViewById(R.id.currentlinkslist);
try {
SQLiteOpenHelper tractionDatabaseHelper = new TractionDatabaseHelper(this);
db = tractionDatabaseHelper.getReadableDatabase();
String query = "SELECT _id, QUESTION FROM QUESTION";
cursor = db.rawQuery(query, null);
CursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"QUESTION"},
new int[]{android.R.id.text1},0);
listCurrent.setAdapter(listAdapter);
}catch(SQLiteException e) {
Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT).show();
}
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listCurrent,
View v, int position, long id) {
String selectedItem = listCurrent.getItemAtPosition(position).toString();
Toast.makeText(AssociateActivity.this,
selectedItem , Toast.LENGTH_SHORT).show();
}
};
listCurrent.setOnItemClickListener(itemClickListener);
From everything I've seen, this code in the AdapterView.OnItemClickListener should fetch the description:
String selectedItem = listCurrent.getItemAtPosition(position).toString();
Toast.makeText(AssociateActivity.this, selectedItem, Toast.LENGTH_SHORT).show();
Instead, I keep getting:
What am I doing wrong?

the method getItemAtPosition() is returning a SQLiteCursor object and this kind of object has no implementations of the method toString(). So in this case you have to return the cursor itself and parse it to your object before you call toString() method.
SQLiteCursor cursor = (SQLiteCursor) listCurrent.getItemAtPosition(position);
String selectedItem = cursor.getString(columIndex); //columIndex is not the position
Toast.makeText(AssociateActivity.this, selectedItem, Toast.LENGTH_SHORT).show();

Related

Loading two SQL columns into a listview but only need to display the first column Android

I am using an sqllite database to store two columns which are phonename and phonenumber. I am using an arrayList to iterate through the data and display the phonename in a listview which is working, but I also need to iterate through the phonenumber column under the same listview as well. I only need the phonename to be showing in the listview.
This is for when the user has selected the item in the listview, it shows the selected phonename and phonenumber, which at the moment it is only currently showing the phonename and showing blank for phonenumber for obvious reasons.
DataDBAdapter
public long insert(String phonename, String phonenumber)
{
ContentValues cv = new ContentValues();
cv.put(COl_MYTABLE_PHONENAME,phonename);
cv.put(COL_MYTABLE_PHONENUMBER,phonenumber);
return mDB.insert(TBL_MYTABLE,null,cv);
}
//---------------------------------------------------------------------------
// Iterating through the database
//---------------------------------------------------------------------------
public ArrayList<String> getAllRowsAsList()
{
Cursor csr = mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
ArrayList<String> rv = new ArrayList<>();
while (csr.moveToNext())
{
rv.add(csr.getString(csr.getColumnIndex(COl_MYTABLE_PHONENAME)));
}
return rv;
}
SelectModemFragment
private void manageListView(Context context)
{
thelist = dbHelper.getAllRowsAsList(); // Extract the list, just the phone names
// Only setup the adapter and the ListView if the adapter hasn't been setup
if(arrayAdapter == null)
{
// Instantiate the adapter
arrayAdapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,thelist); //<<<<<<<<<< list included
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
namedisplay = arrayAdapter.getItem(position);
Toast.makeText(view.getContext(), namedisplay + " Selected for Communication", Toast.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), phoneNo, Toast.LENGTH_SHORT).show();
}
});
}
Issue
using ArrayAdapter only allows a a single item to be passed, thus unless you resort to complicated/messy/inefficient methods ArrayAdapter is only really suitable for a single value.
Fix
You could use an ArrayList where your_object has members for all the required values. i.e phonenumber and phonename. Noting that unless you use a Custom Adapter that you should override the the toString method to extract the data that you want to be displayed, as that is what a standard ArrayAdapter uses.
Alternative (use a CursorAdapter)
An alternative would be to use a Cursor Adapter (e.g. SimpleCursorAdapter), you can then return the Cursor and use it directly. However, a CursorAdapter REQUIRES a column specifically name _id (BaseColumns._ID can be used).
One of the clear advantages of a Cursor adapter is the the 4th paremmter passed to the onItemClick/onItemLongClick is the id of the row (if used correctly) allowing a single value to then get/update/delete/pass the respective selected row.
As such I'd recommend a Cursor Adapter for a ListView and hence the more comprehensive answer.
You may think I don;t have such a column. However, you can use the normally hidden rowid column and dynamically create a column named _id.
You could have a method, in the database helper (DataDBAdapter) such as :-
public Cursor getAllRowsAsCursor()
{
String[] columns = new String[]{"rowid AS " + BaseColumns._ID,"*"}
return = mDB.query(TBL_MYTABLE,null,null,null,null,null,null)
}
The ManageList method could then be :-
private void manageListView(Context context) {
myCursor = dbhelper.getAllRowsAsCursor();
// Only setup the adapter and the ListView if the adapter hasn't been setup
if(arrayAdapter == null)
{
// Instantiate the adapter
arrayAdapter = new SimpleCursorAdapter(context,android.R.layout.simple_list_item_1,myCursor,new String[]{DataAdapter.COl_MYTABLE_PHONENAME},newint[]{android.R.id.text1},0);
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String namedisplay = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
String phonenumber = myCursor,getString(myCursor.getColumnIndex(DataAdapter.COL_MYTABLE_PHONENUMBER);
Toast.makeText(view.getContext(), namedisplay + " Selected for Communication", Toast.LENGTH_SHORT).show();
Toast.makeText(view.getContext(), phonenumber, Toast.LENGTH_SHORT).show();
}
});
} else {
arrayAdapter.swapCursor(myCursor);
}
Notes
MyCursor would be declared as a class variable e.g. Cursor MyCursor;
Instaed of
ArrayAdapter<String> arrayAdapter; you would have
SimpleCursorAdapter arrayAdapter;
The above is in-principle code and has not been tested, so there may be errors and/or omissions.
Working Example
The following is the code based upon the code from the previous question asked (which this appears to follow on from). It has two ListViews the old and a new one that uses a SimpleCursorAdapter. Clicking an item display phone number and also id. Lon Clicking an Item deletes that item (refreshing both ListViews).
DataDBAdapter.java has two new methods (so add these) :-
//<<<<<<<<<< ADDED
public Cursor getAllRowsAsCursor() {
return mDB.query(TBL_MYTABLE,null,null,null,null,null,null);
}
public int delete(long id) {
String whereclause = COL_MYTABLE_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
return mDB.delete(TBL_MYTABLE,whereclause,whereargs);
}
SelectModemFragment.java is now :-
public class SelectModemFragment extends Fragment {
private SelectModemViewModel mViewModel;
ListView display_contacts1;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> thelist;
DataDBAdapter dbhelper;
//<<<<<<<<<< ADDED
ListView display_contacts2;
SimpleCursorAdapter sca;
Cursor MyCursor;
public static SelectModemFragment newInstance() {
return new SelectModemFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.select_modem_fragment, container, false);
display_contacts1 = view.findViewById(R.id.lv001); //<<<<<<<<<< top listview ArrayAdapter<String>
display_contacts2 = view.findViewById(R.id.lv002);
dbhelper = new DataDBAdapter(view.getContext());
AddSomeData();
manageListView(view.getContext());
manageListView2();
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(SelectModemViewModel.class);
// TODO: Use the ViewModel
}
//Sets up the ListView if not already setup
private void manageListView(Context context) {
thelist = dbhelper.getAllRowsAsList(); //<<<<<<<<<< extract the list (just the phone names) from the database
// Only setup the adapter and the ListView if the adapter hasn't been setup
if (arrayAdapter == null) {
// Instantiate the adapter
arrayAdapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,thelist); //<<<<<<<<<< list included
display_contacts1.setAdapter(arrayAdapter); //<<<<<<<<<< Tie the adpater to the ListView
// Set the ListViews OnItemClick Listener
display_contacts1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = arrayAdapter.getItem(position); //<<<<<<<<<< this gets the phone name
Toast.makeText(view.getContext(),"You clicked the phone named " + name,Toast.LENGTH_SHORT).show();
}
});
} else {
//<<<<<<<<<< MODIFIED to cope with changes (needs to rebuild the array within the adpater)
arrayAdapter.clear();
for (String s: thelist) {
arrayAdapter.add(s);
}
arrayAdapter.notifyDataSetChanged();
}
}
//<<<<<<<<<< ADDED FOR CursorAdapter
private void manageListView2() {
MyCursor = dbhelper.getAllRowsAsCursor();
if (sca == null) {
sca = new SimpleCursorAdapter(
getContext(),
android.R.layout.simple_list_item_1,
MyCursor,
new String[]{DataDBAdapter.COl_MYTABLE_PHONENAME},
new int[]{android.R.id.text1},
0
);
display_contacts2.setAdapter(sca);
display_contacts2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(view.getContext(),
"You Clicked the phone name " +
MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COl_MYTABLE_PHONENAME)) +
". The phonenumber is " +
MyCursor.getString(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_PHONENUMBER)) +
". The ID (as passed) is " + String.valueOf(id) +
". The ID (from Cursor) is " + String.valueOf(MyCursor.getLong(MyCursor.getColumnIndex(DataDBAdapter.COL_MYTABLE_ID)))
,
Toast.LENGTH_SHORT).show();
}
});
//<<<<<<<<<< EXTRA delete row on long click
display_contacts2.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
dbhelper.delete(id);
manageListView2();
manageListView(getContext());
return true;
}
});
} else {
sca.swapCursor(MyCursor);
}
}
// Add some testing data (only if none already exists)
private void AddSomeData() {
if (DatabaseUtils.queryNumEntries(dbhelper.getWritableDatabase(),DataDBAdapter.TBL_MYTABLE) < 1) {
dbhelper.insert("Phone 1", "0000000000");
dbhelper.insert("Phone 2", "1111111111");
}
}
#Override
public void onResume() {
super.onResume();
manageListView2();
manageListView(getContext());
}
#Override
public void onDetach() {
super.onDetach();
MyCursor.close();
}
}

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

insert an item and sub item from list view

i have a problem with my list view, i display an item and subitem , i want to insert the two in database but it doesn't work !! the error is that i can't cast it to a text view
please someone help me.
This is the error that i get :
java.lang.ClassCastException: android.widget.TwoLineListItem cannot be cast to android.widget.TextView
Here the code of List View :
String[] databaseColumnNames = new String[] { DBAdapter.col_N_Ordre,DBAdapter.col_Nom_prénom};
int[] toViewIDs = new int[] { android.R.id.text1,android.R.id.text2 };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,android.R.layout.simple_expandable_list_item_2 , cursor, databaseColumnNames, toViewIDs);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(myCursordapter);
Here the code of insertion :
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(final AdapterView<?> arg0, View arg1,
final int position, long arg3) {
Toast.makeText(getApplicationContext(), " " + position, Toast.LENGTH_LONG).show();
final String s = ((TextView)arg1).getText().toString();
db.insertest(s);
The query is :
public long insertest(String region) {
ContentValues initialValues = new ContentValues();
initialValues.put(col_Region,region);
//initialValues.put(col_Provence_prefecture );
return db.insert(MENAGE,null, initialValues);
}
Put following code in your listview item click listener
TextView v1 = (TextView)arg1.findViewById(android.R.id.text1);
String first = v1.getText().toString();
TextView v2 = (TextView)arg1.findViewById(android.R.id.text2);
String second = v2.getText().toString();
ContentValues cv = new ContentValues();
cv.put(DBAdapter.col_Region, first);
cv.put(DBAdapter._id, second);
myCursordapter.notifyDataSetChanged();
list.setAdapter(adapter);
DBAdapter sql_Adapter = new DBAdapter(context);
sql_Adapter.open();
db.insertest(cv);
sql_Adapter.close();

Display primary key in the SQlite database when selecting item in Spinner

I am trying to display the primary key of the item I selected in Spinner.I want to display the primary key in TextView.How will I do this?I already know how to display a field in a table in database.
In my DatabseHandler.java
This is how I insert data in my table criteria
public long insertLabelCriteria(String label, String label2, String label3){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CRI_NAME, label);
values.put(KEY_CRI_PER, label2);
values.put(KEY_CRI_EVPK, label3);
// Inserting Row
long id = db.insert(TABLE_CRITERIA, null, values);
db.close(); // Closing database connection
return id;
}
This is my method in getting labels and returning list of labels
public List<Criteria> getAllLabels( String evpk ){
List<Criteria> labels = new ArrayList<Criteria>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CRITERIA + " WHERE "
+ KEY_CRI_EVPK + " = " + evpk ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(new Criteria(cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
In my MainActivity
I have a method loadSpinnerData and I use this evrytime I add a criteria, it will load the Spinner to view the item I added in database
private void loadSpinnerData() {
// TODO Auto-generated method stub
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<Criteria> lables = db.getAllLabels(evpk.getText().toString());
// Creating adapter for spinner
ArrayAdapter<Criteria> dataAdapter = new ArrayAdapter<Criteria> (this,
android.R.layout.simple_spinner_dropdown_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
criteria_spin.setAdapter(dataAdapter);
criteria_spin.setOnItemSelectedListener(this);
}
Now, on selecting item, how can I display the primary key of the selected item in spinner?
This codes below are just to show and select the item click.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
I also try to add this code ,but the id display is arraylist number, not the primary key
long rowId = id;
String criteriapk = String.valueOf(label);
cripk.setText(criteriapk);
I find it hard, in finding solution with this.What will I do?Help me plss
I also try this method, but the value is cursor.in the TextView, it does not display number.
public Cursor find_id_of_criteria(String label){
SQLiteDatabase db=this.getWritableDatabase();
String selectQuery = "SELECT criteria_id FROM Criteria WHERE criteria_name = "+"'" + label +"'";
Cursor id = db.rawQuery(selectQuery, null);
db.close();
return id;
}
and in loadSpinnerdata I put this
//display id of criteria
Cursor id2 = db.find_id_of_criteria(label);
String cri =(String.valueOf(id2).toString());
cripk.setText(cri);
You have to implement an own adapter extending BaseAdapter or CursorAdapter class and use it instead of ArrayAdapter.
Here is an example using CursorAdapter. I haven't tested it as it is meant to be a start for your own implementation. Of course you can use other layouts as well, with some minor changes to this code.
public class CriteriaCursorAdapter extends CursorAdapter {
private class Holder {
TextView text;
}
private LayoutInflater mInflater;
public CriteriaCursorAdapter(Context context, Cursor c) {
super(context, c);
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(
android.R.layout.simple_spinner_dropdown_item, parent, false);
}
Holder holder = (Holder)convertView.getTag();
if (holder == null) {
holder = new Holder();
holder.text = (TextView)convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
}
Cursor c = (Cursor)getItem(position);
holder.text.setText(c.getString(1));
return convertView;
}
}
Important: If you use CursorAdapter your cursor has to have a column named '_id'. You can achieve this by modifying your SELECT-statement, if your TABLE doesn't contain this column!
SELECT columnPK _id, col1, .... FROM ...
To get the primary-key (column '_id' of cursor) you can use long getItemId(int position); of your CriteriaCursorAdapter.
You will find many examples for extending BaseAdapter or CursorAdapter. One Example
Simple.. You are almost near to answer. Change your getAllLabels as following way.
public List<Criteria> getAllLabels( String evpk ){
List<Criteria> labels = new ArrayList<Criteria>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CRITERIA + " WHERE "
+ KEY_CRI_EVPK + " = " + evpk ;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Criteria ct = new Criteria();
ct.setLabel(cursor.getString(1));
ct.setKey(Integer.parseInt(c.getString(0)));
labels.add(ct);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
Here I changed the do while loop only. In this way create getters and setters for label and key. To get the primary key use the selected Criteria object like ct.getKey; I hope this will help you.
UPDATE
List<String> field_key; //accessible in whole class.
private void loadSpinnerData() {
// TODO Auto-generated method stub
// database handler
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
// Spinner Drop down elements
List<Criteria> lables = db.getAllLabels(evpk.getText().toString());
List<String> field_lables = new ArrayList<String>();
field_key = new ArrayList<String>();
// Creating adapter for spinner
for (Criteria ct : lables) {
field_lables.add(ct.getLabel);
field_key.add(ct.getkey);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_dropdown_item, field_lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
criteria_spin.setAdapter(dataAdapter);
criteria_spin.setOnItemSelectedListener(this);
}
&
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
String key = field_key.get(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label+" Your key: " + key,
Toast.LENGTH_LONG).show();
}
Try this way and let me know what happens

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

Categories

Resources