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();
Related
private void populateListView(){
Cursor c = loginDataBaseAdapter.allData();
startManagingCursor(c);
String[] fromfields = new String[]{"_id", "NAME", "YEAR", "GENRE"};
int[] toViewIDs = new int[]{R.id.TVmovieID, R.id.TVmovieTtile, R.id.TVmovieYear, R.id.TVmoviegenre};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, R.layout.mlayout, c, fromfields, toViewIDs);
lv.setAdapter(myCursorAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = parent.getItemAtPosition(position).toString();
Toast.makeText(Proba.this, "String"+s, Toast.LENGTH_SHORT).show();
}
});
}
This is a method I call onCreate of this Activity, I use toast just to make sure that im getting the right value, but I get the android.database.sqlite... . I want to get the value of just one field, but first I want to get the value of the whole list.
Correct way of implementation to get any fields
final String[] fromfields = new String[]{"_id", "NAME", "YEAR", "GENRE"};
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = myCursorAdapter.getItem(position);
int columnIndex = cursor.getColumnIndexOrThrow(fromfields[1])
String name = cursor.getString(columnIndex);
Toast.makeText(Proba.this, "Name is " + name, Toast.LENGTH_SHORT).show();
}
});
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);
}
});
I've got a functioning search interface on my app. Now I'm trying to make each search result list item clickable and display in a new activity. I've got them clickable, but I can't figure out how to pass the ListAdapter values (records) into the onItemClick method.
Here's my code so far:
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_MAKE,
DBAdapter.KEY_YEAR, DBAdapter.KEY_MAKE,
DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rDateTV, R.id.rYearTV,
R.id.rMakeTV, R.id.rModelTV };
final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
DBHelper.close();
// --- Click on list item ---
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//--- here's the problem: how do I pass the ListAdapter values into onItemClick. the below doesn't like .getText()
String sYear = (view.findViewById(R.id.rYearTV)).getText().toString();
String sMake = (view.findViewById(R.id.rMakeTV)).getText().toString();
String sModel = (view.findViewById(R.id.rModelTV)).getText().toString();
// -- then pass these strings to an intent to launch a new activity
}
});
// --- END click on list item ----
}
Any ideas? I'm a rookie here, so if you could show me the code, that would be AWSOME!
In OnItemClickListener.onItemClick call parent.getItemAtPosition(position). That method returns cursor which is set to the given position. Then get your data from that cursor. Don't close cursor inside OnItemClickListener.onItemClick.
for example:
ListView clickList = getListView();
clickList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor)parent.getItemAtPosition(position)
String sMake = c.getString(c.getColumnIndexOrThrow(DBAdapter.KEY_MAKE));//get data from cursor
...
}
});
I created a SQLiteDatabase where I can see the items with the 'View' Button and clicking on it, I get the whole database into a ListView. In this ListView I would like the items to be clickable and if I click on them, I want to add a new entry to it with the same name, but another id. My code so far:
ListView lv;
ArrayList<String> todoItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, todoItems));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
hornot info = new hornot(this);
info.open();
Cursor c = info.getAllTitles();
if (c.moveToFirst())
{
do{
todoItems.add(c.getString(0) + " " + c.getString(1) + " " + c.getString(2));
}while (c.moveToNext());
}
if (todoItems.size() > 0)
{
lv.setAdapter(new ArrayAdapter<String>(sqview.this,android.R.layout.simple_list_item_1, todoItems));
}
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//-/////////////////////////
}
});
info.close();
}
As you see, I put the database items into an array, then I put them into a ListView. With an upgrade button I can add items, so I think I need to do something same here.
In the dbhelper the createEntry function:
public long createEntry(String name, String hotness) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
In the main.java I convert the EditTexts to Strings then put the values into the database:
String name = sqlName.getText().toString();
String hotness = sqlHotness.getText().toString();
hornot entry = new hornot(dbhelp.this);
entry.open();
entry.createEntry(name, hotness);
entry.close();
So what should I write for the onItemClick function?
In the onItemClick() method you have the position parameter that indicates the position(in the adapter) of the list row that was clicked. You could then use getItemAtPosition on the ListView to get the data from the row:
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String rowData = (String) lv.getItemAtPosition(position); //you'll need to make the lv as final
String[] data = rowData.split(" "); //split the result using the spaces (so you could obtain the name, hotness and the other string you use)
entry.createEntry(data[0], data[1]);
}
I don't know your database structure so I can't recomend you something about unique id.
I created spinner in my app and I'm filling it with data from a database. It works ok until I want to select item in first position, when I do that spinner closes and nothing is hapennig. But if I choose item on any other positions it works just fine and i don't have any idea why ?
my code:
public String returnString(AdapterView<?> parent,int position,long ID){
return parent.getSelectedItem().toString();
}
void showDrugStores()
{
final DBAdapter db = new DBAdapter(this);
db.open();
final Cursor drugCursor;
Spinner drugStoreSpinner = (Spinner) findViewById(R.id.drugStoreSpinner);
drugCursor = db.getDrugStores();
drugCursor.moveToFirst();
startManagingCursor(drugCursor);
String[] from = new String[]{db.KEY_NAZWAAPTEKI};
int[] to = new int[]{R.id.tvDBViewRow};
SimpleCursorAdapter drugStoreAdapter = new SimpleCursorAdapter(this,
R.layout.closed_spinner, drugCursor, from, to);
drugStoreAdapter.setDropDownViewResource(R.layout.db_view_row);
drugStoreSpinner.setAdapter(drugStoreAdapter);
drugStoreSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String selection = returnString(parent, pos, id);
db.open();
db.getDruSto(selection);
TextView show_selected =(TextView) findViewById(R.id.show);
show_selected.setText(drugCursor.getString(1));
db.close();
});
}
It is probably because the first item is ALREADY selected - if you want to add an option to represent that nothing is selected, you should add that to the head of your list.