I'm just a noob in android. I've got this code from someone's blog.
He made a simple database query and populate an arraylist in listview.
How do I get a value from each selected item in listview to text view in new activity?
Here's the arraylist code:
public ArrayList<ArrayList<Object>> rowTable() {
ArrayList<ArrayList<Object>> fillArray = new ArrayList<ArrayList<Object>>();
Cursor cur;
try {
cur = db.query(TABLE_TEST, new String[] { ROW_ID, ROW_NAME,
ROW_CLASS }, null, null, null, null, null);
cur.moveToFirst();
if (!cur.isAfterLast()) {
do {
ArrayList<Object> fillList = new ArrayList<Object>();
dataList.add(cur.getLong(0));
dataList.add(cur.getString(1));
dataList.add(cur.getString(2));
dataArray.add(fillList);
} while (cur.moveToNext());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR DATABASE", e.toString());
}
return fillArray;
}
and here's the listview code.
private void getArrayList() {
// TODO Auto-generated method stub
ArrayList<ArrayList<Object>> getData = dtbase.rowTable();//
name = new String[getData.size()];
for (int x = 0; x < getData.size(); x++) {
ArrayList<Object> getRow = getData.get(x);
name[x] = getRow.get(1).toString();
}
ArrayAdapter<String> sName = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, name);
lv.setAdapter(sName);
}
can you help me?
It's very easy to get the selected item
Here is the method you need to override.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
...
}
}
Then use the position argument to access the arraylist so you could display it in your textview.
Related
I am trying to show a listview of data from database in fragments. For that reason I've added a table in database. Now I'm trying to create data adapter. Here is my code:
list=(ListView)rootView.findViewById(R.id.listView1);
try{
DatabaseHandler db = new DatabaseHandler(getActivity());
List<Label> allLabel = db.getAllLabels();
for (Label label : allLabel) {
ArrayAdapter<Label> dataadapter= new ArrayAdapter<Label>(getActivity(),android.R.layout.simple_list_item_1,allLabel);
list.setAdapter(dataadapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v, int position,long id)
{
Toast.makeText(getActivity(), ((TextView)v).getText(), Toast.LENGTH_LONG).show();
}
});
}
}
catch (Exception e)
{
e.printStackTrace();
}
this is my output of containing field value not data value:
com.qcash.atmlocator.Label#52852d88
com.qcash.atmlocator.Label#52852dd8
com.qcash.atmlocator.Label#52852e08
com.qcash.atmlocator.Label#52852e38
this is the getAllLabels() function used in my code:
public List<Label> getAllLabels(){
List<Label> labels = new ArrayList<Label>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Label label = new Label();
label.setId(cursor.getInt(0));
label.setName(cursor.getString(1));
label.setLatitude(cursor.getDouble(2));
label.setLongitude(cursor.getDouble(3));
labels.add(label);
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
How can I get the database value? please help me out.
Adding cursor data to a string and adding that string to the calling function fragment solved that. Here is the code:
String name=cursor.getString(0)+"\n"+cursor.getString(1)+"\n"+cursor.getString(2)+"\n"+cursor.getString(3);
FindPeopleFragment.ArrayofName.add(name);
Finally showing that array to adapter completes that:
ArrayAdapter<String> dataadapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,ArrayofName);
Override the toString() method in Label class. I am assuming that you class has a variable 'name'.
class Label{
// other variables.
#Override
public String toString() {
return name;
}
}
Update:
Change the onItemclick listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v, int position,long id)
{
Label label = (Label)parent.getItemAtPosition(position);
Toast.makeText(getActivity(), "" + label.toString(), Toast.LENGTH_LONG).show();
}
});
hope you could help me with this problem. i want to get the rowId of a selected item in a listview from sqlite so that i can pass the value to another activity.
i already fed the listview with info from my sqlite table and use onClickedItem in the listview and use pos + 1 to get the id, but i dont want this solution because whenever i delete an item from the listview i wont be able to get the correct rowId from the database itself... this is my code :
in my DBhelper:
public List<String> getSYAList() {
List<String> List = new ArrayList<String>();
try {
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SYA ;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(0)) + " " +(c.getString(1)) + " "+ (c.getString(2)));
} while (c.moveToNext());
}
} catch (Exception e) {
Toast.makeText(ourContext, "Error encountered.",
Toast.LENGTH_LONG).show();
}
return List;
}
in my activity:
private void loadSYA() {
// TODO Auto-generated method stub
final DBhelper entry = new DBhelper(this);
entry.open();
final List<String> sya = entry.getSYAList();
if(sya.size()>0) // check if list contains items.
{
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(SYA.this,android.R.layout.simple_dropdown_item_1line, sya);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sqlSYA.setAdapter(arrayAdapter);
sqlSYA.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(SYA.this,SYAInfo.class);
Bundle b = new Bundle();
b.putInt("id", (int)position + 1);
i.putExtras(b);
startActivity(i);
}
}); }
else
{
Toast.makeText(SYA.this,"No items to display",1000).show();
}
entry.close();
}
i really hope you anyone could help me to find a solution for this one. thanks in advance guys !!!
im a newbie to android and i have this problem here hope you guys can help me with this :)
anyways, i want to get the id of a selected item in the spinner from sqlite database so that i can save it to another table later on.
here's my code:
in my DB.java :
public List<String> getSemesterList() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SEMESTER;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(1)));
} while (c.moveToNext());
}
return List;
}
public String getSemesterId() {
String[] columns = new String[] { KEY_SEMESTER_ID, KEY_SEMESTER };
Cursor c = ourDatabase.query(TABLE_SEMESTER, columns, null, null, null, null, null, null);
int id = c.getColumnIndex(KEY_SEMESTER_ID);
String semId = "";
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
semId = semId + c.getInt(id) + " "
+ "\n";
}
return semId ;
}
and in my createSYAttended.class
// TODO Auto-generated method stub
DB entry = new DB(this);
entry.open();
final List<String> all = entry.getSemesterList();
if(all.size()>0) // check if list contains items.
{
sqlSem = (Spinner) findViewById(R.id.sprSemester);
arrayAdapter = new ArrayAdapter<String>(CreateSyAttended.this,android.R.layout.simple_spinner_dropdown_item, all);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sqlSem.setAdapter(arrayAdapter);
entry.close();
sqlSem.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
} }
use a mapping for the index of your List<String> all = entry.getSemesterList(); to the spinner item
so when you get below callback
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
you can then use the position you get in the callback to map to the item in the semesterList all
I have a listview which connect to an sqlite database. at first it shows my sqlite fields. but my problem is,I can't delete row by setOnLongClickDelete().
error:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1510)
codes:
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList() {
// setListAdapter(new ArrayAdapter<String>(this,R.layout.cartformat,results));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " +title+ ",Quantity: "+qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
try{ String currentString = results.get(position);
String resultRegexString = "Title\\:([^,]+),Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(currentString);
if(resultRegexMatcher.find()){
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3)));
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
database.delete("CART", whereClause, null);
database.close();
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
results.remove(position);
}
return true;
} catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;
}
}
} );
displayResultList();
}
}
following Toast works:
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
If you are able to successfully remove the data from the SQLite database then you simply make your listAdapter global and then adding the code
listAdapter.notifyDataSetChanged();
after
results.remove(position);
in your onItemLongClick. After this you can remove calling displayResultList(); in setOnLongClickDelete().
I have two tables with names disease_table and sysmptoms_table. I retrieved the data from disease_table from the DB and displayed on the listview and when the listitem is clicked, I have to select and display disease category symptoms accordingly and I did that successfully but my code has redundancy, I had to write two methods in the datahelper class to retrieve the symptoms as per the disease in another listview. and I am retrieving the symptom data in list view with the query with the condition of WHERE "disease_id=1" with foreign key reference
the code for the methods is as follows,
//getting pain symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,symptompain));
public List<String> getAllSymptomPain() {
List<String> symptompain = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=1", null, null, null, null);
if(null != cr){
symptompain = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptompain.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptompain;
}
//getting colorchange symptom names in a arraylist and then display in listview
//this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,symptomcolorchange));
public List<String> getAllSymptomColorChange() {
List<String> symptomcolorchange = null;
cr = db.query(SYMPTOM_TABLE_NAME, new String[] {"symname"}, "diseaseid=2", null, null, null, null);
if(null != cr){
symptomcolorchange = new ArrayList<String>();
if (cr.moveToFirst()) {
do {
symptomcolorchange.add(cr.getString(0));
} while (cr.moveToNext());
}
if (cr != null && !cr.isClosed()) {
cr.close();
}
}
return symptomcolorchange;
}
How can I write these two in a single method and then call it in class which extends listactivity under onListItemclick method?
And my OnListItemClick() method is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String item=(String)getListAdapter().getItem(position);
if(item.equals("Pain in Teeth")){
// passing the method here
}
else if(item.equals("Pain in Gums")){
// passing the method here
}
else if(item.equals("Pain in Mucosa")){
// passing the method here
}
else if(item.equals("Pain in TMJoint")){
// passing the method here
}
else if(item.equals("Non-Specific Pain")){
// passing the method here
}
}
Try this:
public List<String> getSymptomsByDiseaseId(long diseaseId) {
List<String> symptomsList = new ArrayList<String>();
String selection = "diseaseid=?";
String[] selectionArgs = { String.valueOf(diseaseId) };
Cursor cursor = db.query(false, SYMPTOM_TABLE_NAME, null, selection, selectionArgs, null, null, null, null);
if (cursor.moveToFirst()) {
do {
symptomsList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
return symptomsList;
}