load contact query in listview - android

I'm trying to show contact data in a listview. I think all it's ok but when I execute the app I have the follow error java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView.
The code is this:
public class BuscaContactos extends Activity {
ListView listContactos;
String opcion;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_busca_contactos);
listContactos=(ListView)findViewById(R.id.listContactos);
ArrayList<String> listagente = consultaAgenda();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(BuscaContactos.this, R.layout.activity_busca_contactos,listagente);
listContactos.setAdapter(adapter);
listContactos.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
private ArrayList<String> consultaAgenda() {
ArrayList<String> datos = new ArrayList<String>();
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String ContactID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String nombre = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
datos.add(ContactID);
datos.add(nombre);
}
c.close();
return datos;
}
}

R.layout.activity_busca_contactos should contain a TextView nothing else.
If you want to use other View then you need to create a CustomAdapter

Related

passing id to next activity through bundle

All i tried is to pass the listview selected items id to the next activity and show the id in a TextView on another page. I receive a number format exception when i click on list item. Any suggestions please.
DataBaseWrapper is the class where database is created.
DishOperation
public class DishOperation {
// Database fields
private DataBaseWrapper dbHelper;
private String[] DISHES_TABLE_COLUMNS = { DataBaseWrapper.DISHES_ID, DataBaseWrapper.DISHES_NAME,DataBaseWrapper.DISHES_INGREDIENTS };
private SQLiteDatabase database;
public DishOperation(Context context) {
dbHelper = new DataBaseWrapper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public Dish addDishes(String name,String ingredients) {
ContentValues values = new ContentValues();
values.put(DataBaseWrapper.DISHES_NAME, name);
values.put(DataBaseWrapper.DISHES_INGREDIENTS, ingredients);
long dishId = database.insert(DataBaseWrapper.DISHES, null, values);
// now that the student is created return it ...
Cursor cursor = database.query(DataBaseWrapper.DISHES,
DISHES_TABLE_COLUMNS, DataBaseWrapper.DISHES_ID + " = "
+ dishId, null, null, null, null);
cursor.moveToFirst();
Dish newComment = parseDishes(cursor);
cursor.close();
return newComment;
}
public void deleteDishes(Dish comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(DataBaseWrapper.DISHES, DataBaseWrapper.DISHES_ID + " = " + id, null);
}
public List getAllDishes() {
List dishes = new ArrayList();
Cursor cursor = database.query(DataBaseWrapper.DISHES,
DISHES_TABLE_COLUMNS, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Dish dish = parseDishes(cursor);
dishes.add(dish);
cursor.moveToNext();
}
cursor.close();
return dishes;
}
public String getInformation(Dish i)
{
long id=i.getId();
String ing= i.getIngredients();
return ing;
}
private Dish parseDishes(Cursor cursor) {
Dish dish = new Dish();
dish .setId((cursor.getInt(0)));
dish .setName(cursor.getString(1));
dish .setIngredients(cursor.getString(2));
return dish ;
}
}
Activity 1
public void onCreate(Bundle savedInstanceState) {
Button btListe;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dishDBoperation = new DishOperation(this);
dishDBoperation.open();
final List values = dishDBoperation.getAllDishes();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("key",id);
startActivity(intent);
}
});
Activity 2
int value;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
TextView text = (TextView) findViewById(R.id.editText3);
Bundle extras = getIntent().getExtras();
if (extras != null) {
long value = extras.getLong("key");
text.setText(String.valueOf(value));// updated!!
}
}
Change
value =Integer.parseInt( extras.getString("key"));
with
long value = extras.getLong("key");
also in your Activity2 you should move
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
in the very beginning of onCreate otherwise your findViewById will return null.
Edit.
Accordingly to the code you posted you have an ArrayAdapter of Dish. Your dataset and your ArrayAdapter should reflect it, and this can be done with Generics.
To get the id of your row as argument of onItemClick, you have to override getItemId. E.g.
setListAdapter(new ArrayAdapter<Dish>(this, android.R.layout.simple_list_item_1, values ) {
#Override
public long getItemId(int position) {
return getItem(position).getId();
}
}));
You should use value = extras.getLong("key"));
In Activity 1, id is of type long and in Activity 2, you try to retrieve it as a String.
Retrieve it by extras.getLong("key");

How do I get the cursor value of a ListView's item onItemClick?

I've created a database with tables (categories) with columns (_id, title etc). I want to read these categories' data from my database and list them in a ListView.
Here is my code:
public class MainActivity extends listActivity{
private ArrayAdapter arrayAdapter;
ArrayList results = new ArrayList();
ListView catlist;
Cursor cur;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
catlist = getListView();
int parentid = getIntent().getIntExtra("catid", 0);
openAndQueryDatabase(parentid);
displayCatListView();
}
private void displayCatListView() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
catlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Toast.makeText(MainActivity.this,
"List View Clicked:" + position, Toast.LENGTH_LONG)
.show();
}
});
}
private void openAndQueryDatabase(int parentid) {
DataBaseHelper db = new DataBaseHelper(this);
SQLiteDatabase dbr = db.getReadableDatabase();
cur = dbr.rawQuery(
"SELECT _id, title, has_sub FROM categories where parent_id=?",
new String[] { String.valueOf(parentid) });
if (cur != null) {
while (cur.moveToNext()) {
int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);
}
cur.close();
}
db.close();
}
}
I can get the item's position onItemClick, but I want to get their row's _id onItemClick. How do I do this?
I'm new to this. Are there any mistakes in my code?
Thanks a lot.
Use CursorAdapter(http://developer.android.com/reference/android/widget/CursorAdapter.html) instead, when you are using ArrayAdapter it's exceed memory allocation, and also you wouldn't get notifications if db changed.
Moreover in case of using CursorAdapter you will have
public void onItemClick(AdapterView<?> parent, View v, final int position, long id)
the "id" param will concur with table's _id field
to get the whole row just do
adapter.getItem(int position)
Instead of
int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);
create a Category class to contain these values, and use a parameterized ArrayList. Something like
class Category {
public int cat_id;
public String cattitle;
public int has_sub;
public Category(int cat_id, ...) {
// constructor logic here
}
}
and
results.add(new Category(cat_id, cattitle, has_sub));
With this, you can set the onItemClickListener as such:
catlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
final int position, long id) {
Category clickedCategory = results.get(position);
int id = clickedCategory.cat_id;
// do something with id
}
});
Your ArrayList is the data source of your ArrayAdapter, and position corresponds to the index of the clicked Category in it.

Delete item from database - ListView - Android

public class DataViewActivity extends Activity{
SQLiteDatabase db;
SimpleCursorAdapter adapter;
String dbTable = "users";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
ListView listView = (ListView) findViewById(R.id.dbPop);
DBHelper dbhelper = new DBHelper(DataViewActivity.this);
db = dbhelper.getWritableDatabase();
Cursor cursor = db.query(dbTable, null, null, null, null, null, null);
startManagingCursor(cursor);
String[] from = new String[] { "name","_id"};
int[] to = new int[] { android.R.id.text1 };
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from,
to);
listView.setAdapter(adapter);
}
}
How to implement onClick listener to this code to delete selected database row. I don't know much about Android so for me its a learning curve.
set setOnItemClickListener to your listview...
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
database.remove(id);//create removemethod in database class
}
});
and in remove method
public void remove(long id){
String string =String.valueOf(id);
database.execSQL("DELETE FROM favorite WHERE _id = '" + string + "'");
}
listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View v, int pos,long id) {
// TODO Auto-generated method stub
{
TextView tv=(TextView)v;
String s1=tv.getText().toString();
//delete row
String delgrp="DELETE FROM (tablename) WHERE (row)='"+s1+"'";
sdb.execSQL(delgrp);
}
ListView.onListItemClick, as third parameter has position. Position is the entry returned by Adpater.getItem(int). So when you click on a row of your ListView, the ListView.onListItemClick is fired. There you can retrieve your Adapter entry and use the info you need to delete the entry from the database.
public void onListItemClick(ListView parent, View v, int position, long id) {
// do something with the cursor
}

Android, SQLite rawQuery does not send any results after select a item in a listView

I'm trying to display a selected item in a listview, populated with SQLite in another activity, but when i make the rawQuery, using the _id row identifier to show it the item in the other activity, but does not send any results, leads me to the other activity, but did not shows anything in the xml layout, i don't know if i'm doing correctly my declaration of rawQuery, this is my search code and my handler to show it:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.course_details);
courseId = getIntent().getIntExtra("COURSE_ID", 0);
SQLiteDatabase db = (new DBHelper(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT emp._id, emp.title, emp.instructor, emp.length, emp.rating, emp.topic, emp.subject, emp.description, mgr._id managerId, mgr.title managerTitle FROM courses emp LEFT OUTER JOIN courses mgr ON emp.title = mgr._id WHERE emp._id = ?",
new String[]{""+courseId});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
tTitle = (TextView) findViewById(R.id.tTitle);
tTitle.setText(cursor.getString(cursor.getColumnIndex("title")));
tInstructor = (TextView) findViewById(R.id.tInstructor);
tInstructor.setText(cursor.getString(cursor.getColumnIndex("instructor")));
tLength = (TextView) findViewById(R.id.tLength);
tLength.setText(cursor.getString(cursor.getColumnIndex("length")));
tRating = (TextView) findViewById(R.id.tRating);
tRating.setText(cursor.getString(cursor.getColumnIndex("rating")));
tTopic = (TextView) findViewById(R.id.tTopic);
tTopic.setText(cursor.getString(cursor.getColumnIndex("topic")));
tSubject = (TextView) findViewById(R.id.tSubject);
tSubject.setText(cursor.getString(cursor.getColumnIndex("subject")));
tDescription = (TextView) findViewById(R.id.tDescription);
tDescription.setText(cursor.getString(cursor.getColumnIndex("description")));
}
db.close();
cursor.close();
return;
}}
this is the class that shows the listview and performs the Intent:
public class lay_main extends ListActivity {
public ListView list;
public DBHelper myAdap;
protected SQLiteDatabase db;
public Cursor cursor;
DBHelper Context;
DBHelper ArrayList;
//adapter cAdapter class
protected ListAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
collectXML();
setupDataBase();
setupAdapter();
}
private void collectXML()
{
list = (ListView)findViewById(android.R.id.list);
}
public void setupDataBase() {
myAdap = new DBHelper(getApplicationContext());
myAdap.insertCourses();
}
public void setupAdapter()
{
if(myAdap.getCourses()!=null)
{
adapter = new cAdapter(this, R.layout.list_courses, myAdap.getCourses());
list.setAdapter(adapter);
}
}
public void onListItemClick(ListView parent, View view, int position, long id)
{
super.onListItemClick(parent, view, position, id);
Intent intent = new Intent(this, CourseDetails.class);
Courses course = (Courses) adapter.getItem(position);
intent.putExtra("COURSE_ID", course.title);
startActivity(intent);
}}
really would appreciate your help.
You can send your data over an bundle:
Bundle sendBundle = new Bundle();
sendBundle.putString("COURSE_ID", course.title); //or use putInt if course.title is int type
//sendBundle.putInt("COURSE_ID", course.title);
Intent i = new Intent(lay_main.this, CourseDetails.class);
i.putExtra("testBundle", sendBundle);
startActivity(i);
and recieve it like:
Bundle receiveBundle = this.getIntent().getBundleExtra("testBundle");
if (receiveBundle != null){
String courseId = receiveBundle.getString("COURSE_ID");
//or int courseId = receiveBundle.getInt("COURSE_ID");
}

Inserting checked values from listView multiple choice

I've one listView with multiple choice and checkbox.
I get the values from listview executing a query in sqlite3.
When i click a button, I need to insert the selected items in another table but i don't know how can i do it.
Before doing insert i'm trying to know if it works showing one console log (Log.v). in this code there is not insert statement.
Any suggestions? Thanks in advance and sorry about my english,
Alex.
I paste the code:
public class productos extends Activity {
SQLiteDatabase db;
Spinner prodSpinner;
ArrayAdapter<String> prodAdapter;
Spinner catSpinner;
ArrayAdapter<String> catAdapter;
Cursor catCursor;
Cursor prodCursor;
String Value2;
String valor2;
SparseBooleanArray sp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productos);
Bundle extras = getIntent().getExtras();
//final String Value = extras.getSerializable("Lista").toString();
//final String Value2 = extras.getSerializable("Super").toString();
Button CatText2 = (Button) findViewById(R.id.textCategoria);
CatText2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.v("valor4:", "AAAAA");
recCatSpinner();
}
});
Button btSelecciona = (Button) findViewById(R.id.btSelecciona);
btSelecciona.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
Toast.makeText(getBaseContext(),"AAAA",Toast.LENGTH_SHORT).show();
}
});
Button btComanda = (Button) findViewById(R.id.btComanda);
btComanda.setOnClickListener(new OnClickListener() {
public void onClick (View arg0) {
EscriuComanda();
}
private void EscriuComanda() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
int count = 0;
//
sp = new SparseBooleanArray();
//SparseBooleanArray sp=prodSpinner.getCheckedItemPositions();
sp.clear();
sp = prodSpinner.getCheckedItemPositions();
for(int i = 0; i < sp.size(); i++)
{
if ( sp.valueAt(i)==true)
{
Log.v("400", "SI: " + valor2);
}
else
{
Log.v("500", "No: " + valor2);
}
}
}
});
//Toast.makeText(getBaseContext(),Value2,Toast.LENGTH_SHORT).show();
recCatSpinner();
}
public class UsuariosSQLiteHelper extends SQLiteOpenHelper {
public UsuariosSQLiteHelper(Context contexto, String nombre,
CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
public void onCreate(SQLiteDatabase db) {
Log.v("OnClickV", "1");
}
public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) {
Log.v("OnClickV", "1");
}
}
public Cursor recuperaCategoria()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "Categorias";
String[] columns = {"_id","Nombre"};
return db.query(tableName, columns, null, null, null, null, null);
}
public Cursor recuperaProductos()
{
final UsuariosSQLiteHelper usdbh =new UsuariosSQLiteHelper(this, "DBLlistaCompra", null, 1);
final SQLiteDatabase db = usdbh.getWritableDatabase();
String tableName = "ArtSuperV";
String[] columns = {"_id","NombreA"};
String where = "NombreC='" + valor2 + "'";
return db.query(tableName, columns, where, null, null, null, null);
}
public void recCatSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
catCursor = recuperaCategoria();
catCursor.moveToPosition(1);
catAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); //.simple_list_item_multiple_choice);// .simple_spinner_item);
catAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(catAdapter);
if (catCursor.moveToFirst()) {
do {
catAdapter.add(catCursor.getString(1));
}
while (catCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),catCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(catCursor);
catCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
recProdSpinner();
}
});
}
public void recProdSpinner() {
final ListView prodSpinner = (ListView) findViewById(R.id.spProductes);
prodCursor = recuperaProductos();
prodCursor.moveToPosition(1);
prodAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice); //.simple_list_item_multiple_choice);// .simple_spinner_item);
prodSpinner.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
prodAdapter.setDropDownViewResource (android.R.layout.simple_list_item_multiple_choice); //.simple_spinner_dropdown_item);
prodSpinner.setAdapter(prodAdapter);
if (prodCursor.moveToFirst()) {
do {
prodAdapter.add(prodCursor.getString(1));
}
while (prodCursor.moveToNext());
if (db != null) {
Toast.makeText(getBaseContext(),prodCursor.getString(1),Toast.LENGTH_SHORT).show();
db.close();
}
}
startManagingCursor(prodCursor);
prodCursor.close();
prodSpinner.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view2, int pos, long id) {
valor2 = parent.getItemAtPosition(pos).toString();
Toast.makeText(getBaseContext(),valor2,Toast.LENGTH_SHORT).show();
Log.v("valor2:", valor2);
}
});
}
}
Cant figure out some of the code flow due to language issue.But scheme should be:1. Set the adapters for both the lists (even if the lists are empty on launch, set the adapter with the empty but initialised array lists and make the array list as the global variables of the class so that they can be accessed from anywhere in the activity.) 2. Now select the items from the list1 and get their index in the first list.3. Add those items in the second array list. 4. Call the "notifyDataSetChanged()" for the adapter of the second list view.Link to know about proper use of "notifyDataSetChanged()" are notifyDataSetChanged example

Categories

Resources