I have a SQLite Database connection to my application, I have followed a Tutorial and that tutorial show the database in a SimpleCursorAdapter, this does the whole class to this adapter and my buttons can not fit in this class.
I would therefore reduce this adapter to to fit with my buttons.
Or is there any other better solution?
For me the SimpleCursorAdapter Mix all my pictures an button to his adapter,
I dont know but i think that the SCadapter makes the whole view into a list view and i dont want that.
I have four classes.
DBAdapter,
Produkter (View)
Car is the SimpleCursorAdapter ViewBinder
and Bus is the Bitmap get, class
enter code here
public class DBhelper {
public static final String KEY_ID = BaseColumns._ID;
public static final String KEY_NAME = "name";
public static final String KEY_KCAL = "kcal";
public static final String KEY_VC = "vitaminc";
public static final String KEY_IMG = "image";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "FruitDB";
private static final int DATABASE_VERSION = 1;
public static final String FRUITS_TABLE = "fruits";
private static final String CREATE_FRUITS_TABLE = "create table "+FRUITS_TABLE+" ("
+KEY_ID+" integer primary key autoincrement, "
+KEY_IMG+" blob not null, "
+KEY_NAME+" text not null unique, "
+KEY_KCAL+" integer not null, "
+KEY_VC+" integer not null);";
private final Context mCtx;
private boolean opened = false;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_FRUITS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+FRUITS_TABLE);
onCreate(db);
}
}
public void Reset() {
openDB();
mDbHelper.onUpgrade(this.mDb, 1, 1);
closeDB();
}
public DBhelper(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
private SQLiteDatabase openDB() {
if(!opened)
mDb = mDbHelper.getWritableDatabase();
opened = true;
return mDb;
}
public SQLiteDatabase getHandle() { return openDB(); }
private void closeDB() {
if(opened)
mDbHelper.close();
opened = false;
}
public void createFruitEntry(Bus fruit) {
openDB();
ByteArrayOutputStream out = new ByteArrayOutputStream();
fruit.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, out);
ContentValues cv = new ContentValues();
cv.put(KEY_IMG, out.toByteArray());
cv.put(KEY_NAME, fruit.getName());
cv.put(KEY_KCAL, fruit.getKcal());
cv.put(KEY_VC, fruit.getVitaminC());
mDb.insert(FRUITS_TABLE, null, cv);
closeDB();
}
} enter code here
public class produkter extends ListActivity {
private DBhelper mDB;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDB = new DBhelper(this);
mDB.Reset();
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
mDB.createFruitEntry(new Bus(img, "Banane", 92, 10));
mDB.createFruitEntry(new Bus(img, "Kiwi", 56, 71));
mDB.createFruitEntry(new Bus(img, "Pfirsich", 41, 10));
mDB.createFruitEntry(new Bus(img, "Zitrone", 40, 51));
String[] columns = {mDB.KEY_ID, mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL,
mDB.KEY_VC};
String table = mDB.FRUITS_TABLE;
Cursor c = mDB.getHandle().query(table, columns, null, null, null, null,
null);
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.produkterx,
c,
new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL, mDB.KEY_VC},
new int[] {R.id.img, R.id.txt, R.id.rating});
adapter.setViewBinder(new Car());
setListAdapter(adapter);
enter code here
public class Car implements SimpleCursorAdapter.ViewBinder {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(view instanceof ImageView) {
ImageView iv = (ImageView) view;
byte[] img = cursor.getBlob(columnIndex);
iv.setImageBitmap(BitmapFactory.decodeByteArray(img, 0,
img.length));
return true;
}
if(view instanceof RatingBar) {
RatingBar rb = (RatingBar) view;
int kcal = cursor.getInt(cursor.getColumnIndex(DBhelper.KEY_KCAL));
int vitc = cursor.getInt(cursor.getColumnIndex(DBhelper.KEY_VC));
rb.setRating((float) (kcal * ((float) vitc/1000.0)));
return true;
}
return false;
}
}
enter code here
public class Bus {
private Bitmap bmp;
private String name;
private int kcal;
private int vitaminc;
public Bus(Bitmap b, String n, int k, int v) {
bmp = b;
name = n;
kcal = k;
vitaminc = v;
}
public Bitmap getBitmap() { return bmp; }
public String getName() { return name; }
public int getKcal() { return kcal; }
public int getVitaminC() { return vitaminc; }
}
enter code here` XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/Blue"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1" >
<Button
android:id="#+id/btnE"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="E" />
<ImageView
android:id="#+id/image1"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginTop="-7dp"
android:contentDescription="#drawable/header2"
android:src="#drawable/header2" />
<Button
android:id="#+id/btnkontakt"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="k" />
<Button
android:id="#+id/btnprodukter"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btnE"
android:text="p" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
<Button
android:id="#+id/btnSok"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/btnprodukter"
android:text="s" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="-7dp"
android:contentDescription="#drawable/sok"
android:src="#drawable/produkter" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_weight="1" >
<ImageView
android:id = "#+id/img"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignParentLeft = "true"
>
</ImageView>
<TextView
android:id = "#+id/txt"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerVertical = "true"
>
</TextView>
<RatingBar
style="?android:attr/ratingBarStyleSmall"
android:id = "#+id/rating"
android:numStars = "5"
android:stepSize = "0.5"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_alignParentRight = "true"
android:layout_centerVertical = "true"
android:layout_marginRight = "5px">
</RatingBar>
</LinearLayout>
</LinearLayout>
> Blockquote
This XML is all in a simpelCA that i dont want!!
I'm a little confused as to the question. Your simple Cursor Adapter is meant to send the data to a listview for populating your screen.
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.produkterx,
c,
new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_KCAL, mDB.KEY_VC},
new int[] {R.id.img, R.id.txt, R.id.rating});
You will want a match for the String[]/int[]. If you don't want to show something don't include it in here.
Related
I want help for displaying data in listview from local database SQLite. I have already data in the database.
so please help me with where am I doing mistakes?
below code of DatabseHelper.Java
private static final String DATABASE_NAME = "Barcode_Printing.db";
static final String TABLE_NAME = "Item_Master";
static final String Item_name = "Item_Name";
static final String wEight = "Weight";
static final String MrP = "MRP";
static final String BarcodE = "BARCODE";
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + BarcodE + " INTEGER PRIMARY KEY, " + Item_name + " TEXT, " + wEight + " TEXT, " + MrP + " INTEGER, EXPIRY_DATE TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getAllItems() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[]{BarcodE, Item_name, wEight, MrP},
null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
return cursor;
}
else
{
return null;
}
}
below for activity_dispaly_items.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.packlab.alpesh.barcodeprinting.Display_Items">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ListView
android:id="#+id/lvItem_Display"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
tools:layout_editor_absoluteY="3dp" />
</android.support.design.widget.CoordinatorLayout>
below for items_display_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tvItemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="TextView"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.065"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvBarcode"
android:layout_width="wrap_content"
android:layout_height="19dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="48dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.119"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tvMrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.119"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvWeight" />
<TextView
android:id="#+id/tvWeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.119"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvBarcode" />
</android.support.constraint.ConstraintLayout>
below code for DisplayItems.Java
its give me error directly "There was an error!"
its don't go in try. its go directly in Catch.
public class Display_Items extends AppCompatActivity
{
SimpleCursorAdapter simpleCursorAdapter;
ListView display_Items;
DatabaseHelper DatabaseHelper;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display__items);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
spinner = findViewById(R.id.spinner_Comapny);
setSupportActionBar(toolbar);
display_Items = findViewById(R.id.lvItem_Display);
DatabaseHelper = new DatabaseHelper(this);
loadSpinnerData();
displayProductList();
}
private void displayProductList()
{
try
{
Cursor cursor = DatabaseHelper.getAllItems();
if (cursor == null)
{
Toast.makeText(Display_Items.this, "Unable to generate cursor.", Toast.LENGTH_SHORT).show();
return;
}
if (cursor.getCount() == 0)
{
Toast.makeText(Display_Items.this, "No Products in the Database.", Toast.LENGTH_SHORT).show();
return;
}
String[] columns = new String[] {
DatabaseHelper.BarcodE,
DatabaseHelper.Item_name,
DatabaseHelper.wEight,
DatabaseHelper.MrP
};
int[] boundTo = new int[] {
R.id.tvBarcode,
R.id.tvItemName,
R.id.tvWeight,
R.id.tvMrp
};
simpleCursorAdapter = new SimpleCursorAdapter(this,
R.layout.item_display_layout,
cursor,
columns,
boundTo,
0);
display_Items.setAdapter(simpleCursorAdapter);
}
catch (Exception ex)
{
Toast.makeText(Display_Items.this, "There was an error!", Toast.LENGTH_SHORT).show();
}
}
}
i provide simple way to read data from sqllite used below code ..
first make one pojo class ..
public class MyTable {
public String itemName,weight,mrp,barcod;
}
then after data base class make method for read data ...
public List<MyTable> getMyItems() {
List<MyTable> mySuperList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_NAME ;
Cursor c = db.rawQuery(selectQuery, null);
if (c != null) {
c.moveToFirst();
while (c.isAfterLast() == false) {
MyTable myTable = new MyTable();
myTable.itemName = (c.getString(c.getColumnIndex("Item_Name")));
myTable.weight = (c.getString(c.getColumnIndex("Weight")));
myTable.mrp = (c.getString(c.getColumnIndex("MRP")));
myTable.barcod = (c.getString(c.getColumnIndex("BARCODE")));
mySuperList.add(myTable);
c.moveToNext();
}
}
return mySuperList;
}
then after used this method and bind data into listview.
as above you bind data into listview then make custom adapter and take one layout for show all data in different view control.
adapter::
public class CommentsAdapter extends ArrayAdapter<MyTable> {
Context context;
List<MyTable> data = null;
public CommentsAdapter(Context context, int layoutResourceId, List<MyTable> data) {
super(context, layoutResourceId, data);
this.context = context;
this.data = data;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// if(context.get()!=null) {
final LayoutInflater inflater = ((Activity) context).getLayoutInflater();
final View outerContiner = inflater.inflate(R.layout.comment_item, parent, false);// define your layout
TextView text = (TextView) outerContiner.findViewById(R.id.comment_text);
TextView barcode = (TextView) outerContiner.findViewById(R.id.comment_barcode);
text.setText(data.get(position).itemName);
barcode.setText(data.get(position).barcode);
return outerContiner;
//}
}
}
then after used below code bind data..
Note ::Here layout same in adapter constructor and getView Method.
List<MyTableTwo> myTableTwos=dbHelper.getMyItems();
CommentsAdapter commentsAdapter=new CommentsAdapter(DbInsert.this,R.layout.table_layout,myTableTwos);
ListView listView=findViewById(R.id.liLvData);
listView.setAdapter(commentsAdapter);
commentsAdapter.notifyDataSetChanged();
I am working on a sqlite database project on android. And it's my first sqlite project. I read lots of article and created my app but there's a problem that I can't find a way to solve it.i want to get NAME_FILTER table to autoCompleteTextView
here is my layout code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="90dp"
android:layout_height="wrap_content"
android:text="#string/customers_name"
android:textSize="16sp" />
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"/>
<EditText
android:id="#+id/edt_filter_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:imeOptions="actionNext"
style="#style/EditText.Input"
android:theme="#style/EditText.Input"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="20dp"
android:paddingBottom="20dp">
<Button
android:id="#+id/btn_submit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_submit"
android:textColor="#333333"
android:background="#drawable/buttonshape"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textSize="18sp"
android:drawableStart="#drawable/ic_check_black_24dp"/>
<Button
android:id="#+id/btn_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/btn_cancel"
android:textColor="#333333"
android:background="#drawable/red_button_background"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:drawableStart="#drawable/ic_cancel_black_24dp"/>
</LinearLayout>
</LinearLayout>
and here is my Activity
public class FiltersActivity extends AppCompatActivity implements ActionMode.Callback{
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
private static int Filter_list_position = -1;
private Button btnSubmit;
private Button btnCancel;
private ListView listView;
private FilterListAdapter adapter;
private EditText edtName;
private int seletcedFilterId;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.filters_title);
setContentView(R.layout.activity_filters);
btnCancel = (Button) findViewById(R.id.btn_cancel);
btnSubmit = (Button) findViewById(R.id.btn_submit);
edtName = (EditText) findViewById(R.id.edt_filter_name);
btnCancel.setOnClickListener(onCancelbuttonClicked);
listView = (ListView) findViewById(R.id.listView);
//Creating the instance of ArrayAdapter containing list of fruit names
ArrayAdapter<String> adapterr = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, NAME_FILTER);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapterr);//setting the adapter data into the AutoCompleteTextView
refreshList();
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
DataBaseHelper Cllas
public class DatabaseHelper {
private SQLiteDatabase mydb;
public DatabaseHelper(Context context){
mydb = new MyDatabase(context).getWritableDatabase();
}
public void addNewFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.insert(MyDatabase.tableFilters, null, values);
mydb.close();
}
public List<filter> getListOfFilters(){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters, null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
public void editFilter(filter filter){
ContentValues values = new ContentValues();
values.put("name", filter.getName());
mydb.update(MyDatabase.tableFilters, values, "id = " + filter.getId(), null);
mydb.close();
}
public void deleteFilter(filter filter){
mydb.delete(MyDatabase.tableFilters, "id = " + filter.getId(), null);
mydb.close();
}
public List<filter> searchFilterByName(String name){
Cursor c = mydb.rawQuery("select * from " + MyDatabase.tableFilters + " where name like '%" + name + "%'", null);
List<filter> filters = new ArrayList<>();
while (c.moveToNext()){
filter em = new filter();
em.setId(c.getInt(c.getColumnIndex(MyDatabase.ID_FILTER)));
em.setName(c.getString(c.getColumnIndex(MyDatabase.NAME_FILTER)));
filters.add(em);
}
c.close();
mydb.close();
return filters;
}
}
and this is my ListAdapter Class
class FilterListAdapter extends BaseAdapter {
private Context context;
private List<filter> filters;
FilterListAdapter(Context context, List<filter> filters){
this.context = context;
this.filters = filters;
}
#Override
public int getCount() {
return filters.size();
}
#Override
public Object getItem(int i) {
return filters.get(i);
}
#Override
public long getItemId(int i) {
return filters.get(i).getId();
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
View rowView = LayoutInflater.from(context).inflate(R.layout.filter_list_item, viewGroup, false);
TextView txtName = (TextView) rowView.findViewById(R.id.txt_filter_name);
txtName.setText(filters.get(position).getName());
return rowView;
}
}
I'm working with Java and XML in Android Studio to populate a ListView with CursorAdapter. I'm kinda new to this and trying to solv a problem. I'm really green so any tips would also help.
My DBHandler looks like that:
public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 10;
private static final String DATABASE_NAME = "jogging.db";
public static final String TABLE_TRIP = "Trip";
public static final String TUR_COLUMN_ID = "_id";
public static final String TUR_COLUMN_DISTANCE = "Ditance";
public static final String TUR_COLUMN_SCORE = "Fastest";
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TRIP + "(" +
TUR_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TUR_COLUMN_DISTANCE + " TEXT, " +
TUR_COLUMN_SCORE + " TEXT " +
");";
db.execSQL(query);
}
CursorAdapter I'm trying to use to get data to ListView:
public class TripCursorAdapter extends CursorAdapter {
public TripCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.content_trips, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tripId = (TextView) view.findViewById(R.id.tripIdView);
TextView tripDistance = (TextView) view.findViewById(R.id.tripDistanceView);
TextView tripScore = (TextView) view.findViewById(R.id.tripScoreView);
String id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String distance = cursor.getString(cursor.getColumnIndexOrThrow("Ditance"));
String score = cursor.getString(cursor.getColumnIndexOrThrow("Fastest"));
tripId.setText(id);
tripDistance.setText(distance);
tripScore.setText(score);
}
And the activity to set up ListView
public class TripsActivity extends AppCompatActivity {
DBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trips);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbHandler = new DBHandler(this);
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor tripCursor = db.rawQuery("SELECT * FROM Trip", null );
ListView lvItems = (ListView) findViewById(R.id.listView);
TripCursorAdapter tripAdapter = new TripCursorAdapter(this, tripCursor, 0);
lvItems.setAdapter(tripAdapter);
}
XML Files:
trips_content.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="hmk.fitness_app.TripsActivity"
tools:showIn="#layout/activity_trips">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
And I have also item_trip.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:id="#+id/tripIdView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Distance"
android:id="#+id/tripDistanceView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:id="#+id/tripScoreView"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
Not quite sure why I get error msg about null object referances. Any tips what I should do?
Change
return LayoutInflater.from(context).inflate(R.layout.content_trips, parent, false);
to
return LayoutInflater.from(context).inflate(R.layout.item_trip, parent, false);
On a database project, I've a table with three variables, namely '_id', 'item' for a food item name and 'type' for the type of food. I have three type's of food: 'Vege Soup', 'Non Vege Soup' and 'Chai'.
In my MainActivity Class, I have three radio buttons in a group which chooses the 'type' of item, followed by a 'view' button to get a ListView of all the items from the type chosen through the radio buttons.
I use the SimpleCursorAdapter, which is intended to map columns from a cursor to TextViews or ImageViews defined in an XML file.
The expected result is ListView contains the rows information. The current result is a blank ListView. I can't figure why.
MainActivity class:
public class MainActivity extends Activity implements OnClickListener,
OnCheckedChangeListener {
Button dinnerAdd, dinnerView;
RadioGroup dishType;
RadioButton vegeSoupView, nonVegeSoupView, chaiView;
Intent i, v;
String type;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
dinnerView = (Button) findViewById(R.id.bView);
dishType = (RadioGroup) findViewById(R.id.rgDishType);
vegeSoupView = (RadioButton) findViewById(R.id.rDtVegeSoup);
nonVegeSoupView = (RadioButton) findViewById(R.id.rDtNonVegeSoup);
chaiView = (RadioButton) findViewById(R.id.rDtChai);
dinnerAdd.setOnClickListener(this);
dinnerView.setOnClickListener(this);
dishType.setOnCheckedChangeListener(this);
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.bAddDish:
i = new Intent("com.example.databaselist.ADDITEM");
startActivity(i);
break;
case R.id.bView:
didItWork = true;
if (vegeSoupView.isChecked()) {
type = "Vege Soup";
} else {
if (nonVegeSoupView.isChecked()) {
type = "Non Vege Soup";
} else {
if (chaiView.isChecked()) {
type = "Chai";
}
}
}
makeIntent();
startActivity(v);
break;
}
}
public void makeIntent(){
Bundle basket = new Bundle();
basket.putString("type", type);
v = new Intent(MainActivity.this, ItemListView.class);
v.putExtras(basket);
}
}
activity_main.xml:
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<RadioGroup
android:id="#+id/rgDishType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_below="#id/bRandomise">
<RadioButton
android:id="#+id/rDtVegeSoup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Vege Soup" />
<RadioButton
android:id="#+id/rDtNonVegeSoup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Non Vege Soup"
android:textSize="15dp"/>
<RadioButton
android:id="#+id/rDtChai"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Chai" />
</RadioGroup>
<Button
android:id="#+id/bView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/rgDishType"
android:layout_centerHorizontal="true"
android:text="View" />
<Button
android:id="#+id/bAddDish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/bView"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Add Dish" />
</RelativeLayout>
The 'view' button when pressed creates an intent to open the listview activity.
ItemListView class:
public class ItemListView extends Activity {
DBAdapter myDb;
MainActivity mA;
Intent a;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.item_list_view);
Bundle gotBasket = getIntent().getExtras();
String from = gotBasket.getString("type");
openDB();
ListViewTypeFromDB_MainActivity(from);
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void ListViewTypeFromDB_MainActivity(String fromguy) {
Cursor cursor = myDb.getRows(fromguy);
startManagingCursor(cursor);
String[] fromFieldNames = new String[] { DBAdapter.KEY_ITEM };
int[] toViewIDs = new int[] { R.id.item_name };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
}
item_list_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listViewFromDB"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Here's the layout for each row of the listview.
item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="NAME!"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
So, as you can see in the ItemListView Class, I have used the SimpleCursorAdapter. Though it managed to get to the item_list_view activity, it came up completely blank. Here is my DatabaseAdapter.
DBAdapter class:
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
// TODO: Setup your fields here:
public static final String KEY_ITEM = "item";
public static final String KEY_TYPE = "type";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_ITEM = 1;
public static final int COL_TYPE= 2;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_ITEM,
KEY_TYPE};
public static final String[] KEY_ITEM_ONLY = new String[] {KEY_ITEM};
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
public static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_ITEM + " string not null unique, "
+ KEY_TYPE + " string not null"
+ ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
public void close() {
myDBHelper.close();
}
public long insertRow(String item, String type) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM, item);
initialValues.put(KEY_TYPE, type);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
public Cursor getRows(String type){
String where = KEY_TYPE + "='" + type + "'";
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " +
oldVersion + " to " + newVersion + ", which will destroy all old
data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
So, is there something wrong with the SimpleCursorAdapter, or could it be a problem in the DBAdapter Class?
Please i really need help with listview filter.because I've seen many tutorials but it doesn't work.and i really tired of this
just i need the EdiText filter
my project contain four classes:
1-LocationActivity (l'activity prencipale)
public class LocationActivity extends Activity implements LocationListener{
public final static String LOCATION_ID = "location_id";
private long location_id;
private EditText name;
private EditText comment;
private RatingBar ratevalue;
private EditText latitude;
private EditText longitude;
private TextView current_latitude;
private TextView current_longitude;
private TextView current_source;
private TextView current_accuracy;
private LocationDatabase db;
private BestLocationProxy best_location_proxy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new LocationDatabase(this);
best_location_proxy = new BestLocationProxy(this);
if (savedInstanceState != null) {
location_id = savedInstanceState.getLong(LOCATION_ID);
}
Intent intent = getIntent();
location_id = intent.getLongExtra(LOCATION_ID, -1);
setContentView(R.layout.location);
name = (EditText) findViewById(R.id.name);
comment = (EditText) findViewById(R.id.comment);
ratevalue = (RatingBar) findViewById(R.id.ratingbar);
latitude = (EditText) findViewById(R.id.latitude);
longitude = (EditText) findViewById(R.id.longitude);
current_latitude = (TextView) findViewById(R.id.current_latitude);
current_longitude = (TextView) findViewById(R.id.current_longitude);
current_source = (TextView) findViewById(R.id.current_source);
current_accuracy = (TextView) findViewById(R.id.current_accuracy);
updateLocation(best_location_proxy.getLastKnownLocation());
Button set_location = (Button) findViewById(R.id.set_location);
set_location.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Location l = best_location_proxy.getLastKnownLocation();
if (l == null) {
return;
}
latitude.setText(Double.toString(l.getLatitude()));
longitude.setText(Double.toString(l.getLongitude()));
}
});
Button closeButton = (Button) findViewById(R.id.close_location_window);
closeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
if (location_id != -1) {
Cursor c = db.getLocation(location_id);
if (c.getCount() != 1) {
finish();
return;
}
c.moveToFirst();
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int comment_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_COMM);
int ratevalue_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_RATE);
int latitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
name.setText(c.getString(name_id));
comment.setText(c.getString(comment_id));
ratevalue.setRating(c.getLong(ratevalue_id));
latitude.setText(Double.toString(c.getDouble(latitude_id)));
longitude.setText(Double.toString(c.getDouble(longitude_id)));
c.close();
}
}
#Override
protected void onResume() {
super.onResume();
best_location_proxy.requestLocationUpdates(100000, 0, this);
}
#Override
protected void onPause() {
super.onPause();
best_location_proxy.removeUpdates(this);
String s_name = name.getText().toString();
if (s_name.equals("")) {
return;
}
String s_comment = comment.getText().toString();
if (s_comment.equals("")) {
return;
}
Double d_ratevalue = (double) ratevalue.getRating();
Double d_latitude = null;
String s_latitude = latitude.getText().toString();
if (!s_latitude.equals("")) {
d_latitude = Double.parseDouble(s_latitude);
}
Double d_longitude = null;
String s_longitude = longitude.getText().toString();
if (!s_longitude.equals("")) {
d_longitude = Double.parseDouble(s_longitude);
}
if (location_id != -1) {
db.updateLocation(location_id, s_name, s_comment, d_ratevalue, d_latitude, d_longitude);
} else {
location_id = db.createLocation(s_name, s_comment, d_ratevalue, d_latitude, d_longitude);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(LOCATION_ID, location_id);
}
private void updateLocation(Location l){
if (l == null){
current_source.setText(R.string.no_provider);
current_latitude.setText(R.string.unavailable);
current_longitude.setText(R.string.unavailable);
current_accuracy.setText(R.string.unavailable);
return;
}
String source;
if (l.getProvider().equals(LocationManager.GPS_PROVIDER)){
source = getString(R.string.location_map);
} else if (l.getProvider().equals(LocationManager.NETWORK_PROVIDER)){
source = getString(R.string.cell);
} else {
source = getString(R.string.unknown);
}
current_source.setText(source);
current_latitude.setText(Double.toString(l.getLatitude()));
current_longitude.setText(Double.toString(l.getLongitude()));
current_accuracy.setText(Float.toString(l.getAccuracy()));
}
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
2-LocationListActivity (listview activity)
public class LocationListActivity extends ListActivity {
private Cursor locations;
private LocationDatabase db;
private final static String RADAR_ACTION = "com.google.android.radar.SHOW_RADAR";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = new LocationDatabase(this);
setContentView(R.layout.list);
registerForContextMenu(this.getListView());
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor c = (Cursor) parent.getAdapter().getItem(position);
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int latitude_id = c
.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c
.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
String name = c.getString(name_id);
float latitude = c.getFloat(latitude_id);
float longitude = c.getFloat(longitude_id);
startBest(latitude, longitude, name);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem add = menu.add(R.string.location_add);
add.setIcon(android.R.drawable.ic_menu_add);
add.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent();
i.setClass(LocationListActivity.this, LocationActivity.class);
startActivity(i);
return true;
}
});
return true;
}
#Override
protected void onResume() {
super.onResume();
updateList();
}
#Override
protected void onStop() {
super.onStop();
if (locations != null){
locations.close();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
Cursor c = (Cursor) getListView().getItemAtPosition(info.position);
int id_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_ID);
int name_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_NAME);
int latitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LATITUDE);
int longitude_id = c.getColumnIndex(LocationDatabase.FIELD_LOCATIONS_LONGITUDE);
final long id = c.getLong(id_id);
final String name = c.getString(name_id);
final float latitude = c.getFloat(latitude_id);
final float longitude = c.getFloat(longitude_id);
menu.setHeaderTitle(name);
MenuItem map = menu.add(R.string.location_map);
map.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
startMap(latitude, longitude, name);
return true;
}
});
MenuItem edit = menu.add(R.string.location_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent();
i.setClass(LocationListActivity.this, LocationActivity.class);
i.putExtra(LocationActivity.LOCATION_ID, id);
startActivity(i);
return true;
}
});
MenuItem delete = menu.add(R.string.location_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
db.deleteLocation(id);
updateList();
return true;
}
});
}
private void updateList() {
if (locations != null) {
locations.close();
}
locations = db.getAllLocations();
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, locations,
new String[] { LocationDatabase.FIELD_LOCATIONS_NAME, },
new int[] { android.R.id.text1 });
setListAdapter(adapter);
}
private void startRadar(float latitude, float longitude){
Intent i = new Intent(RADAR_ACTION);
i.putExtra("latitude", latitude);
i.putExtra("longitude", longitude);
startActivity(i);
}
private void startMap(float latitude, float longitude, String name){
Formatter f = new Formatter(Locale.US);
f.format("geo:0,0?q=%1$.5f,%2$.5f(%3$s)", latitude, longitude, name);
Uri uri = Uri.parse(f.toString());
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
}
private void startBest(float latitude, float longitude, String name){
if (isRadarAvailable()){
startRadar(latitude, longitude);
} else {
startMap(latitude, longitude, name);
}
}
private boolean isRadarAvailable(){
return isIntentAvailable(RADAR_ACTION);
}
private boolean isIntentAvailable(String action) {
PackageManager packageManager = getPackageManager();
final Intent intent = new Intent(action);
#SuppressWarnings("rawtypes")
List list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}
3-LocationDataase (database activity sqlite)
public class LocationDatabase extends SQLiteOpenHelper {
public final static String TAG = LocationDatabase.class.toString();
public final static String DB_NAME = "locations";
public final static int DB_VERSION = 1;
public final static String TABLE_LOCATIONS = "locations";
public final static String FIELD_LOCATIONS_ID = "_id";
public final static String FIELD_LOCATIONS_NAME = "name";
public final static String FIELD_LOCATIONS_COMM = "comment";
public final static String FIELD_LOCATIONS_RATE = "ratevalue";
public final static String FIELD_LOCATIONS_LATITUDE = "latitude";
public final static String FIELD_LOCATIONS_LONGITUDE = "longitude";
public final static String[] PROJECTION_LOCATIONS = { FIELD_LOCATIONS_ID,
FIELD_LOCATIONS_NAME, FIELD_LOCATIONS_COMM, FIELD_LOCATIONS_RATE, FIELD_LOCATIONS_LATITUDE,
FIELD_LOCATIONS_LONGITUDE };
public LocationDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
getWritableDatabase(); // make upgrades work
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_LOCATIONS + " ( " +
FIELD_LOCATIONS_ID + " INTEGER PRIMARY KEY NOT NULL, " +
FIELD_LOCATIONS_NAME + " Text, " +
FIELD_LOCATIONS_COMM + " Text, " +
FIELD_LOCATIONS_RATE + " REAL, " +
FIELD_LOCATIONS_LATITUDE + " REAL, "
+ FIELD_LOCATIONS_LONGITUDE + " REAL )");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
public long createLocation(String name, String comment, Double ratevalue, Double latitude, Double longitude) {
Log.d(TAG, "Inserting location " + name + comment + ratevalue);
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_LOCATIONS_NAME, name);
values.put(FIELD_LOCATIONS_COMM, comment);
values.put(FIELD_LOCATIONS_RATE, ratevalue);
values.put(FIELD_LOCATIONS_LATITUDE, latitude);
values.put(FIELD_LOCATIONS_LONGITUDE, longitude);
long id = db.insert(TABLE_LOCATIONS, null, values);
Log.d(TAG, Long.toString(id));
db.close();
return id;
}
public void updateLocation(Long location_id, String name, String comment, Double ratevalue, Double latitude,
Double longitude) {
Log.d(TAG, "Updating location");
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_LOCATIONS_NAME, name);
values.put(FIELD_LOCATIONS_COMM, comment);
values.put(FIELD_LOCATIONS_RATE, ratevalue);
values.put(FIELD_LOCATIONS_LATITUDE, latitude);
values.put(FIELD_LOCATIONS_LONGITUDE, longitude);
db.update(TABLE_LOCATIONS, values, "_id = ?",
new String[] { location_id.toString() });
db.close();
}
public Cursor getAllLocations() {
Log.d(TAG, "Selecting all locations");
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_LOCATIONS, PROJECTION_LOCATIONS, null, null,
null, null, FIELD_LOCATIONS_NAME);
Log.d(TAG, Integer.toString(c.getCount()));
db.close();
return c;
}
public Cursor getLocation(long location_id) {
Log.d(TAG, "Selecting location " + Long.toString(location_id));
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_LOCATIONS, PROJECTION_LOCATIONS, "_id = ?",
new String[] { Long.toString(location_id) }, null, null, null);
Log.d(TAG, Integer.toString(c.getCount()));
db.close();
return c;
}
public void deleteLocation(long location_id){
Log.d(TAG, "Deleting location " + Long.toString(location_id));
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_LOCATIONS, "_id = ?", new String[] {Long.toString(location_id)});
}
}
4-BestLocationProxy
in the Layout I have location.xml and list.xml
1-location.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="311dp"
android:orientation="vertical"
android:paddingRight="20dip" >
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="#string/name"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/name"
android:singleLine="true"
android:layout_weight="1" />
<TextView
android:text="#string/comment"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/comment"
android:singleLine="true"
android:layout_weight="1" />
<TextView
android:text="#string/Rate"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
</TableLayout>
<RatingBar
android:id="#+id/ratingbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stepSize="1"
/>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:text="#string/latitude"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/latitude"
android:singleLine="true"
android:layout_weight="1"
android:numeric="signed|decimal" />
<TextView
android:text="#string/longitude"
android:gravity="left|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:editable="true"
android:id="#+id/longitude"
android:singleLine="true"
android:layout_weight="1"
android:numeric="signed|decimal" />
</TableLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:text="#string/source"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_source"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
<TableRow>
<TextView
android:text="#string/latitude"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_latitude"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
<TableRow>
<TextView
android:text="#string/longitude"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_longitude"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
<TableRow>
<TextView
android:text="#string/accuracy"
android:gravity="right|center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingRight="10dip" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/current_accuracy"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
</TableLayout>
<View
android:layout_width="fill_parent"
android:background="#android:drawable/divider_horizontal_bright"
android:layout_marginBottom="10dip"
android:layout_marginTop="10dip"
android:layout_height="4dip" />
<Button
android:id="#+id/set_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/set_location" />
<Button
android:id="#+id/close_location_window"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/close" />
</LinearLayout>
</ScrollView>
2- list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:longClickable="true"
android:layout_weight="1" />
<ScrollView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<TextView
android:id="#+id/emptyText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/empty_msg"
android:textSize="20sp"
android:textColor="?android:attr/textColorSecondary"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:lineSpacingMultiplier="0.92" />
</ScrollView>
</LinearLayout>
Sorry...too Long
I think I see what you are trying to do. Here is an example using the ListView's TextFilter:
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
ListView list = new ListView(this);
layout.addView(list);
setContentView(layout);
String[] array = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
}
You need to open the keyboard by long pressing the Menu button.
Unfortunately, this feature is completely inadequate to sort a result set from a CursorAdapter. In fact the TextFilter doesn't even respond when I bound it to a SimpleCursorAdapter.
Solution:
Here's one basic approach, try adding an EditText and a Button. Say, you want to sort the location by name. When the user clicks the button you query your database with what's in the EditText, like this:
db.query(TABLE_LOCATIONS, PROJECTION_LOCATIONS,
FIELD_LOCATIONS_NAME " LIKE '%?%'", editTextString,
null, null, FIELD_LOCATIONS_NAME);
Of course, editTextString is the user's input from the EditText. Now simply set this new Cursor returned from your Database to your adapter like this:
adapter.changeCursor(newCursor);
You will have to use the same approach to sort by more than just the name, but this is the general idea. Design wise you can move the search EditText and Button into a PopUpWindow, or instead of a Button your can re-query the Database with every new letter typed into the EditText with a TextWatcher; there are many different methods. Hope that helps.