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);
Related
I am building a list box manipulated by cursor adapter. I have written the code below. RoomShare is the activity which holds the list. MessDatabase is the class that extends from SQLiteOpenHelper. TempDataFromDB is the temporary class that holds the record derived from DB.DB2CursorAdapter is the cursor adapter.
In RoomShare activity I am creating the MessDatabase object(derived from SQLiteOpenHelper). In the constructor of MessDatabase, I am creating table "Share_room" and adding a row to it Then Select* query is run on cursor.Then DB2CursorAdapter object is created. In the newView of DB2CursorAdapter, I am populating 2 textviews.
When I populate 2 textViews, the list item appears overwritten. But when I use 1 textview, in db_cursor_roomShare.xml, everything is fine. I think some problem with xml file.
public class RoomShare extends AppCompatActivity {
DB2CursorAdapter DBAdapter;
MessDatabase mdb;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_share);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String selectQuery = "SELECT * FROM " + TempDataFromDB.TABLE_NAME /*+ " ORDER BY " +
TempDataFromDB.COLUMN_MESS_NAME + " DESC"*/;
//this.deleteDatabase("ShareRoom_db");
mdb = new MessDatabase(this);
SQLiteDatabase db = mdb.getWritableDatabase();//getReadableDatabase();
cursor = db.rawQuery(selectQuery,null);
DBAdapter = new DB2CursorAdapter(this, cursor);
final ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(DBAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*Snackbar.make(view, "text u", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();*/
}
});
db.close();
}
public class MessDatabase extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ShareRoom_db";
public MessDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TempDataFromDB.CREATE_TABLE);
//insertMessName("Demo");
db.execSQL("INSERT INTO " + TempDataFromDB.TABLE_NAME +
"(" + TempDataFromDB.COLUMN_MESS_NAME +
")" + "VALUES " + "('One')");
}
public class DB2CursorAdapter extends CursorAdapter {
private LayoutInflater cursorInflater;
public DB2CursorAdapter(Context context, Cursor cursor) {
super(context,cursor);
System.out.println("Sandeep1");
/*cursorInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);*/
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// R.layout.list_row is your xml layout for each row
System.out.println("Sandeep2");
cursorInflater = LayoutInflater.from(parent.getContext());
return cursorInflater.inflate(R.layout.db_cursor_room_share, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
System.out.println("Sandeep3");
TextView tvBody = (TextView) view.findViewById(R.id.tvBody);
TextView tvPriority = (TextView) view.findViewById(R.id.tvPriority);
// Extract properties from cursor
String id = cursor.getString(cursor.getInt(cursor.getColumnIndex(TempDataFromDB.COLUMN_ID)));
String mess_name = cursor.getString(cursor.getColumnIndex(TempDataFromDB.COLUMN_MESS_NAME));
Toast toast=Toast.makeText(context,mess_name,Toast.LENGTH_SHORT);
toast.show();//----This is printing perfectly one
// Populate fields with extracted properties
tvBody.setText(id);
tvPriority.setText(mess_name);
System.out.println("Sandeep4");
}
public class TempDataFromDB {
public static final String TABLE_NAME = "Share_room";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_PARTICIPANTS = "Participants";
public static final String COLUMN_MESS_NAME = "Mess_Name";
private int id;
private String Participants;
String[] arrayParticipants;
private String Mess_Name;
// Create table SQL query
public static final String CREATE_TABLE =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PARTICIPANTS+ " TEXT,"
+ COLUMN_MESS_NAME+"TEXT"
+ ")";
public TempDataFromDB() {
}
public TempDataFromDB(int id, String Participants,String Mess) {
this.id = id;
this.Participants = Participants;
this.Mess_Name = Mess;
}
db_cursor_roomShare.xml
<?xml version="1.0" encoding="utf8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match parent"
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Study cursors"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="mess name"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<android.support.constraint.ConstraintLayout>
activity_room_share.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/res-auto"
xmlns:tools="http://schemas.android.tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RoomShare"
<ListView android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weight="1"/>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
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>
</android.support.design.widget.CoordinatorLayout>
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;
}
}
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?
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.