Android listview arrange alphabetically - android

i have a listview .item in listview come from database . the problem is that the item have not arrange in alphabetically order.help me to solve my problem.this is my listview activity code
this is the code of datalist activity.
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, vitamins;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
vitamins = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, vitamins, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
this is dbhelper class
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null,null);
return cursor;
}
public Cursor getFood(String dish_name,SQLiteDatabase sqLiteDatabase)
{
String[] projections = { Food.NewDishInfo.DISH_QUANTITY, Food.NewDishInfo.DISH_CALORIE, Food.NewDishInfo.DISH_FAT,
Food.NewDishInfo.DISH_PROTEIN, Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
String selection = Food.NewDishInfo.DISH_NAME+" LIKE ?";
String[] selection_args = {dish_name};
Cursor cursor = sqLiteDatabase.query(Food.NewDishInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);
return cursor;
}

You have to add order by to your query:
public Cursor getInformations(SQLiteDatabase db){
Cursor cursor;
String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null, "column_name ASC");
return cursor;
}
public Cursor getFood(String dish_name,SQLiteDatabase sqLiteDatabase)
{
String[] projections = { Food.NewDishInfo.DISH_QUANTITY, Food.NewDishInfo.DISH_CALORIE, Food.NewDishInfo.DISH_FAT,
Food.NewDishInfo.DISH_PROTEIN, Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
String selection = Food.NewDishInfo.DISH_NAME+" LIKE ?";
String[] selection_args = {dish_name};
Cursor cursor = sqLiteDatabase.query(Food.NewDishInfo.TABLE_NAME,projections,selection,selection_args,null,null, "column_name ASC");
return cursor;
}
ASC means ascending and DESC means descending.

Related

How can I select values from a column in sqlite database which will starts with a particular letter inserted by user

I want the following sql code in sqlite terms:
"SELECT * FROM babynames WHERE name like '$id%'"
I get the following erreor
SQLiteLog: (1) near "like": syntax error
My code:
public class Datalist extends ListActivity{
public String id1;
RegistrationAdapter adapter_ob;
DBhandler helper_ob;
SQLiteDatabase db_ob;
ListView nameList;
Cursor cursor;
public ListView listView;
ArrayList<HashMap<String, String>> list = new ArrayList();
private ArrayList<String> results = new ArrayList<String>();
String tableName = DBhandler.TABLE_NAME;
String n=DBhandler.KEY_NAME;
String m=DBhandler.KEY_MEAN;
private SQLiteDatabase newDB;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.list);
id1 = getIntent().getStringExtra(config.TAG_ID);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
// TODO Auto-generated method stub
//TextView tView = new TextView(this);
//tView.setText("This data is retrieved from the database and only 4 " +
//"of the results are displayed");
//getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
// TODO Auto-generated method stub
try {
DBhandler dbHelper = new DBhandler(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT _name, _mean FROM " +
tableName + "where _name like'" +id1+ "%'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
//Integer id=c.getInt(c.getColumnIndex("_id"));
String Name = c.getString(c.getColumnIndex("_name"));
String mean= c.getString(c.getColumnIndex("_mean"));
/* HashMap<String, String> baby = new HashMap();
//baby.put(config.TAG_ID, id);
baby.put(config.TAG_NAME, Name);
baby.put(config.TAG_MEAN1, mean);
list.add(baby);*/
results.add("" + Name + ""
+ "" + mean);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
//listView.setAdapter(new SpecialAdapter(this, list, R.layout.list_item, new String[]{config.TAG_NAME, config.TAG_MEAN1}, new int[]{R.id.name, R.id.mean1}));
}
//listView.setAdapter(new SpecialAdapter(this, list, R.layout.list_item, new String[]{config.TAG_NAME, config.TAG_MEAN1}, new int[]{R.id.name, R.id.mean1}));
}
}
Anybody please help me.Thanks in advance..
Try this...
public Cursor getBabyName(String query) {
return db.query(DbHelper.NAME_TABLE, NAME_FIELDS,
DbHelper.BABY_NAME+ " like '" + query + "%'", null,
null, null, null, null);
}

Android SQLite get value from column

I have a column ShopName, and another column called LocationCode, if the LocationCode equals to "SKP", the corresponding ShopName will be added to an array, my question is, how can I do that?
I got something like this:
public List<String> getQuotes() {
String WhiteFarm = "WhiteFarm";
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE 'LocationCode' = " + WhiteFarm, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
And another class like this:
public class DatabaseGrabber extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_main);
final TextView Shop_name = (TextView)findViewById(R.id.ShopName);
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
final List<String> ShopName = databaseAccess.getQuotes();
databaseAccess.close();
Button StartDraw = (Button)findViewById(R.id.draw_start);
StartDraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(ShopName);
String random = ShopName.get(0);
Shop_name.setText(random);
}
});
}
}
If your LocationCode contains a String (or TEXT for SQLite) type of data then your value should be enclosed in a single quote as shown in the code below:
Cursor cursor = database.rawQuery("SELECT * FROM WhereToEat WHERE LocationCode = " + "'" + WhiteFarm "'", null);

Return String[] From database

I am trying to populate my AutoCompleteTextView from a column of values in my database.
The query I am running in my database is:
// GET MEMOS
public ArrayList<String> autoCompleteMemo(String table)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> memoList = new ArrayList<String>();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
memoList.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
return memoList;
}
And here is how I am attempting to set the values:
memoList = new String[db.autoCompleteMemo(table).size()];
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, memoList);
etMemo.setAdapter(adapter);
For some reason, this does not appear to be working. Am i converting from ArrayList to String[] properly?
Thanks
Also,
If i do something similar to this
String[] memoList = getResources().getStringArray(R.array.memoList);
and populate that in Strings.xml it works fine.
I changed my DB method to the following and it now works
public String[] autoCompleteMemo(String table) {
SQLiteDatabase db = this.getReadableDatabase();
String SQL_GET_MEMOS = "SELECT memo FROM " + table;
Cursor cursor = db.rawQuery(SQL_GET_MEMOS, null);
if (cursor.getCount() > 0) {
String[] str = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
str[i] = cursor.getString(cursor.getColumnIndex("memo"));
i++;
}
return str;
}
else {
return new String[] {};
}
}

Null Pointer Exception while Retriving Data from Sqlite

I am retrieving data from sqlite to base adapter by cursor.
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
String[] v0 = new String[] { tes0 };
String[] v01 = new String[] { tes1 };
String[] v02 = new String[] { tes2 };
String[] v03 = new String[] { tes3 };
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}
Then, Adapter_listView.java
public class Adapter_ListView extends BaseAdapter {
private int count;
private Context context;
private String[] string1;
private String[] string2;
private String[] string3;
private String con1;
private String con2;
private String con3;
public Adapter_ListView(Context baseContext, String[] v01, String[] v02, String[] v03, int theTotal) {
this.count = theTotal;
this.context = baseContext;
this.string1 = v01;
this.string2 = v02;
this.string3 = v03;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View contentView, ViewGroup arg2) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
contentView = inflater.inflate(R.layout.layout_inflate_list2, null);
TextView title = (TextView)contentView.findViewById(R.id.inflate_title);
TextView body = (TextView)contentView.findViewById(R.id.inflate_body);
TextView sub = (TextView)contentView.findViewById(R.id.inflate_sub);
title.setText(string1[position]);
body.setText(string2[position]);
sub.setText(string3[position]);
return contentView;
}
}
from this code always error --> ArrayOuOfBound if execute this code
title.setText(string1[position]);
how i can solve it?
You need to open your database in the activity you retrieve or insert data into your SQLite database. Also make sure you close it when your finished.
final DatabaseHelper m = new DatabaseHelper(this);
m.open();
In your onDestroy or pause. Call
m.close();
This may be the issue, because i dont see where you open your database in the code.
EDIT :
In your DatabaseHelper class. Create a method.
public void open(){
db.open();
}
public void close(){
db.close()
}
Then you will have the method to close and open the database in your activities where you need to insert and retrieve information.
To retrive data from cursor, first you must go to first row data in cursor.
Some code like this:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
...
}
good luck!! :D
It seems you want to load resultset into list, if so please change your code to set adapter outside of loop:
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
int theTotal=c.getCount();
String[] v0 = new String[theTotal];
String[] v01 = new String[theTotal];
String[] v02 = new String[theTotal];
String[] v03 = new String[theTotal];
int i=0;
if (c!=null) c.moveToFirst();
while (c.moveToNext()) {
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i] =tes0 ;
v01[i] = tes1 ;
v02[i] = tes2 ;
v03[i] = tes3 ;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),
v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
Try this:
main.java
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c=db.rawQuery("select * from budget",null);
if(c.getCount()>0)
{
int i=0;
int clength=c.getCount();
String[] v0=new String[clength];
String[] v1=new String[clength];
String[] v2=new String[clength];
String[] v3=new String[clength];
while (c.moveToNext())
{
String tes0 = Integer.toString(c.getInt(c.getColumnIndex("_id")));
String tes1 = Double.toString(c.getDouble(c.getColumnIndex("material_actual")));
tes2 = c.getString(c.getColumnIndex("start_date"));
tes3 = c.getString(c.getColumnIndex("end_date"));
v0[i]=tes0;
v01[i]=tes1;
v01[i]=tes2;
v01[i]=tes3;
i++;
}
Adapter_ListView adapter = new Adapter_ListView(getBaseContext(),v01, v02 , v03, theTotal); //string[]
TaskList.setAdapter(adapter);
}

Fetching row columns into edit texts, row id in textview

I have a page with a number edit texts, i want to populate these with columns of a raw with the row id equaling a textview value... this is what i have so far in the edit text page.
public class CBCreate extends Activity {
EditText EditRecipe,EditRecipe2,EditRecipe3;
Button Rname;
CBDataBaseHelper entry;
TextView RowIDText;
Cursor c;
String name;
String category;
String description;
//final String SQL_STATEMENT = "SELECT Recipe_Name, Recipe_Category, Recipe_Description FROM RecipeData WHERE _id = " + RowIDText ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create); // sets the content view to main
EditRecipe = (EditText) findViewById(R.id.editText1);
EditRecipe2 = (EditText) findViewById(R.id.editText2);
EditRecipe3 = (EditText) findViewById(R.id.editText3);
RowIDText = (TextView) findViewById(R.id.RowID);
Rname = (Button) findViewById(R.id.RecipeName);
String RowID;
try{
Bundle extras = getIntent().getExtras();
if (extras != null) {
RowID = extras.getString("SELECTED");
RowIDText.setText(RowID);
}
if (RowIDText != null){
entry = new CBDataBaseHelper(this);
String s = RowIDText.getText().toString();
int ID = Integer.parseInt(s);
entry.open();
Cursor cursor = entry.fetchRow(ID);
if (cursor.moveToFirst()){ // data?
name = cursor.getString(cursor.getColumnIndex(CBDataBaseHelper.KEY_NAME));
}
entry.close();
EditRecipe.setText(name);
EditRecipe2.setText(category);
EditRecipe3.setText(description);
}
}catch (Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("darn");
TextView tv = new TextView(this);
tv.setText(name);
d.setContentView(tv);
d.show();
}
}
public void doIt(View view) {
String Name = EditRecipe.getText().toString();
String description = EditRecipe.getText().toString();
String category = EditRecipe.getText().toString();
entry = new CBDataBaseHelper(CBCreate.this);
entry.open();
entry.createEntry(Name, description, category);
entry.close();
EditRecipe.setText("");
EditRecipe2.setText("");
EditRecipe3.setText("");
}
public void goBack(View view){
Intent myIntent = new Intent(this, CBFilter.class);
startActivity(myIntent);
}
}
and then this is what i have within the database helper class... i think i want to call this method?
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor = mydatabase.query(true, DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_CATEGORY, KEY_DESCRIPTION }, KEY_ROWID + "="
+ rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
I would use mydatabase.rawquery(QUERY) instead of the cursors query method. Its easier for SQL developers I think. Anyways, once you have your values in the cursor, you can do this
EditRecipe.setText(cursor.getString(0));
EditRecipe2.setText(cursor.getString(1));
Where 0 represents the first column in your returned table. You would put that code after your mCursor.moveToFirst();

Categories

Resources