Wrong when scroll listview with adapter - android

(Sorry I'm not good at English)
I haved created a custom BaseAdapter to show my data from sqlite to a ListView.
Now I can see list but when i scroll listview quickly, rows are view oddly. I can't understand this. And one more strange point is that, if i have 5 data row, getView run 5 time but only first 4 row can be show. I use log and i see 5 time "return view;" clearly.
Here are my adapter code:
public class LocalRankAdapter extends BaseAdapter {
private static final String FIELD1 = "time";
private static final String FIELD2 = "name";
private static final String TABLE_NAME = "rank";
private static final String FIELD_ORDER = "time";
private DataBaseHelper dbHelper;
private Cursor mCursor;
private Context mContext;
private int timeColIndex;
private int nameColIndex;
private int index;
private int length;
public static float recent_time=0;
public static String recent_playerName="";
public LocalRankAdapter(Context context, DataBaseHelper mdbHelper) {
mContext=context;
dbHelper=mdbHelper;
// get data from database
mCursor = dbHelper.getData(TABLE_NAME, new String[] { FIELD1, FIELD2 }, FIELD1 + " !=0 ", FIELD_ORDER + " ASC");
mCursor.moveToFirst();
length=mCursor.getCount();
timeColIndex=mCursor.getColumnIndex(FIELD1);
nameColIndex=mCursor.getColumnIndex(FIELD2);
index=1;
}
public static void insertData(DataBaseHelper dbHelper, float currentTime, String name) {
ContentValues cv=new ContentValues();
cv.put(FIELD1, currentTime);
cv.put(FIELD2, name);
dbHelper.insertData(TABLE_NAME, new String[] {FIELD1, FIELD2}, cv);
}
#Override
public int getCount() {
return length-1;
}
#Override
public View getView(int id, View convertView, ViewGroup parent) {
View v=convertView;
if (convertView == null) {
v=convertView;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, parent, false);
TextView rankNumber=(TextView) v.findViewById(R.id.txtRank);
TextView time=(TextView) v.findViewById(R.id.txtTime);
TextView playerName=(TextView) v.findViewById(R.id.txtPlayerName);
String timeStr=mCursor.getString(timeColIndex);
String playerNameStr=mCursor.getString(nameColIndex);
if(Float.parseFloat(timeStr)==(recent_time/1000f) && playerNameStr.equals(recent_playerName)) {
v.setBackgroundColor(mContext.getResources().getColor(R.color.item_bg_recent));
rankNumber.setText(String.valueOf(index++)+" (Your)");
} else rankNumber.setText(String.valueOf(index++));
time.setText(timeStr);
playerName.setText(playerNameStr);
mCursor.moveToNext();
return v;
}
return v;
}
#Override
public Object getItem(int id) {
return id;
}
#Override
public long getItemId(int arg0) {
return 0;
}
public static void setModeView(int mtime, String mplayerName) {
recent_time=mtime;
recent_playerName=mplayerName;
}
}

you change your query
String getData = "SELECT " + FIELD1 + "," + FIELD2 + " FROM " + TABLE_NAME;
Cursor cursor;
cursor = myDataBase.rawQuery(getData, null);
while (cursor.moveToNext()) {
//String cursor.getColumnIndex(FIELD1);
int id = cursor.getInt(1);
String name = cursor.getString(0);
}

I see one possible problem here:
#Override
public int getCount() {
return length-1;
}
You should write return length; because length=mCursor.getCount()
Another issue that you use cursor inside getView and just do moveNext on it.
I think it is not good idea because fetching data isn't quick process. So it cause lags on scrolling. Try to read complete dataset to internal list of structures and use it in getView.

Related

ListView onItemLongClick view isSelected always returns False

I have a class that extends ListFragment and uses a SimpleCursorAdapter. I have created 2 buttons that enables the user to select/deselect all in the list and this works fine. There could be 200 items in the list, so if they wanted to only select 190 of them, they could select all 200 then deselect 10.
The ListView uses setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
The problem is that I want the user to be able to individually deselect a row by long pressing the row. I use a setOnItemLongClickListener on the ListView but the view.isSelected is always returning false even when the row is selected.
Does anyone know why this is happening.
I've put log statements in to prove this fact.
I have also had a look around the net and some posts are saying that a possible problem is that I am using SimpleCursorAdapter and that it is too basic a component.
I'm not particularly good with adapters, lists and touch events, so could anyone point me in the right direction?
I suppose the obvious thing to tackle, is why the isSelected method always returns false.
public class CarerListForGroupMessageFragment extends ListFragment {
private static final String TAG = CarerListForGroupMessageFragment.class.getSimpleName();
RROnCallApplication rrOnCallApp;
Cursor cursor;
ListView listView;
MyAdapter myAdapter;
OnCarerForGroupMessageSelectedListener mListener;
EditText etext;
Button resetSearch;
Button selectAll;
Button deselectAll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rrOnCallApp = (RROnCallApplication) getActivity().getApplicationContext();
cursor = getCarerList(null);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragmentcarerlistforgroupmessage, container, false);
}
#SuppressWarnings("deprecation")
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] from = new String[]{DBModel.C_CARER_FIRSTNAME, DBModel.C_CARER_LASTNAME, DBModel.C_CARER_PHONENUMBER};
int[] to = {R.id.carerrowfirstname, R.id.carerrowlastname, R.id.carerrowtelno};
myAdapter = (MyAdapter) new MyAdapter(getActivity(),R.layout.carerrow , cursor, from, to);
setListAdapter(myAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setFastScrollEnabled(true);
getListView().setTextFilterEnabled(true);
selectAll = (Button) getActivity().findViewById(R.id.carerlistselectallgroupmessage);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < cursor.getCount(); i++){
getListView().setItemChecked(i, true);
}
myAdapter.notifyDataSetChanged();
}
});
deselectAll = (Button) getActivity().findViewById(R.id.carerlistdeselectallgroupmessage);
deselectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < cursor.getCount(); i++) {
getListView().setItemChecked(i, false);
}
myAdapter.notifyDataSetChanged();
}
});
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getActivity(), "On long click listener", Toast.LENGTH_LONG).show();
boolean ret = false;
if(! view.isSelected()) {
//row in list is not currently selected, so set it as selected
Log.e(TAG, "row postion " + position + " in list is not currently selected");
view.setSelected(true);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);
getListView().setItemChecked(position, true);
myAdapter.notifyDataSetChanged();
ret = true;
} else {
Log.e(TAG, "row " + position + " in list is currently selected");
view.setSelected(false);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, true);
getListView().setItemChecked(position, false);
myAdapter.notifyDataSetChanged();
ret = true;
}
return ret;
}
});
} // End of onActivityCreated
// Container Activity must implement this interface
public interface OnCarerForGroupMessageSelectedListener {
public void onCarerForGroupMessageSelected(String carerId, String carerFirstName, String carerLastName, String carerTelNo ,boolean longClick);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnCarerForGroupMessageSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnCarerForGroupMessageSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.e(TAG, "in onListItemClick");
v.setSelected(true);
//v.setBackgroundColor(Color.parseColor("#FF0000"));
TextView carerName = (TextView) getView().findViewById(R.id.textviewcarername);
Cursor cursor = (Cursor) getListAdapter().getItem(position);
String carerID = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_ID));
String carerFirstName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_FIRSTNAME));
String carerLastName = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_LASTNAME));
String carerTelNo = cursor.getString(cursor.getColumnIndex(DBModel.C_CARER_PHONENUMBER));
Log.e(TAG, "carerID = " + carerID);
mListener.onCarerForGroupMessageSelected(carerID, carerFirstName, carerLastName, carerTelNo, false);
getListView().setItemChecked(position, true);
myAdapter.notifyDataSetChanged();
}
private class MyAdapter extends SimpleCursorAdapter {
#SuppressWarnings("deprecation")
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
}
#Override
public
View getView(int position, View convertView, ViewGroup parent) {
Log.e(TAG, "inside myadapter getview");
View v = super.getView(position, convertView, parent);
if(v == null)
return null;
Log.e(TAG, "clicked the listview!");
//Cursor c = (Cursor)getItem(position);
// String tagScanTime = c.getString(c.getColumnIndex(LoginValidate.C_TAG_SCAN_TIME));
// ((TextView)v.findViewById(R.id.rowcarername)).setText(name + " signed " + status +" at ");
return v;
}
}} //end of CarerListFragment
[EDIT 1]
DBModel class
public class DBModel {
private static final String TAG = DBModel.class.getSimpleName();
// table carer column names
public static final String C_CARER_ID_INDEX = BaseColumns._ID;
public static final String C_CARER_ID = "carerid";
public static final String C_CARER_FIRSTNAME = "carerfirstname";
public static final String C_CARER_LASTNAME = "carerlastname";
public static final String C_CARER_PHONENUMBER = "carerphonenumber";
public static final String C_CARER_EMAIL = "careremail";
Context context;
DBHelper dbhelper;
RROnCallApplication rrOnCallApplication;
public DBModel(Context context) {
this.context = context;
dbhelper = new DBHelper();
rrOnCallApplication = (RROnCallApplication) context.getApplicationContext();
}
/**
* inner class to create/open/upgrade database
*
* #author matt
*
*/
private class DBHelper extends SQLiteOpenHelper {
// database name and version number
public static final String DB_NAME = "roadrunneroncall.db";
public static final int DB_VERSION = 3;
// table names
public static final String TABLECARER = "carer";
public DBHelper() {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG, "SQLiteOpenHelper oncreate ");
String sqlToCreateCarerTable = String
.format("create table %s ( %s INTEGER primary key, %s TEXT, %s TEXT, %s TEXT, %s TEXT, %s TEXT)",
TABLECARER, C_CARER_ID_INDEX, C_CARER_ID, C_CARER_FIRSTNAME,
C_CARER_LASTNAME, C_CARER_PHONENUMBER, C_CARER_EMAIL);
db.execSQL(sqlToCreateCarerTable);
Log.e(TAG, "oncreate " + sqlToCreateCarerTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}//end of onUpgrade
}//end of DBHelper
public SQLiteDatabase getDB(){
return dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
}
public void deleteTableCarer() {
// open database
SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
// delete contents of table
db.delete(DBHelper.TABLECARER, null, null);
// close database
// db.close();
}
public void insertIntoCarer(ContentValues cv) {
SQLiteDatabase db = dbhelper.getWritableDatabase(RROnCallApplication.getSecretKey().toString());
db.insertWithOnConflict(DBHelper.TABLECARER, null, cv, SQLiteDatabase.CONFLICT_REPLACE);
// db.close();
}
public Cursor queryAllFromCarer() {
// open database
SQLiteDatabase db = dbhelper.getReadableDatabase(RROnCallApplication.getSecretKey().toString());
return db.query(DBHelper.TABLECARER, null, null, null, null, null, null);
}
Please check this code.
if(!getListView().isItemChecked(position))
instead of
if(! view.isSelected())
And keep boolean flag value inside DBModel class.

Data not being inserted in Table on Button Press

When I tap the button for inserting the data it says it is successful, but when I check my listview there is no data. But If I add again, then only the data is inserted.
Why is the data only inserted on the second time?
Thanks in advance! :D
This is my Database Helper class:
public static final String DB_NAME = "CartDB";
public static final String TABLE_NAME = "Orders";
public static final String COLUMN_ID = "id";
public static final String NAME ="name";
public static final String SIZE ="size";
public static final String QUANTITY ="quantity";
private static final int DB_VERSION = 1;
public cartDatabaseHelper(Context context)
{
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ NAME + " VARCHAR, "
+ SIZE + " VARCHAR, "
+ QUANTITY + " VARCHAR);";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXIST Orders";
db.execSQL(sql);
onCreate(db);
}
public boolean addPerson(String name, String size, String quantity){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SIZE,size);
contentValues.put(QUANTITY,quantity);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getListContents(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
And this is my MainActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alcohol_list);
db = new cartDatabaseHelper(this);
GridAlcoholAdapter adapter = new GridAlcoholAdapter(alcoholType.this, images, names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = names.get(position);
String size = textSize.getText().toString().trim();
String quantityNumber = textQuantityNumber.getText().toString().trim();
String bottleCase = textBottleCase.getText().toString().trim();
String bottleCaseQuantity = textQuantity.getText().toString().trim();
textQuantity.setText(quantityNumber + " " + bottleCase);
db.addPerson(name,size,bottleCaseQuantity);
dialog.dismiss();
}
});
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_cart:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.cartdialog);
dialog.setTitle("YOUR CART");
listView = (ListView) dialog.findViewById(R.id.listView);
final ListCartAdapter adapter = new ListCartAdapter(alcoholType.this, orderName, orderSize, orderQuantity);
listView.setAdapter(adapter);
Cursor data = db.getListContents();
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
data.close();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
orderName.clear();
orderSize.clear();
orderQuantity.clear();
}
});
dialog.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is my Adapter Class:
public class ListCartAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> orderName;
private ArrayList<String> orderSize;
private ArrayList<String> orderQuantity;
public ListCartAdapter(Context context, ArrayList<String> orderName, ArrayList<String> orderSize, ArrayList<String> orderQuantity){
// public ListCartAdapter(Context context, ArrayList<String> orderName){
this.context = context;
this.orderName = orderName;
this.orderSize = orderSize;
this.orderQuantity = orderQuantity;
}
#Override
public int getCount() {
return orderName.size();
}
#Override
public Object getItem(int position) {
return orderName.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listView;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listView = inflater.inflate(R.layout.cart_list_item, null);
TextView name = (TextView) listView.findViewById(R.id.textOrderName);
TextView size = (TextView) listView.findViewById(R.id.textOrderSize);
TextView quantity = (TextView) listView.findViewById(R.id.textOrderQuantity);
name.setText(orderName.get(position));
size.setText(orderSize.get(position));
quantity.setText(orderQuantity.get(position));
return listView;
}
Why is the data only inserted on the second time?
The problem is in your while loop. When there is only one order then your while loop body will not be executed because you have used data.moveToNext() as condition. If your order count more than one, only then it will enter into the while loop.
ERROR:
data.moveToFirst();
while (data.moveToNext()) {
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
}
SOLUTION:
if(data.moveToFirst())
{
do
{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while(data.moveToNext());
}
Hope this will help~
this is happening because you are adding data to orderName,orderSize and orderQuantity after setting adapter to listView. and you are not even calling
adapter.notifyDataSetChanged();
to let the adapter know that dataSet has changed
The problem is that the adapter doesn't know that you have added an element to the database.
After:
db.addPerson(name,size,bottleCaseQuantity);
you should make
adapter.notifyDataSetChanged()
Well guys I fixed the problem
I made a do-while in retrieving the data and it works!
do{
orderName.add(data.getString(1));
orderSize.add(data.getString(2));
orderQuantity.add(data.getString(3));
} while (data.moveToNext());
thanks again to anyone who wanted and helped :D

android: how to get all folders with names

Hi can somebody help me with my code?? I have a class which should show me folders on my SD card+ folders name, but all folders have same name, but each should have different. How can i implement it??
public class ThumbnailAdapter extends BaseAdapter {
// Context required for performing queries
private final Context mContext;
// Cursor for thumbnails
private final Cursor cursor;
private final int count;
String bucket;
String id;
public ThumbnailAdapter(Context c) {
this.mContext = c;
// Get list of all images, sorted by last taken first
final String[] projection = {
MediaStore.Images.Media.BUCKET_ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME
};
String BUCKET_GROUP_BY =
"1) GROUP BY 1,(2";
String BUCKET_ORDER_BY = "MAX(datetaken) DESC";
cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
BUCKET_GROUP_BY,
null,
BUCKET_ORDER_BY
);
if (cursor.moveToFirst()) {
int bucketColumn = cursor.getColumnIndex(
MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int idColumn = cursor.getColumnIndex(
MediaStore.Images.Media.BUCKET_ID);
do {
// Get the field values
bucket = cursor.getString(bucketColumn);
id = cursor.getString(idColumn);
} while (cursor.moveToNext());
}
count = cursor.getCount();
Log.d("ThumbnailAdapter", count + " images found");
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout ll = new LinearLayout(mContext);
ImageView imageView = new ImageView(mContext);
TextView mytext = new TextView(mContext);
mytext.setText(bucket);
imageView.setImageResource(R.drawable.your_folder_icon);
ll.addView(imageView);
ll.addView(mytext);
return ll;
}
You are probably not setting your TextView mytext to change the text it displays - try the line:
mytext.setText(projection[position]);
I'm not quite sure how you are indexing your projection String array, but by just providing the right index (using the position variable in the getView() method, you should be able to change the TextView name correctly.

How to getItemID from sqlite with BaseAdapter?

I have sqlite column is defined like this:
public final static String S_ID = "_ID";
public final static String S_PHOTOPATH = "Photopath";
public final static String S_NAME = "Name";
public final static String S_POS = "Pos";
public final static String S_SCORE = "Score";
public final static String S_FIXED = "Fixed";
I'd like to getItemID from a sqlite helper class with a adapter class extends BaseAdapter. Here is my code:
public class Page1ListAdapter extends BaseAdapter {
private LayoutInflater adapterInflater;
public Cursor mCursor;
TagView tag;
public Page1ListAdapter(Context context, Cursor cursor) {
super();
mCursor = cursor;
adapterInflater=LayoutInflater.from(context);
}
#Override
public int getCount() {
return mCursor.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
tag = new TagView();
convertView = adapterInflater.inflate(R.layout.page1listview_item, null);
tag.imgV = (ImageView) convertView.findViewById(R.id.ItemImage);
tag.titleV = (TextView) convertView.findViewById(R.id.ItemTitle);
tag.descriptionV = (TextView) convertView.findViewById(R.id.ItemText);
convertView.setTag(tag);
} else {
tag = (TagView) convertView.getTag();
}
mCursor.moveToPosition(position);
Bitmap bmp = BitmapFactory.decodeFile(mCursor.getString(mCursor.getColumnIndex(DBHelper.S_PHOTOPATH)));
BitmapDrawable bmpDrawable = new BitmapDrawable(getActivity().getResources(), bmp);
tag.imgV.setBackground(bmpDrawable);
tag.titleV.setText(mCursor.getString(mCursor.getColumnIndex(DBHelper.S_NAME)));
tag.descriptionV.setText(mCursor.getString(mCursor.getColumnIndex(DBHelper.S_POS)));
return convertView;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
Log.i("mCursor.getCount() --->", String.valueOf(mCursor.getCount()));
mCursor.move(position);
long id = mCursor.getLong(0); // <--- error here
return id;
}
public void setTag (Drawable dwb, String title, String description) {
tag.imgV.setBackground(dwb);
tag.titleV.setText(title);
tag.descriptionV.setText(description);
}
}
However, the getItemID() always get error or wrong ID.
How could I get the _ID column value with cursor?
Thanks in advance!
Cursor.move() moves the cursor by relative amount. You want an absolute position, use moveToPosition() instead.
First initialize database obj like below
SQLiteDatabase db = myDb.getReadableDatabase();
Put your parameter names into query.But I inserted it.
try{
Cursor cursor=db.query(DB_helper.YourTableName, new String[] {"_ID","Photopath","Name","Pos","Score","Fixed"}, null,null, null, null, null);
if(cursor.getCount()>0){
cursor.moveToFirst();
do{
//cursor.getString(0); Means get String from first column(_ID)
USER_ID =cursor.getString(0);
USERNAME=cursor.getString(3);
USERTYPE=cursor.getString(5);
PLANTID =cursor.getString(4);
}while (cursor.moveToNext());
cursor.close();
db.close();
}
}catch(Exception e){
e.printStackTrace();
}
You can store it values into String on into array list and use it anywhere.
Thanks

How to display database content on android Listview?

I am working on a contact book like application.I have a database and,I want to display the data in ListView. Can anybody tell me how to achieve this? Below is what I have tried so far,
public class Contacts {
private int id;
private String name;
private String phone_number;
private String email;
public Contacts()
{
}
public Contacts(int id, String name, String phone_number, String email)
{
this.id = id;
this.name = name;
this.phone_number = phone_number;
this.email = email;
}
public Contacts(String name, String phone_number, String email)
{
this.name = name;
this.phone_number = phone_number;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "ContactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_EMAIL = "email";
public DatabaseHandler(Context context) {
super( context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
public void insertContact(Contacts contacts)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, contacts.getName()); // Contact Name
cv.put(KEY_PH_NO, contacts.getPhone_number()); // Contact Phone
cv.put(KEY_EMAIL, contacts.getEmail()); //Contact Email
// Inserting Row
db.insert(TABLE_CONTACTS, null, cv);
db.close();
}
// Getting All Contacts
public List<Contacts> getAllContacts()
{
List<Contacts> contactList = new ArrayList<Contacts>();
// 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 {
Contacts contact = new Contacts();
//contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhone_number(cursor.getString(2));
contact.setEmail(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
}
while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
public class View_data extends ListActivity {
DatabaseHandler db = new DatabaseHandler(this);
Cursor c ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
db.getWritableDatabase();
List<Contacts> values = db.getAllContacts();
ArrayAdapter<Contacts> adapter = new ArrayAdapter<Contacts>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_data, menu);
return true;
}
}
In View_data class i tried to display the data but couldn't do it.
Any Suggestion will be highly appreciated.
You have to pass the context ,your list item layout and cursor in the Custom adapter.........
final CustomAdapter adapter = new CustomAdapter(MainActivity.this,
R.layout.listitem, cursor);
list.setAdapter(adapter);
then this is how CustomAdapter class is implemented in which you have to override your bindView method. This will look complex until you study it and then try to do it yourself.
public class CustomAdapter extends CursorAdapter {
// Cursor cursor;
Context context;
public CustomAdapter(Context context, int RId, Cursor cursor) {
super(context, cursor);
// this.cursor = cursor;
this.context = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView team1 = (TextView) view.findViewById(R.id.listitem_team1);
team1.setText(cursor.getString(10));
TextView team2 = (TextView) view.findViewById(R.id.listitem_team2);
team2.setText(cursor.getString(11));
TextView date = (TextView) view.findViewById(R.id.listitem_date);
date.setText(cursor.getString(3));
TextView city = (TextView) view.findViewById(R.id.listitem_city);
city.setText(cursor.getString(2));
TextView time = (TextView) view.findViewById(R.id.listitem_time);
time.setText(cursor.getString(4));
TextView ground = (TextView) view.findViewById(R.id.listitem_ground);
date.setText(cursor.getString(1));}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
return v;
}
}
you can also refer to this link http://dj-android.blogspot.in/2012/10/android-show-data-from-sqlite-db-into.html
You have to pass the data to the UserAdapter.The code
List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase); is used to retrive data from SQL database which are applied to the variable data. Try this method.
List<DataProvider> data = userDbHelper.getInformation(sqLiteDatabase);
UsersAdapter adapter = new UsersAdapter(this, (ArrayList<DataProvider>) data);
list.setAdapter(adapter);
Then UserAdapter class implentation is given below which extends the ArrayAdapter..
public class UsersAdapter extends ArrayAdapter<DataProvider> {
private static class ViewHolder {
TextView id;
TextView name;
TextView number;
}
public UsersAdapter(Context context, ArrayList<DataProvider> users) {
super(context, R.layout.new_layout, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
// User user = getItem(position);
DataProvider dataProvider = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.new_layout, parent, false);
viewHolder.id = (TextView)convertView.findViewById(R.id.textId);
viewHolder.name = (TextView) convertView.findViewById(R.id.textname);
viewHolder.number = (TextView) convertView.findViewById(R.id.textnumber);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data from the data object via the viewHolder object
// into the template view.
viewHolder.id.setText(dataProvider.getId());
viewHolder.name.setText(dataProvider.getName());
viewHolder.number.setText(dataProvider.getMob());
// Return the completed view to render on screen
return convertView;
}
}
The above code is UserAdapter which extends the ArrayAdapter.Try this method you will get the solution.
You can also refer this link https://github.com/codepath/android_guides/wiki/using-an-arrayadapter-with-listview

Categories

Resources