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?
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'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);
I will insert DATE into the DATABASE, using a datepicker. It will be stored as STRING in the database. My another step is to check the date. By this, I mean I will have a edittext and a button. In the Edit Text, it will select the date using datapicker.
Upon clicking on the button, it will check whether the database have the date. If have, it will direct to another page, else it will toast no such date.
This is my code:
selection.java
public class selection extends Activity {
Button newButton;
Button updateButton;
Button deleteButton;
Button summaryButton;
static EditText updateEdit;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selection);
updateEdit = (EditText)findViewById(R.id.updateEdit);
updateEdit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// showDialog(DATE_DIALOG_ID);
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
});
newButton = (Button) findViewById(R.id.newBTN);
newButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent mainAct=new Intent(getApplicationContext(),MainActivity.class);
startActivity(mainAct);
}
});
updateButton = (Button) findViewById(R.id.updateBTN);
updateButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent updateAct=new Intent(getApplicationContext(),update.class);
startActivity(updateAct);
}
});
deleteButton = (Button) findViewById(R.id.deleteBTN);
deleteButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent updateAct=new Intent(getApplicationContext(),update.class);
startActivity(updateAct);
}
});
summaryButton = (Button) findViewById(R.id.summaryBTN);
summaryButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent summaryView=new Intent(getApplicationContext(),summary.class);
startActivity(summaryView);
}
});
}
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
public EditText editText;
DatePicker dpResult;
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
//return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
updateEdit.setText(String.valueOf(day) + "/"
+ String.valueOf(month + 1) + "/" + String.valueOf(year));
// set selected date into datepicker also
}
}
}
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_PRICE = "fuelprice";
public static final String KEY_FUEL = "fuelpump";
public static final String KEY_COST = "tcost";
public static final String KEY_ODM = "odometer";
public static final String KEY_CON = "fcon";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "fuelLog";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
try{
db.execSQL(DATABASE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}//onCreate
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}//onUpgrade
}//DatabaseHelper
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//open
//---closes the database---
public void close()
{
DBHelper.close();
}//close
//---insert a log into the database---
public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_PRICE, fuelprice);
initialValues.put(KEY_FUEL, fuelpump);
initialValues.put(KEY_COST, tcost);
initialValues.put(KEY_ODM, odometer);
initialValues.put(KEY_CON, fcon);
return db.insert(DATABASE_TABLE, null, initialValues);
}//insertLog
}
selection.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1 ">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/newBTN"
android:text="New"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/updateBTN"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<EditText
android:id="#+id/updateEdit"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false"
android:enabled="true">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/deleteBTN"
android:text="Delete"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<EditText
android:id="#+id/deleteEdit"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/summaryBTN"
android:text="Summary"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</TableRow>
</TableLayout>
</LinearLayout>
Implement a method in your DBAdapter to get the dates into an array or arraylist e.g. datesList:
public ArrayList<String> getAllDates() {
ArrayList<String> datesList = new ArrayList<String>();
Cursor cursor = database.query(MySQLiteHelper.DATABASE_TABLE,
yourColumn, null, null, null, null, null);
cursor.moveToLast();
while (!cursor.isBeforeFirst()) {
// I am thinking your date is located at 1
String date = cursor.getString(1);
datesList.add(date);
cursor.moveToPrevious();
}
// Make sure to close the cursor
cursor.close();
return datesList;
}
And for comparing the dates, start a loop something like:
DBAdapter adapter = new DBAdapter();
adapter.open();
ArrayList <String> datesList = adapter.getAllDates();
for (String d:datesList){
if (d.equals(date)){
// do something
return;
}
}
It is important that the pattern of dates from database and from date picker are important such as "dd/MM/yyyy". Hope it helps
I am trying to modify an example of a listview that is connected to a database. it was setup to only allow for one item in the listview to be selected and then for the user to click a "delete person" button. I have made changes that I thought would allow a user to select multiple people and then click delete and have it delete the items in list selected (checked) and then when the user clicks the delete button to go through a for loop and for the items that are checked to get their id and call the database and delete that row or item from the database table. The code runs and deletes items but it deletes the wrong items and only part of the selected items. I know it has something to do with the way I am checking for the id of the selected (checked) items in the list, but I don't know how to fix it. Please see the code in the onDeleteClick() method.
The source code for the main activity:
public class MainActivity extends ListActivity {
private static final int ADD_DIALOG = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView list = getListView();
list.setItemsCanFocus(false);
//list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// initialize the adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
//android.R.layout.simple_list_item_single_choice,
android.R.layout.simple_list_item_multiple_choice,
null,
new String[]{DBHelper.C_NAME},
new int[]{android.R.id.text1});
setListAdapter(adapter);
updateAdapterData();
}
public void updateAdapterData(){
// re-query the data
SQLiteDatabase db = new DBHelper(this).getReadableDatabase();
//SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
Cursor c = db.query(DBHelper.TABLE_PEOPLE, null, null, null, null,
null, null);
((SimpleCursorAdapter)getListAdapter()).changeCursor(c);
db.close();
}
public void onAddClicked(View view){
showDialog(ADD_DIALOG);
}
public void onDeleteClicked(View view){
ListView lstView = getListView(); // added for hw
//int position = getListView().getCheckedItemPosition(); // removed for hw
SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
for(int i = 0; i < lstView.getCount(); i++){
if(lstView.isItemChecked(i)){
long itemId = lstView.getItemIdAtPosition(i);
int rowsAffected = db.delete(DBHelper.TABLE_PEOPLE,
DBHelper.C_ID + " = " + itemId, null);
}
}
db.close();
//if(rowsAffected > 0)
updateAdapterData();
//if(position >= 0){
//long itemId = getListAdapter().getItemId(position);
//SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
//int rowsAffected = db.delete(DBHelper.TABLE_PEOPLE, DBHelper.C_ID
+ " = " + itemId, null);
//db.close();
//if(rowsAffected > 0)
// updateAdapterData();
//}
}
protected Dialog onCreateDialog(int id){
Dialog d;
switch(id){
case ADD_DIALOG:
d = new Dialog(this);
d.setContentView(R.layout.add_person_dialog);
d.setTitle("Add a Person");
final TextView nameText = (TextView)d.findViewById(R.id.name);
d.findViewById(R.id.okay_btn).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
addPerson(nameText.getText().toString());
dismissDialog(MainActivity.ADD_DIALOG);
}
});
d.findViewById(R.id.cancel_btn).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
dismissDialog(MainActivity.ADD_DIALOG);
}
});
break;
default:
d = super.onCreateDialog(id);
break;
}
return d;
}
public void addPerson(String name){
// add the new data to the db
DBHelper helper = new DBHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DBHelper.C_NAME, name);
db.insert(DBHelper.TABLE_PEOPLE, null, cv);
db.close();
// update the view
updateAdapterData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
source code for database helper class:
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "myDatabase.db";
private static final int DB_VERSION = 1;
public static final String TABLE_PEOPLE = "people";
public static final String C_ID = "_id";
public static final String C_NAME = "name";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
final String sqlCreateTablePeople = "CREATE TABLE "
+ TABLE_PEOPLE + "( " + C_ID
+ " integer primary key autoincrement, " + C_NAME
+ " text not null);";
db.execSQL(sqlCreateTablePeople);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
final String sqlDropTablePeople = "DROP TABLE IF EXISTS " + TABLE_PEOPLE +
";";
db.execSQL(sqlDropTablePeople);
onCreate(db);
}
}
the layout for the main activity:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Person"
android:onClick="onAddClicked"
/>
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Person"
android:onClick="onDeleteClicked"
/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
></ListView>
</LinearLayout>
the layout for the add person dialog:
<?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" >
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/okay_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Okay"
/>
<Button
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel"
/>
</LinearLayout>
</LinearLayout>
Try using getCheckedItemIds()
public void onDeleteClicked(View view){
long[] positions = getListView().getCheckedItemIds();
SQLiteDatabase db = new DBHelper(this).getWritableDatabase();
for(int i = 0; i < positions.length; i++){
int rowsAffected = db.delete(DBHelper.TABLE_PEOPLE,
DBHelper.C_ID + " = " + positions[i], null);
}
db.close();
if(rowsAffected > 0)
updateAdapterData();
}
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.