I want to get latitude and longitude data from sqlite database.
So i use this code below, but there is a problem in getListAdapter(). It say that i must create 'getListAdapter()' method. I'm searching on the net, but there is no example for getListAdapter() method.
Can you fix my code. So if i click the item it will give me the lat and long data from my database.
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
//TODO Auto-generated method stub
String selectedItem = (String) getListAdapter().getItem(position);
String query = "SELECT lat, long FROM hoteltbl WHERE name = '" + selectedItem + "'";
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
Cursor result = dbs.rawQuery(query, null);
result.moveToFirst();
double lat = result.getDouble(result.getColumnIndex("lat"));
double longi = result.getDouble(result.getColumnIndex("long"));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&saddr=&daddr="+lat+","+longi));
startActivity(intent);
}
By the way, this is the problem from my previous question
You do not need to extend ListActivity. You simply need to find the listview and call its getAdapter() method.
Here is your updated code.
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
//TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.YOURLISTVIEW);
String selectedItem = (String) lv.getAdapter().getItem(position);
String query = "SELECT lat, long FROM hoteltbl WHERE name = '" + selectedItem + "'";
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
Cursor result = dbs.rawQuery(query, null);
result.moveToFirst();
double lat = result.getDouble(result.getColumnIndex("lat"));
double longi = result.getDouble(result.getColumnIndex("long"));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&saddr=&daddr="+lat+","+longi));
startActivity(intent);
}
Your activity should extends ListActivity to have getListAdapter method.
Take a look at this tutorial.
If you want to get item, you should use getItem(position) method from adapter which was set to ListView
Related
I have to find "id" in database and I try this way but I can't solve it. Could you help me. Thanks a lot.
listview.setOnItemClickListener(new AdapterView.XouOnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String text = (String) listview.getItemAtPosition(arg2);
Database db = new Database(getApplicationContext());
String query = "SELECT name, id FROM tableDB WHERE name = '" + text + "'"; // I think problem is here
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
id_position = cursor.getInt(cursor.getColumnIndex("id"));
go_detail();
}
});
// this part is OK
private void go_detail(){
Intent intent = new Intent(getApplicationContext(), Detail_page.class);
intent.putExtra("id", (int) name_ids[id_position]);
startActivity(intent);
}
I think error is in your go_detail function. try adding a parameter, such as go_detail(int id_position){....} right now, it cant get the id without parameter
I want to open new activity which will display instructions from the position id of my listview.
This is my helper
public List<step_con> getSteps(){
List<step_con> steplist = new ArrayList<step_con>();
String query = "SELECT s1,s1_img,s2,s2_img,s3,s3_img,s4,s4_img,s5,s5_img,s6,s6_img, FROM step_software WHERE _id = "+ id;
Cursor cur = database.rawQuery(query, null);
if (cur.moveToFirst()) {
do {
step_con steps = new step_con();
steps.setS(cur.getString(0));
steps.setImage(cur.getBlob(1));
steps.setS2(cur.getString(2));
steps.setImage2(cur.getBlob(3));
steps.setS3(cur.getString(4));
steps.setImage3(cur.getBlob(5));
steps.setS4(cur.getString(6));
steps.setImage4(cur.getBlob(7));
steps.setS5(cur.getString(8));
steps.setImage5(cur.getBlob(9));
steps.setS6(cur.getString(10));
steps.setImage6(cur.getBlob(11));
} while (cur.moveToNext());
}
database.close();
return steplist;
}
The +id is the position of mylistview.
And this is my listitemclick
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),DatabaseAccess.class);
int pos = position;
String pos1 = String.valueOf(pos);
}
I'm new to android without attending class, just learning by myself. Please help what should i do or include?
How to create cursor object to get item id from database?
Here is my method of DBHelper, see the Cursor method
public int getItemIdByPosition(int position) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToPosition(position);
return Integer.parseInt(cursor.getString(0));
}
Seems to be correct.
Maybe the position passed through method is not correct, maybe is more efficient is you use, instead of pass a position on your method pass the ID:
"select * from " + TABLE_NAME + " where id = " = id
Also you can use:
cursor.getColumnIndex(COLUMN_NAME) instead of cursor.getString(0)
Your code seems to be right, I just would check the below things that I mentioned.
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE " + POSITION + " = " + position;
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
int userId;
if (cursor.moveToFirst())
{
userId = cursor.getInt(0);
}
cursor.close();
return userId;
This is a sample code hope you can get a help from this
private void displayListView(String getter){
//get the customer data from the db and feed them to cursor and load the data to lest
Cursor cursor = dbHelper.fetchallcustomercompany(getter);
String[] columns = new String[] {
//get the needed columns of the db and feed them in to string array
DBCreater.Key_customer_Shop
};
int[] to = new int[]{
//get the textboxs in xml layout,which going to display the values in to integer array
R.id.tv_demo_search_text_Isuru
};
//address the xml list view to java
final ListView listView = (ListView)findViewById(R.id.lv_searchcustomer_cuzlist_Isuru);
// feed the context,displaying layout,data of db, data source of the data and distination of the data
if(cursor.getCount()==0){
Toast.makeText(getApplicationContext(), " No matching data", Toast.LENGTH_SHORT).show();
}
else{
dataAdapter = new SimpleCursorAdapter(this, R.layout.demo_search, cursor, columns, to,0);
//load the data to list view
listView.setAdapter(dataAdapter);
//what happen on when user click on the item of the list view
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Cursor cursor =(Cursor)listView.getItemAtPosition(arg2);
//get the value of the customer name from the clicked listitem
String name=cursor.getString(cursor.getColumnIndexOrThrow("customer_shop"));
}
});
}
}
Try this:
public int getItemIdByPosition(int position) {
int itemID = 0;
Cursor localCursor = database.rawQuery("select * from " + TABLE_NAME,
null);
int i = localCursor.getColumnIndex("ID");
if (localCursor.moveToFirst()) {
do {
itemID = Integer.parseInt(localCursor.getString(i));
} while (localCursor.moveToPosition(position));
}
localCursor.close();
return itemID;
}
I am simply displaying a list from sqlite table. I have not used any BDHelper class. With this code only how can i get id.
When i click on 1st Item, it shows 0 where as in table it's id is 1. Below is my code.
SQLiteDatabase myDB;
try {
myDB = openOrCreateDatabase(DB_NAME,
SQLiteDatabase.CREATE_IF_NECESSARY, null);
myDB.execSQL("create table if not exists " + COUNTRY_TABLE
+ "(country_id INTEGER PRIMARY KEY,"
+ "country_title text,"
+ "country_status int(11));");
/*myDB.execSQL("insert into " + COUNTRY_TABLE +" values "+
"(null,'India',1)," +
"(null,'China',1)," +
"(null,'Australia',1)," +
"(null,'Japan',1)," +
"(null,'Germany',1)");*/
Cursor c = myDB.rawQuery("select country_id,country_title from "
+ COUNTRY_TABLE + " where country_status=1", null);
if (c != null) {
if (c.moveToFirst()) {
do {
int id = c.getInt(c.getColumnIndex("country_id"));
String name = c.getString(c.getColumnIndex("country_title"));
clist.add(id + ") " + name);
} while (c.moveToNext());
//int itemcount = clist.size();
//Toast.makeText(MainActivity.this, itemcount, Toast.LENGTH_LONG).show();
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, clist));
}
}
} catch (SQLiteException se) {
Toast.makeText(MainActivity.this, se.getMessage().toString(),Toast.LENGTH_LONG).show();
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(MainActivity.this,String.valueOf(id),Toast.LENGTH_LONG).show();
}
Please suggest what should i do to get the id fron table and not the position.
try below code:
Put your id and name data in clist ArrayList, generate getter, setter method first, set your id and name in that method when myou get that data, each time add that data in ArrayList and then use it like below.
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(MainActivity.this,clist.get(position).getId(),Toast.LENGTH_LONG).show();
}
public List<Emp> AllRecords()
{
List<Emp> dataset = new ArrayList<Emp>();
Cursor cursor = database.query(DatabaseHelper.TABLE_EMPLOYEE,allColumns, null, null,null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Emp obj = cursorToContact(cursor);
dataset.add(obj);
cursor.moveToNext();
}
cursor.close();
return dataset;
}
private Emp cursorToContact(Cursor cursor)
{
Emp obj = new Emp();
obj.setId(cursor.getInt(0));
obj.setName(cursor.getString(1));
obj.setDesig(cursor.getString(2));
return obj;
}
//--------------
list_data = (ArrayList<Emp>) qh.AllRecords();
CustomListAdapter adapter = new CustomListAdapter(MainActivity.this,list_data);
//---------
int id=list_data.get(arg2); //Type mismatch: cannot convert from Emp to int
Plz tell what should i write to get country id.
Seeing as how there is no accepted answer...
I did this and it seemed to work.
I'm using a ListView Activity, SQLiteDatabase and an ArrayAdapter
In my onListItemClick method, I instantiate a new object and make it equal to whatever item is at that current position in my adapter.
Task task = adapter.getItem(arg3);
In my task class, I have a private variable of type long called id, as well as a setter and getter for that variable.
Hence, I can then do this:
long taskId = task.getId();
Checking this result with Toast yielded the id generated by SQLite NOT the position in the ListView, which is what I needed.
Hope this helps someone out!
you can set tag on list item with the id after which you can call getTag() on onItemClick.
((TextView)v).getText(); by using this we will get the text of view, then we can query to the table again to get id of the corresponding text and toast it.
String country_title=((TextView)v).getText();
Cursor c = myDB.rawQuery("select country_id from "+ COUNTRY_TABLE + " where country_title='"+country_title+"'", null);
Toast.makeText(MainActivity.this,c.getString(c.getColumnIndexorThrow("country_title")),Toast.LENGTH_LONG).show();
This was not possible the way i wanted it but got its solution some other way. While in cursor loop, adding data to list, take another ArrayList and add only id to it.
clist1.add(id);
Now, on onListItemClick, you can get the position of the item. So, use this position and get the id from the other ArrayList clist1
int country_id=clist1[position];
Hope this helps.
I'm a couple years late, but it might help someone else: basically set the tag wherever you're setting the individual views.
// Find fields to populate in inflated template
TextView productName = (TextView) view.findViewById(R.id.product_name);
TextView productPrice = (TextView) view.findViewById(R.id.product_price);
TextView productQuantity = (TextView) view.findViewById(R.id.product_quantity);
// Extract properties from cursor
String name = cursor.getString(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_NAME));
int price = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_PRICE));
int quantity = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.COLUMN_QUANTITY));
int id = cursor.getInt(cursor.getColumnIndexOrThrow(ProductDbContract.ProductEntry.ID));
// Set Tag
productName.setTag(id);
and then later you can access it by calling on getTag():
int id = (Integer)((TextView)findViewById(R.id.product_name)).getTag();
Log.d("LETSEE",String.valueOf(id));
I need your help to fix my code.
My intention is if i click the item on ListView it will take me to intent action_view.
The problem is i got force close if i click the item on ListView.
I think the problem is in onItemClick method, can you give the better way to get it done.
Here's my code:
public class HotelList extends ListActivity{
hotelHelper dbHotelHelper;
protected Cursor cursor;
protected ListAdapter adapter;
ListView numberList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.hotellist);
numberList = (ListView)findViewById(android.R.id.list);
numberList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
String selectedItem = (String) getListAdapter().getItem(position);
String query = "SELECT lat, long FROM hoteltbl WHERE name = '" + selectedItem + "'";
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
Cursor result = dbs.rawQuery(query, null);
result.moveToFirst();
double lat = result.getDouble(result.getColumnIndex("lat"));
double longi = result.getDouble(result.getColumnIndex("long"));
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?f=d&saddr=&daddr="+lat+","+longi));
startActivity(intent);
}
});
dbHotelHelper = new hotelHelper(this);
try{
dbHotelHelper.createDataBase();
}
catch (Exception ioe){
Log.e("err","Unable to create database");
}
view();
}
private void view() {
// TODO Auto-generated method stub
SQLiteDatabase db = dbHotelHelper.getReadableDatabase();
try{
cursor = db.rawQuery("SELECT * FROM hoteltbl", null);
adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"name"},
new int[] {android.R.id.text1}
);
numberList.setAdapter(adapter);
}
catch (Exception e){
Log.e("error",e.toString());
}
}
}
Inside item click
you have many ways it might cause exception,
Exception will cause your app force close
your code is not handled with exceptions
I am listing down the causes it might cause the exception, please check followings
String selectedItem = (String) getListAdapter().getItem(position);
here you might get type conversation issue, you are converting something is not supported by String
SQLiteDatabase dbs = dbHotelHelper.getReadableDatabase();
Cursor result = dbs.rawQuery(query, null);
result.moveToFirst();
double lat = result.getDouble(result.getColumnIndex("lat"));
double longi = result.getDouble(result.getColumnIndex("long"));
If dbHotelHelper.getReadableDatabase returns null or dbHotelHelper null, in this case your app will force close
In case dbs.rawQuery return null, your app will force close
if result null then you might calling moveToFirst, getDouble and getColumnIndex on null object, in this case also your app will force close
For your info
SimpleCursorAdapter constructor was deprecated in API level 11.
This option is discouraged, as it results in Cursor queries being performed on the application's UI thread and thus can cause poor responsiveness or even Application Not Responding errors. As an alternative, use LoaderManager with a CursorLoader.