Getting item from ListView - android

I'm working on a android project and a got stuck. I'm trying to get an item from a ListView but all I get is info about the item's position in the database I created and not the item itself.
this is my code :
public class Map extends Activity {
Cursor cursor;
ListView listView;
String categoria = "livro";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
final CitySQL dbHelper = new CitySQL(Map.this, null, null, 1);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
final String[] camposDb = {"city", BaseColumns._ID};
cursor = db.query("cities", camposDb, null, null, null, null, "city ASC");
int[] camposView = new int[] {android.R.id.text1};
#SuppressWarnings("deprecation")
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(Map.this,
android.R.layout.two_line_list_item, cursor, camposDb, camposView);
listView= (ListView)findViewById(R.id.city_list);
listView.setAdapter(adapter);
final Geocoder geocoder=new Geocoder(this, Locale.ENGLISH);
listView.setOnItemClickListener(new OnItemClickListener(){
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onItemClick(AdapterView<?> parent, View view, int posicao,long id) {
final String morada = listView.getAdapter().getItem(posicao).toString();
Toast.makeText(Map.this, morada, Toast.LENGTH_LONG).show();
I made a Toast to see exactly what was happening when I clicked but my goal is to get the item (a city name) and look for a location.

Change
final String morada = listView.getAdapter().getItem(posicao).toString();
to
Cursor cursor = (Cursor) listView.getAdapter().getItem(posicao);
String morada = cursor.getString(cursor.getColumnIndex("column_name_for_city"));

Related

Android onListItemClick exception: "java.lang.String cannot be cast to android.database.Cursor"

As title says, it get this exception from the code I pasted below. I tried to make it work both with the uncommented code and also with the commented part insted of the IF block just before it.
The error I get is: java.lang.ClassCastException: java.lang.String cannot be cast to android.database.Cursor which I don't understand, since the item in the listview should exactly be a String! Any idea?
public class ListScoutActivity extends ListActivity {
private DBHelper database;
private ListView listav;
private Cursor cursor;
ArrayList<String> stringlist = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_scout);
database = new DBHelper(getApplicationContext());
SQLiteDatabase db = database.getWritableDatabase();
listav = this.getListView();
listav.setVisibility(View.VISIBLE);
int codpartita;
String team;
cursor = db.rawQuery("SELECT _codpartita as _id, team, FROM partita ORDER BY _codpartita DESC", null);
cursor.moveToFirst();
while ( !cursor.isAfterLast() ) {
team = cursor.getString(cursor.getColumnIndex("team"));
stringlist.add(team);
cursor.moveToNext();
}
cursor.moveToFirst();
if (cursor.getCount()>0) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(ListScoutActivity.this,
android.R.layout.simple_list_item_1, cursor, new String[]{"team"},
new int[]{android.R.id.text1}, 0);
listav.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(ListScoutActivity.this,
// android.R.layout.simple_list_item_1, android.R.id.text1, stringlist);
// listav.setAdapter(adapter);
db.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor)l.getItemAtPosition(position);
//.. other things..
}

How to expand Listview row using SimpleCursorAdapter

I am using Database to inflate my list view and i am using simple cursor adapter to do that. Now i want to expand row on list item click(Like if user Clicks on row, two text views of current row visible to him). I searched a lot but not find any answer. please help!!!! Thank you.
public class CallLogs extends Activity {
EditText from,to;
Button call;
TextView call_from,call_to,date_call,verify;
private SQLiteDatabase database;
String fields[] = { "from", "to", "date" };
private CursorAdapter dataSource;
long profile_counts;
SQLiteDatabase sqLiteDatabase;
DataBaseHandler dbHelper;
MyDataBaseHelper databaseHelper;
MyDBHelper databaseHelper_new;
Button get;
ListView listView;
RelativeLayout r2;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.call_logs);
databaseHelper_new= new MyDBHelper(this);
from = (EditText)findViewById(R.id.from);
to = (EditText)findViewById(R.id.to);
call_from = (TextView)findViewById(R.id.textView4);
call_to = (TextView)findViewById(R.id.textView6);
date_call = (TextView)findViewById(R.id.textView8);
verify = (TextView)findViewById(R.id.call_from);
call = (Button) findViewById(R.id.call);
get = (Button) findViewById(R.id.get);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String from_num = from.getText().toString();
call_from.setText(from_num);
String to_num = to.getText().toString();
call_to.setText(to_num);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm:ss");
String date = df.format(Calendar.getInstance().getTime());
date_call.setText(date);
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
Log.d("currentDateandTime",date+"");
String duration = "6 seconds";
databaseHelper_new.addFriend(from_num,to_num,duration,date);
dataAdapter.notifyDataSetChanged();
}
});
displayListView(); }
private void displayListView() {
Cursor cursor = databaseHelper_new.getFriends();
// The desired columns to be bound
String[] columns = new String[] { "call_from", "call_to","call_duration","call_date"};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code,
R.id.name,
R.id.continent,
R.id.region,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new MyCursorAdapter(
this, R.layout.country_info,
cursor,
columns,
to,
0);
listView = (ListView) findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode = cursor.getString(cursor.getColumnIndexOrThrow("call_from"));
Toast.makeText(getApplicationContext(),countryCode, Toast.LENGTH_SHORT).show();}});}
private class MyCursorAdapter extends SimpleCursorAdapter{
public MyCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//get reference to the row
View view = super.getView(position, convertView, parent);
//check for odd or even to set alternate colors to the row background
if(position % 2 == 0){
view.setBackgroundColor(Color.rgb(238, 233, 233));
}
else {
view.setBackgroundColor(Color.rgb(255, 255, 255));
}
return view;
}}}
Maybe it's not possible please use class that extends BaseAdapter

filling ListView from database in Android

I'm new in Android programming and I'm wondering witch is the most appropriate way to fill a ListView from DataBase.
Here the method I'm using in database to get my items
// Getting All stats
public List<StatParcours> getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
StatParcours stat = new StatParcours();
stat.setID(Integer.parseInt(cursor.getString(0)));
stat.setDate(cursor.getString(1));
stat.setDuration(cursor.getString(2));
stat.setDistance(Double.parseDouble(cursor.getString(3)));
stat.setSpeed(Double.parseDouble(cursor.getString(4)));
stat.setCondition(cursor.getString(5));
// Adding contact to list
statList.add(stat);
} while (cursor.moveToNext());
}
// return contact list
return statList;
}
and in the main activity, I'm using this. I know there is something wrong with the populateMyStatsList method, but I still don't know how to fix it.
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
populateMyStatsList ();
populateListView();
registerClickCallback();
}
private void populateMyStatsList (){
MyStats = db.getAllSats();
}
private void populateListView() {
ArrayAdapter<StatParcours> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Log.i("Populate", "ok");
}
private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.HistListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
StatParcours clickedCar = MyStats.get(position);
String message = "You clicked position " + position
+ " Which is car make " + clickedCar.getDate();
Toast.makeText(History.this, message, Toast.LENGTH_LONG).show();
}
});
}
private class MyListAdapter extends ArrayAdapter<StatParcours> {
public MyListAdapter() {
super(History.this, R.layout.item_view, MyStats);
Log.i("MyListAdapter", "ok");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
Log.i("Make sure", "ok");
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Log.i("getview", "ok");
StatParcours currentStat = MyStats.get(position);
TextView makeText = (TextView) itemView.findViewById(R.id.item_txtMake);
makeText.setText(currentStat.getDate());
TextView yearText = (TextView) itemView.findViewById(R.id.item_txtYear);
yearText.setText("" + currentStat.getDistance());
TextView condionText = (TextView) itemView.findViewById(R.id.item_txtCondition);
condionText.setText(currentStat.getCondition());
return itemView;
}
}
}
You need to use a SimpleCursor Adapter. I can't reach the developer site for the documentation but here is an example with your code above.
EDIT: Here is the link to the android developer website.
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
SECOND EDIT: This would go in the populateListView()
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Set your layout to int[]
int[] to = new int[]{R.id.item_txtMake,R.id.item_txtYear,R.id.item_txtCondition};
//set your columns to string[]; fill in your actual column names
string[] from = new string[]{"make","year","condition"};
//set up adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),R.layout.item_view, cursor, from,to,null);
//set adapter to listview
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Since you only have TextView in your ListView you can just simply use SimpleCursorAdapter.
// Getting All stats
public Cursor getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(selectQuery, null);
}
And in your History class
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
Cursor c = getAllSats();
String[] fromColumns = {Your database column name for date,
Your database column name for distance,
Your database column name for condition};
int[] toViews = {R.id.item_txtMake,
R.id.item_txtYear,
R.id.item_txtCondition};
adapter = new SimpleCursorAdapter(this, R.layout.item_view,
c, fromColumns, toViews, 0);
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
registerClickCallback();
}

android simplecursoradapter errors out every time

I'm stuck trying to create a simple cursor adapter. I've checked every website I can find, and all the threads here and I just can't see what's wrong.
gcDBAssist dbHelper;
SQLiteDatabase db;
Cursor cursor;
String display;
String TAG = "Listing the database";
ListView listTimeline;
SimpleCursorAdapter adapter;
static final String[] FROM = { gcDBAssist.C_ID, gcDBAssist.C_TIME, gcDBAssist.C_SCORE, gcDBAssist.C_LEVEL, gcDBAssist.C_POSTED, gcDBAssist.C_USER };
static final int[] TO = { R.id.textID, R.id.textTime, R.id.textScore, R.id.textLevel, R.id.textPosted, R.id.textUser };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_list);
listTimeline = (ListView) findViewById(R.id.listTimeline);
dbHelper = new gcDBAssist(this);
db = dbHelper.getReadableDatabase();
}
#Override
protected void onResume() {
super.onResume();
//get the data
cursor = db.rawQuery("SELECT * from " +gcDBAssist.TABLE, null);
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, FROM, TO, 0);
listTimeline.setAdapter(adapter);
I've run some checks and I can access the database using a while(cursor.moveToNext()).

Get information from a listItem onClick with _id

I have a listview populated by a database. The listview displays some columns of the database. I want to be able to click the listItem and display a new activity that shows that whole record. I am trying to do this by passing the id between through an intent but it is not working. The activity is starting but the textViews aren't being populated. I have included the relevent code snippets here. Would really appreciate some help
MainActivity
public class MainActivity extends ListActivity {
....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
}
private void fillList() {
ListView lv = getListView();
Cursor c = db.getData();
startManagingCursor(c);
CustomCursorAdapter adapter = new CustomCursorAdapter(getApplicationContext(), c);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent k = new Intent(MainActivity.this, ProductDetails.class);
k.putExtra("item_id", id);
startActivity(k);
}
});
}
}
ProdDetails
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new ProdDB(this);
setContentView(R.layout.product_details);
db.open();
long id = getIntent().getLongExtra("item_id", 0);
Cursor cursor = db.getDetails(id);
while(cursor.moveToFirst()){
tv1.setText(cursor.getString(cursor.getColumnIndex(ProdDB.KEY_PRODCODE)));
tv2.setText(cursor.getString(cursor.getColumnIndex(ProdDB.KEY_PRODNAME)));
...
...
}
}
}
DB.getDetails() - from ProdDB
String[] columns = new String[] {KEY_ROWID,
KEY_PRODCODE,
KEY_PRODNAME,
KEY_PRODTYPE,
KEY_PRODCAT,
KEY_PRODPRICE,
KEY_PRODRRP,
KEY_PRODSUPPLIER,
KEY_NOTES};
return db.query(DB_TABLE, columns, KEY_ROWID + " = ?", new String[]{String.valueOf(id)}, null, null, null);
you're having issue cause you're using while(cursor.moveToFirst()){. if you must use the while loop then you should use the .moveToNext() instead. Otherwise, you can just take out the while loop for moveToFirst since i'm assuming you only need the one row. as for why, don't ask me, i couldn't tell you.

Categories

Resources