Android SimpleCursorTreeAdapter Child Click - java

I have an expandable list using a simplecursortreeadapter
How would I integrate an onclicklistener or any way to change the
Below is my script so far. I was trying to use the onclicklistener at the bottom of this post, but I cannot figure out how to change it from a listview to expandable listview listener for the children.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cattest);
SQLiteDatabase checkDB = null;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor groupCursor = checkDB.rawQuery("SELECT * FROM countries", null);
MySimpleCursorTreeAdapter mscta = new MySimpleCursorTreeAdapter(
this,
groupCursor,
R.layout.employee_list_item,
new String[] {"country"},
new int[] {R.id.country},
R.layout.employee_list_item,
new String[] {"employee"},
new int[] {R.id.lastName});
setListAdapter(mscta);
checkDB.close();
}
class MySimpleCursorTreeAdapter extends SimpleCursorTreeAdapter{
public MySimpleCursorTreeAdapter(Context context, Cursor cursor,
int groupLayout, String[] groupFrom, int[] groupTo,
int childLayout, String[] childFrom, int[] childTo) {
super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom,
childTo);
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
String countryID = Integer.toString(groupCursor.getInt(0));
SQLiteDatabase checkDB = null;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor value = checkDB.rawQuery("SELECT * FROM employee WHERE _id='"+ countryID +"'", null);
String test = "";
if(value.moveToFirst())
test = value.getInt(0) + ": " + value.getString(1);
while(value.moveToNext()){
test += ";" + value.getInt(0) + ": " + value.getString(1);
}
return value;
}
}
Tried implementing this
questionList = (ListView) findViewById (R.id.list);
sample(typedText);
questionList.setOnItemClickListener(
new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
Intent intent = new Intent(All.this, com.second.app.Second.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
//Cursor cursor = (Cursor) adapter.getItem(position);
//intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
}
);
EDIT:
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
// use groupPosition and childPosition to locate the current item in the adapter
Intent intent = new Intent(Categories.this, com.second.app.Second.class);
Cursor cursor = (Cursor) mscta.getItem(childPosition);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
//Cursor cursor = (Cursor) adapter.getItem(position);
//intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
return true;
}
At the moment the getChild(childPosition); is outputting the error
The method getItem(int) is undefined for the type
Categories.MySimpleCursorTreeAdapter

Look into the setOnChildClickListener method: http://developer.android.com/reference/android/widget/ExpandableListView.html#setOnChildClickListener(android.widget.ExpandableListView.OnChildClickListener)

Related

How to Filter Contacts using SimpleCursorAdapter and ListView

I am trying to add a Search Contact feature in my app.
Everything is working fine but the search contact function is not working.
I trying to implement this feature for 2 days but i don't where i am doing mistake. If anybody can figured out the mistake please write the answer.
private void getContactResults () {
//TODO get contacts code here
Toast.makeText(this, "Getting contacts ....", Toast.LENGTH_LONG).show();
li = (ListView) findViewById(R.id.list);
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
final String phoneNumber = ContactsContract.CommonDataKinds.Phone.NUMBER;
final String phoneName = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
final String phoneID = ContactsContract.CommonDataKinds.Phone._ID;
final String[] ContactsList = {phoneName, phoneNumber, phoneID};
final int[] to = {android.R.id.text1, android.R.id.text2};
final SimpleCursorAdapter ArrayAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, ContactsList, to);
li.setAdapter(ArrayAdapter);
li.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
new ArrayList<>(Arrays.asList((ContactsList)));
// Filter contacts by search
li.setTextFilterEnabled(true);
ArrayAdapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
return cur;
}
});
EditText queryText = (EditText) findViewById(R.id.search_box);
queryText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
}
#Override
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
// This is the filter in action
ArrayAdapter.getFilter().filter(s.toString());
// Don't forget to notify the adapter
ArrayAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(final Editable s) {
// This is the filter in action
ArrayAdapter.getFilter().filter(s.toString());
// Don't forget to notify the adapter
ArrayAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Data changed", Toast.LENGTH_SHORT).show();
}
});
ArrayAdapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
return cur;
}
});
The error is in the code above. It doesn't look like you are using the constraint value
It should be like the
ArrayAdapter.setFilterQueryProvider(new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null ,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, new String[]{constraint}, null);
return cur;
}
});
I would also advise not using null, as per the android documentation due to performance issue that can arise.
* #param projection A list of which columns to return. Passing null will
* return all columns, which is inefficient.

how to open item in search listview

Hi I have a search list in which I want to click on any item. By clicking a particular position, item on that position should open. I have done the following :
public List<DBSearch> searchByName(String name){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from biography where name like '%" + name + "%'", null);
List<DBSearch> dbsearch = new ArrayList<>();
while (cursor.moveToNext()){
DBSearch sea = new DBSearch();
sea.setId(cursor.getLong(0));
sea.setName(cursor.getString(1));
sea.setImage(cursor.getBlob(2));
sea.setComment(cursor.getString(3));
dbsearch.add(sea);
}
cursor.close();
db.close();
return dbsearch;
}
and this is my activity :
private void search(String name) {
persons = (ArrayList<DBSearch>) databaseAdapter.searchByName(name);
SearchAdapter personListAdapter = new SearchAdapter(persons, this);
personListView.setAdapter(personListAdapter);
personListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
Intent i = new Intent(getBaseContext(),AWDetailsActivity.class);
String my_id = persons.get(position).getId("id").toString();
i.putExtra("id", my_id);
startActivity(i);
}
}
);
}
Thank you very much.

Android Listview not updating after delete item

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ?
DatabaseHandler .java code
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
SQLAdapter.java code
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and Main java code
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
if (contact_data.size() > 0)
contact_data.remove(position);
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
}
i can remove item in database ,but listview not updated . what am i doing wrong ? if anyone knows solution help me
thanks
Under your method dbHelper.deleteUser add this code:
contact_data.remove(position);
To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter.
EDIT:
Add one remove method in your adapter for you can remove object. Code:
Adapter:
public void removeObject (int position) {
this.data.remove(position);
}
Activity:
Change:
contact_data.remove(position);
to:
cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();
EDIT 2:
Just delete all the objects from ArrayList.
contact_data.clear();
or in your adapter
data.clear();

Display data from SQLite database into ListView in Android

Although this question has been asked many times on here, I just can't find the proper answer to fit my code. I realise it may be something small, but I just can't seem to find the problem as I'm only really new to this.
Here's my code getClientNames in DatabaseHelper class:
public Cursor getSitesByClientname(String id) {
String[] args={id};
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
String results = "";
/*int count = myCursor.getCount();
String[] results = new String[count + 1];
int i = 0;*/
if (myCursor != null) {
if(myCursor.getCount() > 0)
{
for (myCursor.moveToFirst(); !myCursor.isAfterLast(); myCursor.moveToNext())
{
results = results + myCursor.getString(myCursor.getColumnIndex("client_sitename"));
}
}
}
return results;
}
One problem is that I'm returning a 'String' to the 'Cursor', but I'm not sure what is the best way around this, as I think I should be returning a Cursor.
Here's the ClientSites class where I want to display the data:
public class ClientSites extends Activity {
//public final static String ID_EXTRA="com.example.loginfromlocal._ID";
private DBUserAdapter dbHelper = null;
private Cursor ourCursor = null;
private Adapter adapter=null;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
//dbHelper.createDatabase();
dbHelper.openDataBase();
ourCursor = dbHelper.getSitesByClientname(uID);
Log.e("ALERT", uID.toString());
startManagingCursor(ourCursor);
Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "XXERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
{
Intent i=new Intent(ClientSites.this, InspectionPoints.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class Adapter extends CursorAdapter {
#SuppressWarnings("deprecation")
Adapter(Cursor c) {
super(ClientSites.this, c);
}
//#Override
public void bindView(View row, Context ctxt,
Cursor c) {
Holder holder=(Holder)row.getTag();
holder.populateFrom(c, dbHelper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Holder holder=new Holder(row);
row.setTag(holder);
return(row);
}
}
static class Holder {
private TextView name=null;
Holder(View row) {
name=(TextView)row.findViewById(R.id.ingredientText);
}
void populateFrom(Cursor c, DBUserAdapter r) {
name.setText(r.getName(c));
}
}
}
Here is the code I'm now using to try and display the data in the Listview. I have altered it somewhat from my original attempt, but still not sure what I'm doing wrong.
public void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.client_sites);
Intent i = getIntent();
String uID = String.valueOf(i.getIntExtra("userID", 0));
//int uID = i.getIntExtra("userID", 0);
//ListView myListView = (ListView)findViewById(R.id.myListView);
dbHelper = new DBUserAdapter(this);
dbHelper.createDatabase();
dbHelper.openDataBase();
String[] results = dbHelper.getSitesByClientname(uID);
//setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results));
//adapter = new ArrayAdapter<String>(ClientSites.this, R.id.myListView, results);
setListAdapter(new ArrayAdapter<String>(ClientSites.this, R.layout.client_sites, results));
//ListView myListView = (ListView)findViewById(R.id.myListView);
ListView listView = getListView();
listView.setTextFilterEnabled(true);
//ourCursor = dbHelper.getSitesByClientname(uID);
//Log.e("ALERT", uID.toString());
//startManagingCursor(ourCursor);
//Log.e("ERROR", "After start manage cursor: ");
//#SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.id.myListView, null, null, null); // LOOK AT THIS IN THE MORNING!!!!!!!!!!!
//CursorAdapter adapter = new SimpleCursorAdapter(this, R.id.myListView, null, null, null, 0);
//adapter = new Adapter(ourCursor);
//Toast.makeText(ClientSites.this, "Booo!!!", Toast.LENGTH_LONG).show();
//myListView.setAdapter(adapter);
//myListView.setOnItemClickListener(onListClick);
I Created a Listview from a database. Here is the code I used for my app
Here is part of the database handler. It will return a List of Categories for my listview. It can return a list of Strings if that is what you need.
public List<Category> getAllCategorys() {
ArrayList<Category> categoryList = new ArrayList<Category>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
try{
if (cursor.moveToFirst()) {
do {
Category category = new Category();
category.setID(Integer.parseInt(cursor.getString(0)));
category.setCategory(cursor.getString(1));
// Adding category to list
categoryList.add(category);
} while (cursor.moveToNext());
}
}finally{
cursor.close();
}
db.close();
// return category list
return categoryList;
Here is how I fill the ListView by calling the database.
int size = db.getCategoryCount();
List<Category> categoryList = db.getAllCategorys();
category_data = new String[size-1];
int i=0;
for(Category cn : categoryList)
{
category_data[i] = cn.getCategory(); // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.categoryrow, category_data);
listViw.setAdapter(listAdapter);
EDIT: Here is something that should work for you
public List<String> getSitesByClientname(String id) {
String[] args={id};
ArrayList<String> result = new ArrayList<String>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor myCursor = db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
try{
if (myCursor.moveToFirst()){
do{
result.add(myCursor.getString(myCusor.getString(myCursor.getColumnIndex("client_sitename"));
}while(myCursor.moveToNext());
}
}finally{
myCursor.close();
}
db.close();
return result;
}
Use it like this
List<String> sites_data = dbHelper.getSitesByClientname(uID);
result_data = new String[sites_data.size()];
int i=0;
for(String s : sites_data)
{
result_data[i] = s; // get the name of the category and add it to array
i++;
}
listAdapter = new ArrayAdapter<String>(this, R.layout.client_sites, result_data);
listViw.setAdapter(listAdapter);
If you want to return the Cursor from dbHelper you can do something like this...
public Cursor getSitesByClientname(String id) {
String[] args={id};
return db.rawQuery("SELECT client_sitename FROM " + CLIENT_SITES_TABLE + " WHERE client_id=?", args);
}
I'd also take some time to read the listview tutorial

listview scrolls to top on delete

ok i have searched and found some solutions that seemed to work for others although i cant figure it out for my self...
"The problem is that you are creating a new adapter every time you reload the data. That’s not how you should use ListView and its adapter. Instead of setting a new adapter (which causes ListView to reset its state), simply update the content of the adapter already set on the ListView. And the selection/scroll position will be saved for you."
when i go to modify an entry or create and hit back instead of confirm it holds my position.
when i confirm a new entry it goes to the top and my new item goes to the bottom...
if i delete an old entry it goes to top
and when i close the app and reopen it goes to top.
mainly i want it to hold position when i delete an item and when i close the app and reopen it.
also when i create a new entry i want it to show that entry
mDbHelper = new QuotesDBAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button1 = (Button) findViewById(R.id.plus);
button1.setOnClickListener(new OnClickListener() {
// #Override
public void onClick(View arg0) {
createNote();
// Intent intent = new Intent(context, QuoteEdit.class);
// startActivity(intent);
}
});
}
private void fillData() {
// Get all of the rows from the database and create the item list
mNotesCursor = mDbHelper.fetchAllQuotes();
startManagingCursor(mNotesCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{QuotesDBAdapter.KEY_QUOTES};
// and an array of the fields we want to bind those fields to (in this case just text1)
int[] to = new int[]{R.id.text1};
// Now create a simple cursor adapter and set it to display
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.row, mNotesCursor, from, to);
setListAdapter(notes);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
menu.add(1, ACTIVITY_CREATE, 0, R.string.menu_insert);
}
public boolean onContextItemSelected;
public boolean onContextItemSelected(MenuItem item) {
AdapterView<ListAdapter> mList = null;
switch(item.getItemId()) {
case ACTIVITY_CREATE:
try {
Intent i = new Intent(this, QuoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
catch (Exception ex)
{
Context context = getApplicationContext();
CharSequence text = ex.toString();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
fillData();
return true;
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteQuote(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createNote() {
Intent i = new Intent(this, QuoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, QuoteEdit.class);
i.putExtra(QuotesDBAdapter.KEY_ROWID, id);
i.putExtra(QuotesDBAdapter.KEY_QUOTES, c.getString(
c.getColumnIndexOrThrow(QuotesDBAdapter.KEY_QUOTES)));
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
try
{
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
switch(requestCode) {
case ACTIVITY_CREATE:
String title = extras.getString(QuotesDBAdapter.KEY_QUOTES);
mDbHelper.createQuote(title);
fillData();
break;
case ACTIVITY_EDIT:
Long rowId = extras.getLong(QuotesDBAdapter.KEY_ROWID);
if (rowId != null) {
String editTitle = extras.getString(QuotesDBAdapter.KEY_QUOTES);
mDbHelper.updateQuote(rowId, editTitle);
}
fillData();
break;
}
}
catch (Exception ex)
{
Context context = getApplicationContext();
CharSequence text = ex.toString();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
// toast.show(); <- something is wrong. fix later. ->
}
}
}
// adapter code
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS tblRandomQuotes");
onCreate(db);
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* #param ctx the Context within which to work
*/
public QuotesDBAdapter(Context ctx) {
this.mCtx = ctx;
}
public QuotesDBAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createQuote(String quotes) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_QUOTES, quotes);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteQuote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllQuotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_QUOTES}, null, null, null, null, null);
}
public Cursor fetchQuote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_QUOTES}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateQuote(long rowId, String title) {
ContentValues args = new ContentValues();
args.put(KEY_QUOTES, title);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
public int getAllEntries()
{
Cursor cursor = mDb.rawQuery("SELECT COUNT(quotes) FROM tblRandomQuotes", null);
if (cursor.moveToFirst()) {
return cursor.getInt(0);
}
return cursor.getInt(0);
}
public String getRandomEntry()
{
Cursor cursor = mDb.rawQuery("SELECT quotes FROM tblRandomQuotes order by RANDOM() limit 1", null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
} else {
return "No Quotes to display.";
}
}
/*
public String getRandomEntry()
{
int id = 1;
id = getAllEntries();
int rand = random.nextInt(id) + 1;
Cursor cursor = mDb.rawQuery("SELECT quotes FROM tblRandomQuotes WHERE _id = " + rand, null);
if(cursor.moveToFirst()) {
return cursor.getString(0);
}
return cursor.getString(0);
}
*/
}
// and edit activity code
mQuoteText = (EditText) findViewById(R.id.title);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(QuotesDBAdapter.KEY_QUOTES);
mRowId = extras.getLong(QuotesDBAdapter.KEY_ROWID);
if (title != null) {
mQuoteText.setText(title);
}
}
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bundle bundle = new Bundle();
jokesToBeAdded = mQuoteText.getText().toString();
if(jokesToBeAdded.length() < 1) {
Toast.makeText(getApplicationContext(), "you forgot something.", Toast.LENGTH_LONG).show();
// createNote();
}
else{
Toast.makeText(getApplicationContext(), "done.", Toast.LENGTH_LONG).show();
bundle.putString(QuotesDBAdapter.KEY_QUOTES, jokesToBeAdded);
}
if (mRowId != null) {
bundle.putLong(QuotesDBAdapter.KEY_ROWID, mRowId);
}
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
}
});
}
protected EditText getString(String keyQuotes, String string) {
// TODO Auto-generated method stub
return null;
}
private void createNote() {
Intent i = new Intent(this, QuoteEdit.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button android:id="#+id/plus"
android:background="#drawable/selector"
android:layout_width="fill_parent"
android:layout_height="75dp"
android:layout_alignParentBottom="true"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/plus"
>
</ListView>
<TextView android:id="#android:id/empty" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="#string/noQ"
/>
</RelativeLayout>
You can do one thing is that, get the visible position of the ListView item before refresing the ListView and then set the position after refreshing the ListView.
I hope you are extending your Activity as ListActivity
ListView mListView = getListView();
int firstPosition = mListView.getFirstVisiblePosition();
setListAdapter(adapter);
mListView.setSelection(firstPosition);
EDIT
In your fillData() function after you call setListAdapter(notes); add one more line set ListView to show the last row like this,
int firstPosition = mListView.getFirstVisiblePosition();
this.setSelection(firstposition)

Categories

Resources