Set onclick to item that isn't visible - android

So I have been looking around for about 4 hours now and maybe I just don't know how to word my search, but I am not finding out what I need.
I am using a custom adapter to setup my listview from items I have stored into an sqlite database. My cursor sends id, name, product_id, data, datetime to my adapter. But my adapter is set to only display the name, data & datetime.
I need to be able to click on the name, but have it go to my next activity and display the information from the product_id that was sent to the adapter. Example I click on Apples, but it would actually be product_id 505 in my database. Unless I set the product_id to a textview, when I click on my item, it does not bring up the correct listing and searches for Apples.
If this is not clear, please let me know and I will to explain it better.
** EDIT **
So my database is like this
_ID | PRODUCT_NAME | PRODUCT_ID | PRODUCT_DATA | DATE
1 Apples 505 Fresh Apples 123456
2 Oranges 506 Fresh Orange 123456
3 Kiwi 507 Fresh kiwi 123456
4 Nuts 508 Fresh Nuts 123456
My ListView shows this:
Apples- FRESH APPLES - DATE
Oranges - FRESH ORANGE - DATE
Kiwi- FRESH KIWI - DATE
Nuts - FRESH NUTS - DATE
When I click on Apples, I want it to return PRODUCT_ID to me, not _ID, so I can pass that product_id onto my next intent.
My Display listing
public void displayListView()
{
DatabaseOperations db = new DatabaseOperations(this);
Cursor cursor = db.getProducts();
dataAdapter = new MainActivityAdapter(
this,
cursor,
0);
ListView listView = (ListView) findViewById(R.id.product_list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
// listening to single list item on click
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,
int position, long ID)
{
TextView listText = (TextView) view.findViewById(R.id.name);
String product_name = listText.getText().toString();
Intent i = new Intent(MainActivity.this, product_detail.class);
i.putExtra("productName", product_name);
MainActivity.this.startActivity(i);
}
});
db.close();
}
My Adapter
public class MainActivityAdapter extends CursorAdapter
{
private LayoutInflater cursorInflater;
private Context c;
// Default constructor
public MainActivityAdapter(Context context, Cursor cursor, int flags)
{
super(context, cursor, flags);
cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
c = context;
// Log.i("Custom-Adapter", "Starting up");
}
public void bindView(View view, Context context, Cursor list)
{
TextView PN = (TextView) view.findViewById(R.id.product_name);
TextView PI = (TextView) view.findViewById(R.id.product_data);
TextView date = (TextView) view.findViewById(R.id.date);
// SET OUR DATA FROM OUR CURSOR
String pn = list.getString( list.getColumnIndex("pn"));
String pi = list.getString( list.getColumnIndex("pi"));;
// NEED TO RECONVERT DATE THEN SHOW IT
Long millidate = list.getLong(list.getColumnIndex("dateTime"));
Date myDateNew = new Date(millidate);
String Sdate = getDate(millidate);
PN.setText(pn);
PI.setText(pi);
date.setText(Sdate);
}
public static String getDate(long milliSeconds)
{
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliSeconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
return date;
}
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
//Log.i("Custom-Adapter", "newView Started");
// R.layout.list_row is your xml layout for each row
return cursorInflater.inflate(R.layout.activity_list, parent, false);
}

I want to get the product_id when I click on the name Apples.
We can achieve it in multiple ways but most common ways are :
Option 1:
Use setTag method for saving id of product with name in TextView :
PN.setText(pn);
PN.setTag((list.getInt(list.getColumnIndex("product_id"))).toString());
Now use getTag method to get clicked product product_id in onItemClick :
String product_name = listText.getText().toString();
int product_id = Integer.parseInt(listText.getTag().toString());
Option 2:
Instead of getting product name from TextView, get clicked row cursor using Adapter in onItemClick :
Cursor cursor = (Cursor) dataAdapter.getItem(position);
String product_name = cursor.getString(cursor.getColumnIndex("pn"));
int product_id = cursor.getInt(cursor.getColumnIndex("product_id"));
....

A good option is to create an array and store product_ids for all the names.
Goto Res->Strings create an array of strings .
then fetch from the array the relevant product_id for the name.

Related

next button for listview

My first activity contains a ListView that's getting a list of items from a database.
And in the OnClickListener, there is a new activity that's open getting all information related to the question from the database, I'm putting them in Intent extras and getting them in the next activity:
public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
String quest = (String) parent.getAdapter().getItem(i);
int pos = lst.getCheckedItemPosition();
Intent inte = new Intent(view.getContext(),Reponse.class);
cursor = db.rawQuery("SELECT * FROM "+ ModelHelper.TABLE_QUESTION + " WHERE " + ModelHelper.KEY_QUESTION + " = ? ",new String[] {quest});
if (cursor != null)
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String repA = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_WAITEDANSWER));
String cible = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_CIBLE));
String plan = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PLANACT));
int ID = cursor.getColumnIndex(ModelHelper.KEY_ID_QUESTION);
inte.putExtra("question", quest);
inte.putExtra("repo", repA);
inte.putExtra("cible", cible);
inte.putExtra("plan", plan);
// inte.putExtra("id", ID);
// inte.putExtra("pos", pos);
startActivity(inte);
finish();
In the info activity, it's simple and I could get the information from the database, here's the code
Intent intent = getIntent();
String question = intent.getStringExtra("question");
String repo = intent.getStringExtra("repo");
String cible = intent.getStringExtra("cible");
String plan = intent.getStringExtra("plan");
final int[] ID = {0};
ID[0] = intent.getIntExtra("ID", ID[0]);
int pos = 0;
pos = intent.getIntExtra("pos",pos);
txtq.setText(question);
txtr.setText(repo);
txtc.setText(cible);
txtp.setText(plan);
I want to add a button NEXT that makes appear the next item in the list by refreshing the same page without going back to the list and click again.
I tried to get the position too with the intent and tried to set a new OnClickListener in the button to set the position = position +1, but it doesn't work.
Any ideas?
First solution
for that, you have to pass the entire list to next activity so you can directly do next item in the list by refreshing the same page without going back.
Second solution.
You have to separately apply query for next info page click on the next/previous button.
You just need to go through the sql Queries
select * from table where key=primaryKey limit Page_Limit offset Start_From
You need to change limit and offset on select of list limit.

To split Strings from a MultiAutoCompleteTextView and set it to different textview

I have a array of strings which is a resultant of options selected from a MultiAutoCompleteTextView using the comma tokenizer. The string appears as below:
"India, China, Japan, America, Australia"
I need to seperate this values based on the coma positiona and set those values to different textview's. Also I need to restrict the users to select only 5 values and those values should not be repeated.
You can use String.split() like this:
String[] array = yourString.split(",");
And iterate through that array.
EDIT:
To check if the user already selected the item, you can add an OnItemClickListener to your multiAutoCompleteTextView and have a HashSet or a Set where your items clicked are stored and check if this item already exists in the set
Example:
Initialize your HashSet first: HashSet<String> hashset = new HashSet<String>();
And later:
youMultiAutoCompleteTv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemClicked = parent.getAdapter().getItem(position).toString();
if(hashset.contains(itemClicked)){
Toast.makeText(getApplicationContext(), "Item exists", Toast.LENGTH_SHORT).show();
}
else {
hashset.add(itemClicked);
}
}
});
Use something like this:
String myListAsString = "India, China, Japan, America, Australia";
String[] countries = myListAsString.split(",");
TextView t1 = (TextView)findViewById(R.id.t1);
TextView t2 = (TextView)findViewById(R.id.t2);
TextView t3 = (TextView)findViewById(R.id.t3);
TextView t4 = (TextView)findViewById(R.id.t4);
TextView t5 = (TextView)findViewById(R.id.t5);
t1.setText(countries[0]);
t2.setText(countries[1]);
t3.setText(countries[2]);
t4.setText(countries[3]);
t5.setText(countries[4]);
You can use this :
String input = editText.getText().toString().trim(); //Getting String from view.
String[] singleInputs = input.split("\\s*,\\s*"); //Splitting in proper way.

Unable to get selected item text from a spinner

In my application I have a spinner that displays a number of spending periods (weekly, bi-weekly, monthly, etc) and I filled it using a SimpleCursorAdapter because those periods are kept in the database. Here is how I implemented it:
Cursor spendingPeriodCursor = dataSource.getSpendingPeriods();
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, spendingPeriodCursor, fromColumns, toColumns);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpendingSpinner.setAdapter(mAdapter);
The spinner populates, and at the end of the activity I try to get the selected item like this:
// Get spending period description:
String spendingDesc = mSpendingSpinner.getSelectedItem().toString();
But it doesn't return the actual string value. It looks like a get a string representation of part of the cursor:
android.database.sqlite.SQLiteCursor#410dfae8
What do I have to do to get the actual text of the selected item?
Cursor cursor = (Cursor) mSpendingSpinner.getSelectedItem();
String text = cursor.getString(cursor.getColumnIndex("my_column_name"));
1) Well, with will be enough with:
String spendingDesc = mSpendingSpinner.getSelectedItem().toString();
2) but you can try too:
mSpendingSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View arg1,
int pos, long arg3) {
String spendingDesc= parent.getSelectedItem().toString();
}
}
3) or
Cursor cursor = (Cursor) mSpendingSpinner.getSelectedItem();
String text = cursor.getString(cursor.getColumnIndex("COLUN_NAME"));

Get spacial content of selected item in listview in android

I am new with android programing and I have a problem with list view
In my app I have to read data from database (name,ID,year) and then add them to listview after that user must select one of
the items and in a new activity again I read data from db and list some of the other Items based on user's selection
Ol at this time In my first activity I read data and add them to listview..To select I must define a listener..right?
I define it like this code
enter code here #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read_book);
String SDcardPath = Environment.getExternalStorageDirectory().getPath();
String DbPath = SDcardPath + "/Tosca/" + "persian_poem.db";
ListView list = (ListView) findViewById(R.id.list_poet_name);
try {
db = SQLiteDatabase.openDatabase(DbPath,null,SQLiteDatabase.CREATE_IF_NECESSARY);
getData();
db.close();
}
catch (SQLiteException e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
ListView list = (ListView) findViewById(R.id.list_poet_name);
Log.i(TAG, "Listview get Item Pos");
Peot_ID.putString ("Peot_ID", (String) list.getItemAtPosition(position));
Intent Book_list_intent = new Intent (Read.this,Book_list.class);
Book_list_intent.putExtras(Peot_ID);
startActivity(Book_list_intent);
}
});
}
private void getData() {
try {
//txtMsg.append("\n");
// obtain a list of from DB
String TABLE_NAME = "classicpoems__poet_contents";
String COLUMN_ID = "poet_id";
String _ID = "_id";
String COLUMN_NAME = "poet_name";
String COLUMN_CENTURY = "century_start";
String [] columns ={_ID,COLUMN_ID,COLUMN_NAME,COLUMN_CENTURY};
Cursor c = db.query(TABLE_NAME,columns,null, null, null, null, COLUMN_ID);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, c,
new String[] {COLUMN_NAME,COLUMN_CENTURY}, new int[] {android.R.id.text1,android.R.id.text2}, 0);
ListView list = (ListView) findViewById(R.id.list_poet_name);
list.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), 1).show();
}
}
But here I have a problem..I want to send data of peot_id (Its deffrent from _id column in db) to next activity..Bt I mentioned that
with this code I can get whole row of selected item and I just want part of it(peot_id ) can you help me how to get just Peot_ID from selected
list item?
and I have another question..
As you see in my code I must refer to one spasial listview several times..each time I defined it by this code
enter code hereListView list = (ListView) findViewById(R.id.list_poet_name);
How can I define this listviwe one time and use it in several places in my code?sth like a public variable or sth like that
Thanks for your help.
As you see in my code I must refer to one spasial listview several
times..each time I defined it by this code
No. Just create one global ListView variable list and simply you can access to it from everywhere in your Activity. There is no need to declaring and initialising ListView again in OnItemClick() method.
I want to send data of peot_id (Its deffrent from _id column in db) to
next activity..Bt I mentioned that with this code I can get whole row
of selected item and I just want part of it(peot_id ) can you help me
how to get just Peot_ID from selected list item?
You are using Android's defined basic layout
android.R.layout.simple_list_item_2
I suggest you to create own XML file for row and then simply get whole View from ListView and from View you can get only ID.
Example:
listrow.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:background="#drawable/addresses_list_selector"
>
<TextView
android:id="#+id/id_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/name_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/id_column"
/>
<TextView
android:id="#+id/century_column"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/name_column"
/>
</RelativeLayout>
Then an usage with CursorAdapter:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listrow, c,
new String[] {COLUMN_ID, COLUMN_NAME, COLUMN_CENTURY},
new int[] {R.id.id_column, R.id.name_column, R.id.century_column}, 0);
And then for getting ID from row:
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
TextView id = (TextView) v.findViewById(R.id.id_column);
if (id != null) {
String idString = id.getText().toString();
}
}
Note:
If you still want to use android's predefined layout, you need to pass into String[] from ID_COLUMN and then access to ID from row via row.findViewById(<id>);
String[] from = {ID_COLUMN, NAME_COLUMN};
int[] to = {android.R.id.text1, android.R.id.text2};
TextView id = v.findViewById(android.R.id.android.R.id.text1);
String idString = id.getText().toString();
You do query like this to get a Particular column record alone :
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_DESIGNATION}, KEY_ROWID + "=" + yourPrimaryKey, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
I personally prefer to use onListItemclick() method like that
//do not forget to override - very important
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//TODO what you what you have here the vars position - position of the selected item in list
// and also the id so you can easy trace what selection done the user
// you can play with this
}

Android: Get Position from SimpleCursorAdapter

I would like to set the position of a spinner item, but the spinner is being populated with a simplecursoradapter with data from a database. I would like to get the current string from the database, then set the spinner to that value. I know that by using an arrayadapter I can get the position from the adapter this way:
String myString = queryData.getString(queryData.getColumnIndex("myString"));
//cast to an ArrayAdapter
mySpinnerAdapter adapter = (mySpinnerAdapter) mySpinner.getAdapter();
int spinnerPosition = ?
//set the default according to value
mySpinner.setSelection(spinnerPosition);
But is there a way to get the position of an item from a SimpleCursorAdapter? In the past I have always build an array of my spinner data along side the cursoradapter, but this seems like a dirty way of doing it. If its the only way though...
You can get the position of the item by doing this:
ArrayList<View> views = new ArrayList<View>();
listView1.reclaimViews(views);
for (int i = 0; i < views.size(); i++)
{
View v = views.get(i);
// Get the view's text value and compare it with your string here
// If the two strings match, store the position, which is 'i' in this case
// If your view is a textview, you would do this:
TextView tv = (TextView)v.findViewById(R.id.textView1);
if (tv.getText().toString().toLowerCase().compareTo(textToCompare.toLowerCase()) == 0)
{
// Store position here
}
}
Even i face the same problem. After breaking my head for some hours, i found this solution.
I hope it will help you.
/// value is column name in DB. take value from
final String[] from = new String[] {"value"};
/// field in spinner. Put value into (keep "R.id.text1" as it is..)
final int[] to = new int[]{R.id.text1};
// Get Database Access Object to interact with DB
DataAccessObject dataAccessObject = new DataAccessObject(context);
final Cursor valueCursor = dataAccessObject.querySpinnerValues();
final SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(
context, R.layout.spinner_row_layout, valueCursor,
from , to );
// when ever a field is selected in the spinner's "spinner.setOnItemSelectedListener" method will be called
// and the primary key
// associted with that particular value will be saved into "someFieldPkMap" map or you can choose other collection..or some
// instance variable..
//
// Note : Here i am fetching two columns fron DB.
// 1. "_id" Primary key should always be "_id" otherwise it will not work
// 2. "value" which will be displayed in the spinner. this column can be anything. but you need to map it. The way i did eg..
// final String[] from = new String[] {"value"}; /// value is column name in DB. take value from
// final int[] to = new int[]{R.id.text1}; /// field in spinner. Put value into (keep "R.id.text1" as it is..)
//
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
valueCursor.moveToPosition(position);
// Get the primary Key associated with the value...
// Use "someFieldPkMap" map to get the primary key
someFieldPkMap.put(fieldName, Integer.parseInt(valueCursor.getString(0)));
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
spinner.setAdapter(simpleCursorAdapter);

Categories

Resources