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
Related
Overview: The programme I'm now trying to make has the following steps.
get the input data from users and store them in the SQLite database.
Fill the list view with the data retrieved from the database.
In order to implement 1, I first created the addNewItem() method as follows.
public void addNewPost(Post post) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// get the variables which are to be put into the database row.
String uploader = post.getUploader();
String content = post.getContent();
String privacy_level = post.getPrivacyLevel();
String uploaded_at = post.getUploadedAt();
String edited_at = post.getEditedAt();
values.put(KEY_UPLOADER, uploader);
values.put(KEY_CONTENT, content);
values.put(KEY_PRIVACY_LEVEL, privacy_level);
values.put(KEY_UPLOADED_AT, uploaded_at);
values.put(KEY_EDITED_AT, edited_at);
db.insert(TABLE_POST, null, values);
db.close();
}
And for 2, I created another method called initListView().
private void initListView() {
SQLiteDatabase db = sqliteHandler.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + SQLiteHandler.TABLE_POST, null);
username.clear();
uploaded_at.clear();
content.clear();
if(cursor.moveToFirst()) {
do {
username.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADER)));
uploaded_at.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_UPLOADED_AT)));
content.add(cursor.getString(cursor.getColumnIndex(DataKeyLists.KEY_CONTENT)));
} while(cursor.moveToNext());
}
FeedAdapter adapter = new FeedAdapter(this, username, uploaded_at, content);
listView.setAdapter(adapter);
cursor.close();
}
And finally this is the FeedAdapter class.
public class FeedAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> username;
private ArrayList<String> uploaded_at;
private ArrayList<String> content;
public FeedAdapter(Context context, ArrayList<String> username, ArrayList<String> uploaded_at, ArrayList<String> content) {
this.context = context;
this.username = username;
this.uploaded_at = uploaded_at;
this.content = content;
}
public int getCount() {
return username.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater;
if(convertView == null) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, null);
ImageView ivFeedThumbnail = (ImageView) convertView.findViewById(R.id.ivFeedThumbnail);
TextView tvFeedUsername = (TextView) convertView.findViewById(R.id.tvFeedUsername);
TextView tvFeedUploaded = (TextView) convertView.findViewById(R.id.tvFeedCreated);
TextView tvFeedText = (TextView) convertView.findViewById(R.id.tvFeedText);
TextView tvFeedLikes = (TextView) convertView.findViewById(R.id.tvFeedLikes);
TextView tvFeedComments = (TextView) convertView.findViewById(R.id.tvFeedComments);
Button btnLike = (Button) convertView.findViewById(R.id.btnLike);
Button btnComment = (Button) convertView.findViewById(R.id.btnComment);
tvFeedUsername.setText(username.get(position));
tvFeedUploaded.setText(uploaded_at.get(position));
tvFeedText.setText(content.get(position));
}
return convertView;
}
}
The code seems to have no problem, but when I run the application, the list is still empty.
Any tips for the solution will be very much appreciated.
I am trying to get the _id field from the cursor when an item in my Grid View is clicked, the same code is working fine in a listview but does not seem to work here:
Class level:
CurAdapter Cur;
GridView grid;
onCreate:
Cursor mCur = dbHelper.contactsQuery();
grid = (GridView)rootView.findViewById(R.id.gridview);
Cur = new CurAdapter(getActivity(), mCur,0);
grid.setAdapter(Cur);
grid.setTextFilterEnabled(true);
onCLick:
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
System.out.println(position);
System.out.println(id);
Cursor cursor = (Cursor) grid.getItemAtPosition(position);
}
});
My CustomAdapter:
private class CurAdapter extends CursorAdapter{
public CurAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv = (TextView) view.findViewById(R.id.item_text);
tv.setTypeface(helv_light);
final RoundedImageView iv = (RoundedImageView) view.findViewById(R.id.item_image);
String name = (cursor.getString(cursor.getColumnIndexOrThrow("Name")));
image = cursor.getString(cursor.getColumnIndexOrThrow("imageUri"));
String isAdhoc = (cursor.getString(cursor.getColumnIndexOrThrow("isAdhoc")));
if(isAdhoc.equals("1")){
boolean check = false;
String frName = null;
Cursor mCur = dbHelper.friendsName(name);
if(mCur != null && mCur.moveToFirst()){
do{
frName = mCur.getString(mCur.getColumnIndex("FriendsName"));
if(frName != null){
if(frName.equalsIgnoreCase(selfName)){
check = false;
}else {
check = true;
}
}
}while (mCur.moveToNext());
}
if(check){
name = name+" "+"("+frName+"'s"+" pet)";
}
}
tv.setText(name);
if((image.contains("jpg") || image.contains("png")) && image.contains("adhoc") != true){
image = "file://"+image;
}
final DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.icon_default)
.showImageForEmptyUri(R.drawable.icon_default)
.showImageOnFail(R.drawable.icon_default)
.resetViewBeforeLoading(true)
.cacheInMemory(true) // default
.cacheOnDisk(true) // default
.build();
ImageLoader.getInstance().displayImage(image, iv, options);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.grid_layout, null);
return view;
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return position;
}
}
My Problem:
11-10 14:51:47.989: E/AndroidRuntime(11194): java.lang.ClassCastException: java.lang.Integer cannot be cast to android.database.Cursor
11-10 14:51:47.989: E/AndroidRuntime(11194): at com.example.FragmentTab3$1.onItemClick(FragmentTab3.java:125)
you are getting the ClassCastException because you are overriding getItem
public Object getItem(int position) {
return position;
}
and in your case it is returning an int not the cursor. You can delete it and use the parent implementation of getItem (which should return the Cursor at position)
Exception is due to return int from getItem(..) as mentioned by blackbelt
This may also help you to get ID of the record - change getItemId(..) this way:
public long getItemId(int position) {
mCur.moveToPosition(position);
return mCur.getLong(mCur.getColumnIndex(BaseColumns._ID));
}
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 does my listview automatically display data alphabetically. Because in my emulator it display data arrange by how it arranged in my database.
can anyone have a explanation with this issue?
this is how i retrieve data from my database.
SQLiteDatabase db = openOrCreateDatabase("database", MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT DISTINCT category,cimage from FoodList", null);
int count = c.getCount();
String[] values = new String[count];
String[] values1 = new String[count];
c.moveToFirst();
for(int x = 0; x < count; x++){
values[x] = c.getString(c.getColumnIndex("category"));
values1[x] = c.getString(c.getColumnIndex("cimage"));
c.moveToNext();
}
list.setAdapter(new imageadapter(this,values,values1));
db.close();
c.close();
here is my imageadapter activity
public class imageadapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public final String[] mobileValues2;
public imageadapter(Context context, String[] mobileValues, String[] mobileValues1) {
this.context = context;
this.mobileValues = mobileValues;
this.mobileValues2 = mobileValues1;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
viewHolder holder = new viewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.logo, null);
holder.category = (TextView) convertView.findViewById(R.id.cat);
holder.image = (ImageView) convertView.findViewById(R.id.imglogo);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.category.setText(mobileValues[position]);
holder.s = mobileValues2[position];
byte[] decodedString = null;
try {
decodedString = Base64.decode(holder.s, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.image.setImageBitmap(decodedByte);
return convertView;
}
public int getCount() {
return mobileValues.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
static class viewHolder{
ImageView image;
TextView category;
String s;
}
}
get the data from the database by arranging it in the order you are intersted and next add to the arrayadapter.
This may solve your problem
Are you using any query for getting the information from the database? If so, why don't you use a SQL statement like this:
SELECT * FROM your_table ORDER BY your_column
public Cursor fetchAllData() {
return database.query(urtablename, null, null, null, null, null,
null);
}
it will return all data using cursor,In ur activity
Cursor cr=dba.fetchAllData();
cr.movetofirst();
while(!cr.isAfterLast())
{
//fetch all data using column name
//like cr.getString(cr.getColumnIndex("ur column name"));
//it will return as per in dATABASE
cr.movetoNext();
}
Create a custom comparator as you need. And now Use this in the sort function of ArrayAdapter.
try this in constructor :
public imageadapter(Context context, String[] mobileValues, String[] mobileValues1) {
this.context = context;
this.mobileValues = mobileValues;
this.mobileValues2 = mobileValues1;
Arrays.sort(mobileValues);
//Arrays.sort(mobileValues2);
}
enjoy.
(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.