ListView alphabetically arrange? - android

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.

Related

Android: fill list view with data from sqlite

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.

Same data displaying in Listview using custom adapterview from the sqlite

i am having error in getting user details in sqlite.
i want to display the these three user details by searching the data base but it showing the same user details three times not three different user details.
Here is my code
Cursor c= mydatabase.query(true, TABLENAME_1, new String[] { KEY_Name,
KEY_CellPhoneNumber,KEY_CompanyName,KEY_Email_id }, KEY_Name + " LIKE ?",
new String[] {"%"+ name+ "%" }, null, null, null,
null);
i am retriving the details in the AsynchTask and in doingBackGround is in which i am having problem with loop please any body solve it..
DataHelper databasehelper = new DataHelper(Search.this);
databasehelper.open();
Cursor c= databasehelper.getAllCustomerDetailsByName(_name);
if(c!=null && c.getCount()>0) {
int nam = c.getColumnIndex(KEY_Name);
int cellnumber = c.getColumnIndex(KEY_CellPhoneNumber);
int company = c.getColumnIndex(KEY_CompanyName);
int emailid = c.getColumnIndex(KEY_Email_id);
flag_data = true;
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
searchmodel.setName(c.getString(nam));
searchmodel.setCellphone(c.getString(cellnumber));
searchmodel.setCompany(c.getString(company));
searchmodel.setEmailid(c.getString(emailid));
Log.i("Search", searchmodel.getName());
Log.i("Search", searchmodel.getCellphone());
Log.i("Search", searchmodel.getCompany());
Log.i("Search", searchmodel.getEmailid());
for (int i = 0; i < c.getCount();i++) {
customerSearch.add(i,searchmodel);
Log.i("index", ""+i);
}
}
}
my customer adapter class is
public class CustomerSearchAdapter extends BaseAdapter {
private ArrayList<CustomerSearchModel> customerSearchData;
private LayoutInflater layoutInflater;
private Context _context;
public CustomerSearchAdapter(Context context,
ArrayList<CustomerSearchModel> listData) {
this.customerSearchData = listData;
_context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return customerSearchData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return customerSearchData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (layoutInflater == null)
layoutInflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.custom_user_details,
null);
holder = new ViewHolder();
holder.customer_user_name = (TextView) convertView
.findViewById(R.id.user_name);
holder.customer_company_name = (TextView) convertView
.findViewById(R.id.company_name);
holder.customer_phone_number = (TextView) convertView
.findViewById(R.id.phone_number);
holder.customer_emailid_number = (TextView) convertView
.findViewById(R.id.emailid_number);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final CustomerSearchModel customDetailItem = (CustomerSearchModel) customerSearchData
.get(position);
holder.customer_user_name.setText(customDetailItem.getName());
holder.customer_company_name.setText(customDetailItem.getCompany());
holder.customer_phone_number.setText(customDetailItem.getCellphone());
holder.customer_emailid_number.setText(customDetailItem.getEmailid());
return convertView;
}
static class ViewHolder {
TextView customer_user_name;
TextView customer_company_name;
TextView customer_phone_number;
TextView customer_emailid_number;
}
}
You are using searchmodel variable globally. you need to create new object of Searchmodel each time in for loop.
Remove searchmodel global variable.
I assume name of class is Searchmodel then you can try this:
DataHelper databasehelper = new DataHelper(Search.this);
databasehelper.open();
Cursor c= databasehelper.getAllCustomerDetailsByName(_name);
if(c!=null && c.getCount()>0) {
int nam = c.getColumnIndex(KEY_Name);
int cellnumber = c.getColumnIndex(KEY_CellPhoneNumber);
int company = c.getColumnIndex(KEY_CompanyName);
int emailid = c.getColumnIndex(KEY_Email_id);
flag_data = true;
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
Searchmodel searchmodel = new Searchmodel();
searchmodel.setName(c.getString(nam));
searchmodel.setCellphone(c.getString(cellnumber));
searchmodel.setCompany(c.getString(company));
searchmodel.setEmailid(c.getString(emailid));
Log.i("Search", searchmodel.getName());
Log.i("Search", searchmodel.getCellphone());
Log.i("Search", searchmodel.getCompany());
Log.i("Search", searchmodel.getEmailid());
for (int i = 0; i < c.getCount();i++) {
customerSearch.add(i,searchmodel);
Log.i("index", ""+i);
}
}
}

Retrieve Data from the database and set in custom listview

Retrieve Data from the database and set in custom listview but only show the last data from DB in list view.
this is my code please solve my problem.
SQLiteDatabase myDb = openOrCreateDatabase(DB_Name,Context.MODE_PRIVATE, null);
try {
c=myDb.rawQuery("select sid,name,num from Contact", null);
if (c.moveToFirst()) {
do {
name1=c.getString(c.getColumnIndex("name")).toString();
num1=c.getString(c.getColumnIndex("num")).toString();
Log.d("string is",name1+num1);
}
while (c.moveToNext());
}
valnumber.add(name1+"<<"+num1+">>");
custlistAdapter = new CustListview(Contact.this, R.layout.custlistview,valnumber);
ShowCont.setAdapter(custlistAdapter);
myDb.close();
CustListview.java
public class CustListview extends ArrayAdapter {
private final Activity context;
private final ArrayList<String> web;
int layoutResourceId;
public CustListview(Activity context,int custlistview, List<String> val)
{
super(context, R.layout.custlistview, val);
this.context = context;
this.web = (ArrayList<String>) val;
}
#Override
public View getView(int position, View Convertview, ViewGroup parent) {
View row=Convertview;
UserHolder holder = null;
if(row==null)
{
LayoutInflater inflater=((Activity)context).getLayoutInflater();
row=inflater.inflate(R.layout.custlistview, null, true);
holder=new UserHolder();
holder.imgdelete=(Button)row.findViewById(R.id.imagedelete);
holder.txtTitle = (TextView) row.findViewById(R.id.txt);
//LayoutInflater inflater = context.getLayoutInflater();
//View rowView= inflater.inflate(R.layout.custlistview, null, true);
row.setTag(holder);
}
else
{
holder=(UserHolder)row.getTag();
}
holder.txtTitle.setText(web.toString());
holder.imgdelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), "delete", Toast.LENGTH_LONG).show();
}});
return row;
}
static class UserHolder {
TextView txtTitle;
Button imgdelete;
}}
Try somthing like that
cursor = sqldb.query("Contact", null, null, null, null, null, "sid");
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
name1=cursor.getString(cursor.getColumnIndex("name"));
num1=cursor.getString(cursor.getColumnIndex("num"));
Log.d("string is",name1+num1);
} while (cursor.moveToNext());
}
}
cursor.close();
Did you check how many names and number you are getting from the database.
Your code was only adding one row in the array which you have to move inside the while loop.
SQLiteDatabase myDb = openOrCreateDatabase(DB_Name,Context.MODE_PRIVATE, null);
try {
c=myDb.rawQuery("select sid,name,num from Contact", null);
if (c.moveToFirst()) {
do {
name1=c.getString(c.getColumnIndex("name"));
num1=c.getString(c.getColumnIndex("num"));
Log.d("string is",name1+num1);
valnumber.add(name1+"<<"+num1+">>");
}
while (c.moveToNext());
}
custlistAdapter = new CustListview(Contact.this, R.layout.custlistview,valnumber);
ShowCont.setAdapter(custlistAdapter);
myDb.close();

gridview didn't work second times

i have a gridview like a listview. It work correctly first run, but when press back and return the activity that have gridView, get some errors...
logCat: android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed. # Open Cursors=761 (# cursors opened by this proc=761)
i look at question like that, solution is always about cursor. I close cursor, when populate items info.. but it didnt work...
my gridView code:
private void refreshList(String sql)
{
gridArray = new ArrayList<Stock>();
final Cursor cursor = _SQLite.RawQueryTry(sql, null);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
if (cursor != null)
{
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
String stockName = cursor.getString(cursor.getColumnIndex("STOK_ADI"));
String stockNo = cursor.getString(cursor.getColumnIndex("STOK_NO"));
String stockCode = cursor.getString(cursor.getColumnIndex("STOK_KODU"));
String stockEntity = cursor.getString(cursor.getColumnIndex("BIRIM"));
String stockKdvOranı = cursor.getString(cursor.getColumnIndex("KDV_ORANI"));
String stockRatio = TableUtils.getFieldValue("KATSAYI", "BIRIM", stockEntity, "STOKBIRI");
String stockAmount = cursor.getString(cursor.getColumnIndex("MIKTAR"));
gridArray.add(new Stock(stockName, stockNo, stockCode, stockKdvOranı, stockEntity, stockAmount, stockRatio, processNo));
cursor.moveToNext();
}
}
}
cursor.close();
gridAdapter = new AdapterStockGridListView(this, R.layout.stockgridlistitems, gridArray);
gridView.setAdapter(gridAdapter);
}
my adapter class is here:
public class AdapterStockGridListView extends ArrayAdapter<Stock>
{
Context context;
int id;
ArrayList<Stock> stock = new ArrayList<Stock>();
public AdapterStockGridListView(Context context, int id, ArrayList<Stock> stock)
{
super(context, id, stock);
this.id = id;
this.context = context;
this.stock = stock;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
RecordHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(id, parent, false);
holder = new RecordHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.stockName);
holder.txtStockNo = (TextView) row.findViewById(R.id.stockNo);
holder.txtStockCode = (TextView) row.findViewById(R.id.stockCode);
row.setTag(holder);
}
else
{
holder = (RecordHolder) row.getTag();
}
Stock item = stock.get(position);
holder.txtTitle.setText(item.getStockName());
holder.txtStockNo.setText(item.getStockNo());
holder.txtStockCode.setText(item.getStockCode());
return row;
}
}
static class RecordHolder
{
TextView txtTitle;
TextView txtStockNo;
TextView txtStockCode;
}
This is because you are trying to access closed cursor. So remove this line
cursor.close();
And to manage cursor properly write this line in your activity or fragment
In Activity
startManagingCursor(pass Your Cursor object here);
In Fragment
getActivity().startManagingCursor(pass Your Cursor object here);
override this method in adapter class and also print the size of array may be it has only one vale
#Override
public int getCount() {
return stock.size();
}

not getting resource id of images in my code

I am trying to make a custom list view with Imageviews in each row that would set their image resource through a string i get from database. The database only contains the name of the images and I need to load it from resources. I've tried all the methods to get resource by name but the function always returns 0. I cannot get my id based on name no matter what I do. This is the Custom adapter that I am using....
public class OwnAddptor extends BaseAdapter {
private LayoutInflater mInflater;
String[] names;
String[] detailarray;
String[] adapimage;
int size;
Context mycont;
public OwnAddptor(Context context,String[] poi_names,String[] details,String[] imageadap) {
mInflater = LayoutInflater.from(context);
this.names = poi_names;
this.detailarray = details;
this.adapimage = imageadap;
this.mycont = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return names.length;
}
#Override
public Object getItem(int puhj) {
// TODO Auto-generated method stub
return puhj;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if (vi == null) {
vi = mInflater.inflate(R.layout.blockview, null);
holder = new ViewHolder();
holder.headline = (TextView) vi.findViewById(R.id.head_line);
holder.detail = (TextView) vi.findViewById(R.id.detail);
holder.image = (ImageView) vi.findViewById(R.id.image);
vi.setTag(holder);
}
else {
holder = (ViewHolder) vi.getTag();
}
holder.headline.setText(names[position]);
holder.detail.setText(detailarray[position]);
// Drawable imgdraw = mycont.getResources().getDrawable(adapimage[position]);
holder.image.setImageDrawable(getAndroidDrawable(adapimage[position], mycont));
System.out.println(adapimage[position]);
return vi;
}
static class ViewHolder {
TextView headline;
TextView detail;
ImageView image;
}
public int getImageId(Context context, String name) {
System.out.println("current name"+name);
return context.getResources().getIdentifier("drawable/"+name, null, context.getPackageName());
}
static public Drawable getAndroidDrawable(String pDrawableName,Context cont){
int resourceId=Resources.getSystem().getIdentifier(pDrawableName, "drawable", cont.getPackageName());
System.out.println("resource ids****"+resourceId);
if(resourceId==0){
return null;
} else {
return Resources.getSystem().getDrawable(resourceId);
}
}
}
And this is the main activity where I query the database and pass the array to the custom adapter class. The text views set correctly according to the position. The only problem is in getting the int id of the images from the resource folder.
public class MainActivity extends Activity {
DataBaseHelper baseHelper ;
SQLiteDatabase database;
OwnAddptor adapcustom;
TextView detail;
ListView view;
TextView headline;
String[] name;
String[] images;
String[] desc;
int[] imgids;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<RowItem> rowItems;
view = (ListView) findViewById(R.id.mylist);
baseHelper = new DataBaseHelper(this);
try
{
baseHelper.createDatabase();
}
catch (IOException ioe)
{
throw new Error("Unable to create database");
}
try
{
baseHelper.openDataBase();
}
catch(SQLException sqle)
{
throw sqle;
}
database = baseHelper.getReadableDatabase();
Cursor cursor= database.rawQuery("Select * from tblArpoi_local", null);
int i = 0;
if (cursor.getCount()>0) {
cursor.moveToFirst();
name = new String[cursor.getCount()];
desc = new String[cursor.getCount()];
images= new String[cursor.getCount()];
imgids = new int[cursor.getCount()];
while (cursor.moveToNext()) {
images[i]= "poi_"+cursor.getString(cursor.getColumnIndex("arPoiImageLink"));
name[i] = cursor.getString(cursor.getColumnIndex("arPoiName"));
desc[i] = cursor.getString(cursor.getColumnIndex("arPoiDescription"));
i++;
}
System.out.println("****"+images.length);
database.close();
cursor.close();
adapcustom = new OwnAddptor(this,name,desc,images);
view.setAdapter(adapcustom);
}
}
public static int getImageId(Context context, String name) {
System.out.println("current name"+name);
return context.getResources().getIdentifier("drawable/"+name, null, context.getPackageName());
}
}
Try with this it will solve your problem.
ImageView my_image = (ImageView) findViewById(R.id.my_imageView);
my_image.setBackgroundResource(getResId("ic_launcher"));
Declare following function to get Drawable Resource Id from the passed drawable string name.
public static int getResId(String drawableName) {
try {
Class res = R.drawable.class;
Field field = res.getField(drawableName);
int drawableId = field.getInt(null);
System.out.println("resource ids****"+drawableId);
return drawableId;
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
return 0;
}
}
That's It.
Hope it helps you.
Thanks.
I use this
context.getResources().getIdentifier(drawableResourceName, "drawable", context.getPackageName());
and it works like a sharm.
you could try to call
holder.image.setImageDrawable(context.getResources().getIdentifier(drawableResourceName, "drawable", context.getPackageName()));
instead of
holder.image.setImageDrawable(getAndroidDrawable(adapimage[position], mycont));
hope this help

Categories

Resources