ListView populated from DB not showing? - java

Records added to DB by calling DBAdapter insert method on another activity
No runtime errors, data seems to be added to db properly, however the listview object does not appear when app is being run
Main Activity
public class MainScreen extends ActionBarActivity implements View.OnClickListener
{
Button addNewButton;
Button sortByNameButton;
Button sortByBusinessButton;
Button sortByPhoneButton;
DBAdapter userDB;
ListView cardList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main_screen);
//declare buttons
addNewButton= (Button)findViewById(R.id.addNewButton);
sortByNameButton= (Button)findViewById(R.id.sortByNameButton);
sortByBusinessButton= (Button)findViewById(R.id.sortByBusinessButton);
sortByPhoneButton= (Button)findViewById(R.id.sortByPhoneButton);
//set onclick listeners
addNewButton.setOnClickListener(this);
//set button to font
addNewButton.setText("Add New");
sortByNameButton.setText("Sort by Name");
sortByBusinessButton.setText("Sort by Business");
sortByPhoneButton.setText("Sort by Phone #");
userDB = new DBAdapter(this);
userDB.open();
cardList=(ListView) findViewById(id.cardList);
populateListViewFromDB();
}
#Override
public void onDestroy(){
userDB.close();
}
private void populateListViewFromDB() {
Cursor cursor = userDB.getAllRows();
//allow activity to manage cursor lifetime (dont want memory leak)
startManagingCursor(cursor);
//map from cursor to view fields
String[] fromFieldNames = new String[]{DBAdapter.KEY_BUS_NAME};
int[] toViewIDs = new int[]{R.id.business_name};
//adapter to map out columns and rows of DB (deprecated, but it's okay)
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(
this, //context
R.layout.item_layout, //layout template
cursor, //cursor
fromFieldNames, //information
toViewIDs //where to put information
);
//String[] vals = {"me","you","he","she"};
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, layout.activity_main_screen, vals);
//set adapter to list view element
cardList.setAdapter(cursorAdapter);
}
}
DBAdapter class:
public class DBAdapter {
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_BUS_NAME = "BusinessName";
public static final String KEY_PERS_NAME = "PersonalName";
public static final String KEY_ADDRESS = "Address";
public static final String KEY_PHONE_NUM = "PhoneNum";
public static final String KEY_EMAIL = "Email";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_BUS_NAME = 1;
public static final int COL_PERS_NAME = 2;
public static final int COL_ADDRESS = 3;
public static final int COL_PHONE_NUM = 4;
public static final int COL_EMAIL = 5;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_BUS_NAME, KEY_PERS_NAME, KEY_ADDRESS, KEY_PHONE_NUM, KEY_EMAIL};
// DB info: its name, and the table we are using (just one).
public static final String DATABASE_NAME = "LocalCards";
public static final String DATABASE_TABLE = "CardInfo";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 3;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_BUS_NAME + " text, "
+ KEY_PERS_NAME + " text, "
+ KEY_ADDRESS + " text, "
+ KEY_PHONE_NUM + " text, "
+ KEY_EMAIL + " text"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
//Cursor x = db.rawQuery("SELECT "+KEY_BUS_NAME+" FROM " + DATABASE_TABLE,null);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
//db.execSQL(DATABASE_CREATE_SQL);
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public void insertRow(String bus_name, String pers_name, String address, String phone, String email) {
/*
* CHANGE 3:
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues values = new ContentValues();
values.put(KEY_BUS_NAME, bus_name);
values.put(KEY_PERS_NAME, pers_name);
values.put(KEY_ADDRESS, address);
values.put(KEY_PHONE_NUM, phone);
values.put(KEY_EMAIL, email);*/
// Insert it into the database.
//return db.insert(DATABASE_TABLE, null, values);
db.rawQuery("INSERT INTO " + DATABASE_TABLE + " (" + KEY_BUS_NAME + "," + KEY_PERS_NAME + "," +
KEY_ADDRESS + "," + KEY_PHONE_NUM + "," + KEY_EMAIL + ") VALUES (" + "'" + bus_name +
"','" + pers_name + "','" + address + "','" + phone + "','" + email + "');",null);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
//Cursor c = db.rawQuery("SELECT * FROM " + DATABASE_TABLE, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String bus_name, String pers_name, String address, String phone, String email) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_BUS_NAME, bus_name);
newValues.put(KEY_PERS_NAME, pers_name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_PHONE_NUM, phone);
newValues.put(KEY_EMAIL, email);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
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);
}
}
}
item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/business_name"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/personal_name"
android:layout_below="#+id/business_name"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/phone_number"
android:layout_below="#+id/business_name"
android:layout_alignParentRight="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/email"
android:layout_below="#+id/phone_number"
android:layout_alignParentRight="true" />
activity_main_screen.xml:
<?xml version="1.0" encoding="utf-8"?>
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Sort by Name"
android:id="#+id/sortByNameButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Sort by Business"
android:id="#+id/sortByBusinessButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/sortByNameButton" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Sort by Phone"
android:id="#+id/sortByPhoneButton"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/sortByBusinessButton" />
<Button
android:layout_width="75dp"
android:layout_height="50dp"
android:text="Add New"
android:id="#+id/addNewButton"
android:layout_alignBottom="#+id/sortByPhoneButton"
android:layout_toRightOf="#+id/sortByPhoneButton" />
<SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchBox"
android:layout_below="#+id/sortByNameButton"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/addNewButton"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cardList"
android:layout_alignParentRight="true"
android:layout_below="#+id/searchBox" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_below="#+id/searchBox"
android:layout_alignBottom="#+id/cardList"
android:layout_alignRight="#+id/searchBox"
android:layout_alignParentLeft="true" />

Related

App stops working when clicked on Button coded to save, refresh and search

I need help fixing a problem with my 3 buttons that don't work properly and I'm not sure how to fix it. The "Save" button is to keep my database save, the "Refresh" button is to clear, and the "Search" button is to find an existing database. My TextView shows the existing database after registered. These are my goals to accomplish.
Here are my code files:
XML File:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_verticsl_margin"
android:paddingBottom="#dimen/activity_verticsl_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dip"
android:gravity="center"
android:text="Registration"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtid"
android:hint="ID"
android:inputType="number"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtfirstname"
android:hint="#string/first_name"
android:layout_marginTop="5dip"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtlastname"
android:hint="#string/last_name"
android:layout_marginTop="5dip"
/>
<EditText
android:id="#+id/txtmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="#string/e_mail" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtuser"
android:hint="#string/username"
android:layout_marginTop="5dip"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txtpw"
android:hint="#string/password"
android:layout_marginTop="5dip"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsave"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
<Button
android:id="#+id/btnclear"
android:layout_width="212dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight=".30"
android:text="refresh"
android:textColor="#fff"
android:textSize="15dip"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="search"
android:textColor="#fff"
android:textSize="15dip"
android:id="#+id/btnsearch"
android:layout_weight="1"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"/>
</TableLayout>
Java File StudentRegistration.java:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StudentRegistration {
public static final String KEY_ROWID ="_id";
public static final String KEY_FNAME = "fname";
public static final String KEY_LNAME = "lname";
public static final String KEY_EMAIL = "email";
public static final String KEY_USER ="user";
public static final String KEY_PASS ="pass";
private static final String DATABASE_NAME = "StudentDB";
private static final String DATABASE_TABLE = "StudentTbl";
private static final int DATABASE_VERSION = 1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME,
null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_FNAME + " TEXT NOT NULL, " +
KEY_LNAME + " TEXT NOT NULL, " +
KEY_EMAIL + " TEXT NOT NULL, " +
KEY_USER + " TEXT NOT NULL, " +
KEY_PASS + " TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
onCreate(db);
}
}
public StudentRegistration(Context c) {
ourContext = c;
}
public StudentRegistration open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long savedata(String fname, String lname, String email, String user, String pass) {
ContentValues cv = new ContentValues();
cv.put(KEY_FNAME, fname);
cv.put(KEY_LNAME, lname);
cv.put(KEY_EMAIL, email);
cv.put(KEY_USER, user);
cv.put(KEY_PASS, pass);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData(){
String[] refresh = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, refresh, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iFName = c.getColumnIndex(KEY_FNAME);
int iLName = c.getColumnIndex(KEY_LNAME);
int iEmail = c.getColumnIndex(KEY_EMAIL);
int iUser = c.getColumnIndex(KEY_USER);
int iPass = c.getColumnIndex(KEY_PASS);
for(c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow)
+ " " + c.getString(iFName)
+ " " + c.getString(iLName)
+ " " + c.getString(iEmail)
+ " " + c.getString(iUser)
+ " " + c.getString(iPass)
+ "\n\n";
}
return result;
}
public String getFName(long l){
String[] getfname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getfname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String fname = c.getString(1);
return fname;
}
return null;
}
public String getLName(long l){
String[] getlname = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getlname, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String lname = c.getString(2);
return lname;
}
return null;
}
public String getEmail(long l){
String[] getemail = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getemail, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String email = c.getString(3);
return email;
}
return null;
}
public String getUser(long l){
String[] getuser = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getuser, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String user = c.getString(4);
return user;
}
return null;
}
public String getPass(long l){
String[] getpass = new String[] {KEY_ROWID, KEY_FNAME, KEY_LNAME,
KEY_EMAIL, KEY_USER, KEY_PASS};
Cursor c = ourDatabase.query(DATABASE_TABLE, getpass, KEY_ROWID + "="
+ 1, null, null, null, null);
if(c != null){
c.moveToFirst();
String pass = c.getString(5);
return pass;
}
return null;
}
}
and the java file MainActivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText FirstName, LastName, Email, UserName, Password, ID;
Button Save, Clear, Search;
TextView TxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstName = (EditText)findViewById(R.id.txtfirstname);
LastName = (EditText)findViewById(R.id.txtlastname);
Email = (EditText)findViewById(R.id.txtmail);
UserName = (EditText)findViewById(R.id.txtuser);
Password = (EditText)findViewById(R.id.txtpw);
TxtData =(TextView)findViewById(R.id.textView);
Save =(Button)findViewById(R.id.btnsave);
Clear=(Button)findViewById(R.id.btnclear);
Search=(Button)findViewById(R.id.btnsearch);
Search.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String search = ID.getText().toString();
Long l= Long.parseLong(search);
StudentRegistration mysearch = new
StudentRegistration(MainActivity.this);
mysearch.open();
String returnedFname = mysearch.getFName(l);
String returnedLname = mysearch.getLName(l);
String returnedEmail = mysearch.getEmail(l);
String returnedUser = mysearch.getUser(l);
String returnedPass = mysearch.getPass(l);
mysearch.close();
FirstName.setText(returnedFname);
LastName.setText(returnedLname);
Email.setText(returnedEmail);
UserName.setText(returnedUser);
Password.setText(returnedPass);
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname = FirstName.getText().toString();
String lname = LastName.getText().toString();
String email = Email.getText().toString();
String user = UserName.getText().toString();
String pass = Password.getText().toString();
StudentRegistration save = new StudentRegistration(MainActivity.this);
save.open();
save.savedata(fname, lname, email, user, pass);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
Clear.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
StudentRegistration refresh = new StudentRegistration(MainActivity.this);
refresh.open();
String data = refresh.getData();
refresh.close();
TxtData.setText(data);
FirstName.setText("");
LastName.setText("");
Email.setText("");
UserName.setText("");
Password.setText("");
ID.setText("");
}
});
}
}
My Manifest File:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.classifiedinformation">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
How can I accomplish my goals?
First of all some hints about what went wrong would have been nice.
You need to initialize ID like you did with the other EditText's.
Add ID = findViewById(R.id.txtid); to your onCreate(Bundle savedInstanceState) method.
The first thing I got when clicking on 'Save' was the following:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference
at com.citiesapps.myapplication.MainActivity$2.onClick(MainActivity.java:76)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
As the stacktrace states you are trying to invoke a method on a null-object in this case 'ID'.
After analyzing your code, i saw your are executing setText on an editText that is not initialized in your java class.
Probable editText code is:
ID.setText(""); Here ID is not initialized with xml file.
Use ID = findViewById(R.id.txtid); for initializing the ID field
Check all editText initialization. Then use that editText.
Thanks :)

I have a retention window, but the data is not saved. How to store the value of boolean in the database?

Hello everybody. I'm trying to make an application that works with the database. I have a retention window, but the data is not saved. How to save the value boolean from check-box into the database?
How to resole this problem?
This is code of Database
public class DataBase extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "DataOfSchedule.db";
public static final String TABLE_NAME = "DataOfSchedule_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "AGE";
public static final String COL_4 = "SEX_MALE";
public static final String COL_7 = "SEX_FEMALE";
public static final String COL_5 = "WEIGHT";
public static final String COL_6 = "HEIGHT";
public static final String COL_8 = "TRAUMA";
public DataBase(Context context){
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY," +
" NAME TEXT," +
" AGE INTEGER NOT NULL DEFAULT 0 , " +
"SEX_MALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\") ," +
"SEX_FEMALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"TRAUMA NOT NULL TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"WEIGHT INTEGER NOT NULL DEFAULT 0," +
"HEIGHT INTEGER NOT NULL DEFAULT 0)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
}
public boolean insertData(String name, Integer age, String sex_male, String sex_female, Integer weight, Integer height, String trauma){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,age);
contentValues.put(COL_4,sex_male);
contentValues.put(COL_5,weight);
contentValues.put(COL_6,height);
contentValues.put(COL_7,sex_female);
contentValues.put(COL_8,trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
//To Check Whether Data is Inserted in DataBase
if(result==-1){
return false;
}else{
return true;
}
}
public Cursor getALLData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
return res;
}
}
It is code of Activity which inserts data
public class InsertData extends AppCompatActivity {
DataBase myDb;
EditText txtName, txtAge , txtWeight, txtHeight;
CheckBox boxSex_male,boxSex_female,boxTrauma;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_data);
myDb = new DataBase(this);
txtName = (EditText) findViewById(R.id.name);
txtAge = (EditText) findViewById(R.id.age);
boxSex_male = (CheckBox) findViewById(R.id.sex_m);
boxTrauma = (CheckBox) findViewById(R.id.trauma);
boxSex_female = (CheckBox) findViewById(R.id.sex_f);
txtWeight = (EditText) findViewById(R.id.weight);
txtHeight = (EditText) findViewById(R.id.height);
btnClick = (Button) findViewById(R.id.InsertBtn);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ClickMe();
}
});
if(boxTrauma.isChecked()){
boxTrauma.setChecked(true);
}else {
boxTrauma.setChecked(false);
}
if(boxSex_female.isChecked()){
boxSex_female.setChecked(true);
}else {
boxSex_female.setChecked(false);
}
if(boxSex_male.isChecked()){
boxSex_male.setChecked(true);
}else {
boxSex_male.setChecked(false);
}
}
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
String sex_male = boxSex_male.getText().toString();
String trauma = boxTrauma.getText().toString();
String sex_female = boxSex_female.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData(name,age_int,sex_male,sex_female,weight_int,height_int,trauma);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}
}
It is my HTML
<ScrollView 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:padding="16dp"
tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/insert_heading"
android:layout_gravity="center"
android:textSize="16dp"
android:textColor="#021aee"/>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_name"/>
<EditText
android:id="#+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_age"
android:numeric="integer"/>
<EditText
android:id="#+id/weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_weight"
android:numeric="integer"/>
<EditText
android:id="#+id/height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_height"
android:numeric="integer"/>
<TextView
android:padding="10dp"
android:text="#string/insert_sex"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/sex_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/male"/>
<CheckBox
android:id="#+id/sex_f"
android:text="#string/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:padding="10dp"
android:text="#string/insert_trauma"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/trauma"
android:text="#string/insert_trauma_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/InsertBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#string/insert_button"
android:textColor="#f2fde4"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
Lets break this problem down into a couple of Posts. First we can deal with the SQLite part of the code then you can post a new question about inserting values--there is just to much code to cover and make this understandable.
Change your code in your DataBase class (BTW: Not a good name!)
Give the variable names for the columns an understandable name. Who can remember what COL_6 is? Also consider that these probably do not need to be public.
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_AGE = "AGE";
public static final String COL_GENDER = "GENDER";
public static final String COL_WEIGHT = "WEIGHT";
public static final String COL_HEIGHT = "HEIGHT";
public static final String COL_TRAUMA = "TRAUMA";
You might not want to check if the table already exists, but I added the check anyway. I also made ID an AUTOINCREMENT column.
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT," +
COL_AGE + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER + " INTEGER NOT NULL DEFAULT 0, " +
COL_TRAUMA + " INTEGER NOT NULL DEFAULT 0, " +
COL_WEIGHT + " INTEGER NOT NULL DEFAULT 0, " +
COL_HEIGHT + " INTEGER NOT NULL DEFAULT 0);");
}
Change the insertData method to accommodate the changes to the static final variables for the columns and the type changes of the parameters:
public boolean insertData(String name, Integer age, Integer sex_male, Integer weight, Integer height, Integer trauma){
boolean success = false;
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_AGE, age);
contentValues.put(COL_GENDER, sex_male);
contentValues.put(COL_WEIGHT, weight);
contentValues.put(COL_HEIGHT, height);
contentValues.put(COL_TRAUMA, trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
if(result != -1) success = true;
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
return success;
}
Also note, no need to get a Writeable database in your getALLData() method:
public Cursor getALLData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME, null);
return res;
}
Now post a new question on how the populate the database from your Activity and we can go from there...

How would I create new activity where I would have option to add new items from database?

I have created database following this tutorial, and I have created one button in main activity which will take users to another activity where they would add some new items. But I don't know how would I do this with ArrayList because I want to add new items in ListView. I want something like this to have in my application. Any help would be appricieated.
Here's the code of DataBase:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "itemManager";
// Contacts table name
private static final String TABLE_ITEMS = "items";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_PRICE = "price";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_PRICE + " TEXT" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new item
void addItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, item.getTitle()); // Title Name
values.put(KEY_PRICE, item.getPrice()); // Price
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
db.close(); // Closing database connection
}
// Getting item
Item getItem(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_TITLE, KEY_PRICE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return item
return item;
}
// Getting All Items
public List<Item> getAllItems() {
List<Item> itemsList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setTitle(cursor.getString(1));
item.setPrice(cursor.getString(2));
// Adding contact to list
itemsList.add(item);
} while (cursor.moveToNext());
}
// return items list
return itemsList;
}
// Updating single item
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, item.getTitle());
values.put(KEY_PRICE, item.getPrice());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
}
// Deleting single item
public void deleteItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
db.close();
}
// Getting items Count
public int getItemsCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
and here is the code of MainActivity:
public class MainActivity extends BaseActivity {
Button addItem;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_container);
// inflate the custom activity layout
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View activityView = layoutInflater.inflate(R.layout.activity_main, null,false);
frameLayout.addView(activityView);
// Setting toolbar
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
DatabaseHandler db = new DatabaseHandler(this);
addItem = (Button) findViewById(R.id.button1);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
Here's my Main Activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<Button
android:id="#+id/button1"
style="#style/MyCustomButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/button" />
<ListView
android:id="#+id/list"
android:layout_margin="5dp"
android:layout_below="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_centerHorizontal="true"
android:divider="#color/list_divider_row"
android:dividerHeight="10.0sp"
android:listSelector="#drawable/list_row_selector" >
</ListView>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/listView1"
android:layout_alignRight="#+id/listView1"
android:layout_below="#+id/app_bar"
android:padding="10dp" >
<TextView
android:id="#+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:text="Items"
android:textColor="#474747"
android:textSize="16sp" />
<TextView
android:id="#+id/item_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/item_text"
android:text="(2)"
android:textColor="#474747"
android:textSize="14sp" />
<TextView
android:id="#+id/total_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Rs. 5700"
android:textColor="#000000"
android:textSize="20dp" />
</RelativeLayout>
</RelativeLayout>
In a nutshell, you need to pass the "result" of adding an item back to the main activity. Then, if there was an item added, you should call your adapter to update the adapter data.
// Your previous code
addItem = (Button) findViewById(R.id.button1);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent, ADD_ITEM_REQ_CODE);
}
});
// Then handle the result
public void onActivityResult(int reqCode, int resultCode, Intent data){
if (reqCode == ADD_ITEM_REQ_CODE && resultCode == RESULT_OK){
// get your ListView adapter and update data
mListAdapter.notifyDataSetChanged();
}
}
Your second activity, the one that adds an item should call setResult(RESULT_OK) when the item was added successfully and setResult(RESULT_CANCELLED) otherwise.
There some other things with your code, for instance, where do you populate your ListView? Normally, you would get the instance though a findViewById and set an adapter to that ListView, with the corresponding data.
Honestly, I think you should have a look to the tutorials again, specially these:
http://developer.android.com/training/basics/intents/result.html
http://developer.android.com/guide/topics/ui/layout/listview.html

saving image in sqlite db using a save button

I'm a newbie in developing an android app and I am currently developing cooking application. I want to add a new recipe to my db with recipe name, ingredients, procedures, category, notes and photo. But the problem is when I add photo from camera or gallery, it stop working and I want to view the image taken to an imageview and save it to db using a save button. But please help me. I don't know what to do with my project.
MY DBAdapter
package com.elasandesu.quickeasykitchenv3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_RNAME = "rname";
public static final String KEY_RCAT = "rcat";
public static final String KEY_RING = "ring";
public static final String KEY_RSTEPS = "rsteps";
public static final String KEY_RNOTE = "rnote";
public static final String KEY_RPHOTO = "rphoto";
//public static final String KEY_RPHOTONME = "rphotornme";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_RNAME = 1;
public static final int COL_RCAT = 2;
public static final int COL_RING = 3;
public static final int COL_RSTEPS = 4;
public static final int COL_RNOTE = 5;
public static final int COL_RPHOTO = 6;
//public static final int COL_RPHOTONME =7;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_RNAME, KEY_RCAT, KEY_RING, KEY_RSTEPS, KEY_RNOTE, KEY_RPHOTO};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Quick.sqlite";
public static final String DATABASE_TABLE = "recipe";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 5;
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public void onCreate(SQLiteDatabase db) {
String CREATE_RECIPE_TABLE = "CREATE TABLE " + DATABASE_TABLE + "("
+ KEY_ROWID + " INTEGER PRIMARY KEY," + KEY_RNAME + " TEXT,"
+ KEY_RCAT + " TEXT," + KEY_RING+ " TEXT," + KEY_RSTEPS + " TEXT,"
+ KEY_RNOTE + " TEXT," + KEY_RPHOTO + " BLOB" + ")";
db.execSQL(CREATE_RECIPE_TABLE);
}
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_RNAME, rName);
initialValues.put(KEY_RCAT, rCat);
initialValues.put(KEY_RING, rIng);
initialValues.put(KEY_RSTEPS, rSteps);
initialValues.put(KEY_RNOTE, rNote);
//initialValues.put(KEY_RPHOTO, rPhoto);
//initialValues.put(KEY_RPHOTONME, rPhotonme);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//Get specific row by category
public Cursor getCateg (String categ) throws SQLException {
String where = "SELECT * FROM recipe where rcat=\""+categ+"\"";
Cursor c = db.rawQuery(where, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
//KEY_RCAT + " = \'" + categ + " \'";
//"select * from contacts where id="+id+"", null
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String rName, String rCat, String rIng, String rSteps, String rNote) {//byte[] rPhoto
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_RNAME, rName);
newValues.put(KEY_RCAT, rCat);
newValues.put(KEY_RING, rIng);
newValues.put(KEY_RSTEPS, rSteps);
newValues.put(KEY_RNOTE, rNote);
//newValues.put(KEY_RPHOTO, rPhoto);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteAssetHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
}
Activity Code
package com.elasandesu.quickeasykitchenv3;
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Addrecipe extends Activity implements OnItemSelectedListener{
String[] cat = {"BEEF","CHICKEN",
"PORK", "FISH", "VEGETABLES"};
private static final int CAMERA_REQUEST = 1;
private static final int PICK_FROM_GALLERY = 2;
private String selectedImagePath;
String DB_NAME = Environment.getExternalStorageDirectory() + "/Quick.sqlite";
String TABLE_NAME = "recipe";
ImageView recphoto;
DBAdapter db;
EditText recname, recing, recsteps, recnote;
Spinner spinner1;
TextView category;
Button save, reset, upload;
public static String rcat = " ";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addrecipe);
category = (TextView) findViewById(R.id.categorytxtview);
spinner1 = (Spinner) findViewById(R.id.categorysp);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, cat);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter_state);
spinner1.setOnItemSelectedListener(this);
save = (Button) findViewById(R.id.savebtn);
reset = (Button) findViewById(R.id.resetbtn);
recname = (EditText) findViewById(R.id.recipename);
recing = (EditText) findViewById(R.id.ingredient);
recnote = (EditText) findViewById(R.id.note);
recsteps = (EditText) findViewById(R.id.procedure);
recphoto= (ImageView) findViewById(R.id.image);
openDB();
final String[] option = new String[] { "Take from Camera", "Select from Gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item, option);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Log.e("Selected Item", String.valueOf(which));
if (which == 0) {
callCamera();
}
if (which == 1) {
callGallery();
}
}
});
final AlertDialog dialog = builder.create();
Button addImage = (Button) findViewById(R.id.uploadbtn);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.show();
}
});
}
//insert activity here :D
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case CAMERA_REQUEST:
Bundle extras= data.getExtras();
if (extras != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage.compress(CompressFormat.PNG, 0, stream);
byte[] bytes = stream.toByteArray();
recphoto.setImageBitmap(selectedImage);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
recphoto.setImageURI(selectedImageUri);
Intent i = new Intent(Addrecipe.this,
Addrecipe.class);
startActivity(i);
finish();
}
break;
}
}
#SuppressWarnings("deprecation")
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**
* open camera method
*/
public void callCamera() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 150);
cameraIntent.putExtra("crop", "true");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
/**
* open gallery method
*/
public void callGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
startActivityForResult(
Intent.createChooser(intent, "Complete action using"),
PICK_FROM_GALLERY);
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
db = new DBAdapter(this);
db.open();
}
private void closeDB() {
db.close();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinner1.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public void saveHasBeenClicked (View v) {
String rName = recname.getText().toString();
String rIng = recing.getText().toString();
String rSteps =recsteps.getText().toString();
String rNote = recnote.getText().toString();
String rCat = (String) spinner1.getSelectedItem();
long newId = db.insertRow(rName,"\n"+ rCat," \n "+ rIng," \n" + rSteps, rNote);
Cursor cursor = db.getRow(newId);
displayRecordSet(cursor);
Intent evilIntent = new Intent(Addrecipe.this, Selected.class);
startActivity(evilIntent);
}
public void onClick_ClearAll(View v) {
db.deleteAll();
Toast.makeText(getBaseContext(), "Cleared ", Toast.LENGTH_LONG).show();
}
// Display an entire record set to the screen.
private void displayRecordSet(Cursor cursor) {
String message = "";
// populate the message from the cursor
// Reset cursor to start, checking to see if there's data:
if (cursor.moveToFirst()) {
do {
// Process the data:
int id = cursor.getInt(DBAdapter.COL_ROWID);
String rName = cursor.getString(DBAdapter.COL_RNAME);
String rCat = cursor.getString(DBAdapter.COL_RCAT);
String rIng = cursor.getString(DBAdapter.COL_RING);
String rSteps = cursor.getString(DBAdapter.COL_RSTEPS);
String rNote = cursor.getString(DBAdapter.COL_RNOTE);
// Append data to the message:
message += "id=" + id
+", Recipe Name : " + rName
+", Category : " + rCat
+", Ingredients : " + rIng
+", Procedure: " + rSteps
+", Note: " + rNote
+"\n";
} while(cursor.moveToNext());
Toast.makeText(getBaseContext(), "Save Has Been Clicked "+ message, Toast.LENGTH_LONG).show();
}
// Close the cursor to avoid a resource leak.
cursor.close();
}
}
And the XML file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/clr"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/nb"
android:onClick="displayClicked"
android:screenOrientation="landscape"
tools:ignore="HardcodedText" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="1462dp" >
<EditText
android:id="#+id/recipename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/recipenametxtview"
android:layout_alignBottom="#+id/recipenametxtview"
android:layout_alignParentRight="true"
android:layout_marginRight="70dp"
android:ems="10"
android:hint="Type the Recipe Name"
tools:ignore="TextFields" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/categorytxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/recipenametxtview"
android:layout_below="#+id/recipename"
android:layout_marginTop="50dp"
android:text="Category:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/ingtxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/categorytxtview"
android:layout_below="#+id/categorysp"
android:layout_marginTop="42dp"
android:text="Ingredients:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="#+id/categorysp"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignLeft="#+id/recipename"
android:layout_alignRight="#+id/recipename"
android:layout_alignTop="#+id/categorytxtview" />
<TextView
android:id="#+id/notetxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="253dp"
android:text="Note:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/ingredient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingtxtview"
android:layout_alignRight="#+id/categorysp"
android:layout_below="#+id/ingtxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type Here the Ingredients : e.g. 1 kilo of Flour"
android:inputType="text"
android:singleLine="false"
tools:ignore="TextFields" />
<EditText
android:id="#+id/procedure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/proceduretxtview"
android:layout_alignRight="#+id/ingredient"
android:layout_below="#+id/proceduretxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Type in this format 1.) procedure 1 [newline] 2.) procedure 2"
tools:ignore="TextFields" />
<EditText
android:id="#+id/note"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/notetxtview"
android:layout_alignRight="#+id/procedure"
android:layout_below="#+id/notetxtview"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Includes information, cautions and other health information"
tools:ignore="TextFields" />
<TextView
android:id="#+id/recipenametxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/itemRname"
android:layout_marginLeft="62dp"
android:layout_marginTop="67dp"
android:text="Recipe Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phototxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/note"
android:layout_below="#+id/note"
android:layout_marginTop="101dp"
android:text="Photo:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/proceduretxtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/ingredient"
android:layout_below="#+id/ingredient"
android:layout_marginTop="172dp"
android:text="Procedure:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/uploadbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/phototxtview"
android:layout_alignBottom="#+id/phototxtview"
android:layout_toRightOf="#+id/ingtxtview"
android:text="Upload Photo" />
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_below="#+id/uploadbtn"
android:layout_marginTop="42dp"/>
<Button
android:id="#+id/resetbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/savebtn"
android:layout_alignBottom="#+id/savebtn"
android:layout_alignRight="#+id/note"
android:layout_marginRight="55dp"
android:onClick="onClick_ClearAll()"
android:text="Reset" />
<Button
android:id="#+id/savebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/uploadbtn"
android:layout_below="#+id/image"
android:layout_marginTop="56dp"
android:onClick="saveHasBeenClicked"
android:text="Save" />
</RelativeLayout>
</ScrollView>
please help me.. it will be a great help.

Populate TableLayout from SQLite-database

I want to display a simple list in a table view which I've created and included below but can't see how i capture the data which I'm getting back from my query to populate this.
I have a database adapter which i think is working:
public class DbAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_ITEM_NAME = "name";
public static final String KEY_ITEM_COST = "cost";
public static final String KEY_ITEM_PRICE_VALUE = "price";
public static final String KEY_ITEM_POSTAGE = "postage";
public static final String KEY_ACTUAL_PL = "profitloss";
private static final String TAG = "DbAdapter";
private static final String DATABASE_NAME = "eBaySalesDB";
private static final String DATABASE_TABLE = "actualSales";
private static final int DATABASE_VERSION = 1;
private DatabaseHelper mDbHelper;
private SQLiteDatabase db;
//private static final String DATABASE_CREATE = "create table if not exists"
// + DATABASE_TABLE + "(" + KEY_ROWID
// + "integer primary key autoincrement, " + KEY_ITEM_NAME
// + "text not null," + KEY_ITEM_COST + "text not null,"
// + KEY_ITEM_PRICE_VALUE + "text not null," + KEY_ITEM_POSTAGE
// + "text not null," + KEY_ACTUAL_PL + "text not null);";
private static final String DATABASE_CREATE = "create table if not exists "
+ DATABASE_TABLE + "(" + KEY_ROWID
+ " integer primary key autoincrement, " + KEY_ITEM_NAME
+ " text not null," + KEY_ITEM_COST + " text not null,"
+ KEY_ITEM_PRICE_VALUE + " text not null," + KEY_ITEM_POSTAGE
+ " text not null," + KEY_ACTUAL_PL + " text not null);";
private final Context mCtx;
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);
}
#Override
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 " + DATABASE_TABLE);
onCreate(db);
}
}
/**
* constructor - takes the context to allow the database to be opened /
* created
*
* #param ctx
*/
public DbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* open up the database. If it cannot be opened it will try to create a new
* instance of the database. if this can't be created it will throw an
* exception
*
* #return this (self reference)
* #throws SQLException
* (if the database can't be opened or closed.
*/
public DbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
db = mDbHelper.getWritableDatabase();
return this;
}
/**
* Method to close the code off to others
*/
public void close() {
mDbHelper.close();
}
/**
* method to insert a record into the database
*/
public long insertRecord(String name, String cost, String price,
String postage, String profitloss) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ITEM_NAME, name);
initialValues.put(KEY_ITEM_COST, cost);
initialValues.put(KEY_ITEM_PRICE_VALUE, price);
initialValues.put(KEY_ITEM_POSTAGE, postage);
initialValues.put(KEY_ACTUAL_PL, profitloss);
return db.insert(DATABASE_TABLE, null, initialValues);
}
/**
* method to delete a record from the database
*/
public boolean deleteRecord(long id) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + id, null) > 0;
}
/**
* method to retrieve all the records
*/
public Cursor getAllRecords() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, null, null, null, null,
null, null);
}
/**
* method to retrieve a particular record
*/
public Cursor getRecord(long id) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_ITEM_NAME, KEY_ITEM_COST, KEY_ITEM_PRICE_VALUE,
KEY_ITEM_POSTAGE, KEY_ACTUAL_PL }, KEY_ROWID + "=" + id, null,
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* method to update a record
*/
public boolean updateRecord(long id, String name, String cost,
String price, String postage, String profitloss) {
ContentValues args = new ContentValues();
args.put(KEY_ITEM_NAME, name);
args.put(KEY_ITEM_COST, cost);
args.put(KEY_ITEM_PRICE_VALUE, price);
args.put(KEY_ITEM_POSTAGE, postage);
args.put(KEY_ACTUAL_PL, profitloss);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
I've also created an Activity to activate a button to view the data which a user can press. It's the third button, viewRecordsDB, which I'm having trouble getting to function....
public class ActualSalesTracker extends Activity implements OnClickListener {
DbAdapter db = new DbAdapter(this);
Button BtnSalesCal, BtnAddRecordDB, BtnViewRecordsDB;
EditText item_name, item_cost, item_price_value, item_postage, actual_pl;
SalesProfitLossCal actSalesCal = new SalesProfitLossCal();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actual_sales_tracker);
Button salesCalBtn = (Button) findViewById(R.id.BtnSalesCal);
// register the click event with the sales calculating profit/loss
// button
salesCalBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// get EditText by id to represent the value of the item stock
// cost and store it as a double
EditText itemCostString = (EditText) findViewById(R.id.item_cost);
String ic = itemCostString.getText().toString();
double itemCost = Double.valueOf(ic).doubleValue();
// get EditText by id to represent the value of the post and
// packaging cost and store it as a double
EditText itemPostageString = (EditText) findViewById(R.id.item_postage);
String ipapc = itemPostageString.getText().toString();
double itemPostage = Double.valueOf(ipapc).doubleValue();
// get EditText by id to represent the value of the selling
// price and store it as a double
EditText itemPriceValueString = (EditText) findViewById(R.id.item_price_value);
String sp = itemPriceValueString.getText().toString();
double itemPriceValue = Double.valueOf(sp).doubleValue();
double actTotalCost = actSalesCal.ActTotalCostCal(itemCost,
itemPostage, itemPriceValue);
double actualProfitLoss = actSalesCal
.calculateProfitLossGenerated(itemPriceValue,
actTotalCost);
String ActualProfitLossString = String.format(
"You made £ %.2f", actualProfitLoss);
TextView ActualProfitLossView = (TextView) findViewById(R.id.yourActualPL);
ActualProfitLossView.setText(ActualProfitLossString);
}
});
// activate the add record button
Button addRecordDB = (Button) findViewById(R.id.BtnAddRecordDB);
// register the click event with the add record button
addRecordDB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText nameText = (EditText) findViewById(R.id.item_name);
String name = nameText.getText().toString();
EditText costText = (EditText) findViewById(R.id.item_cost);
String cost = costText.getText().toString();
EditText priceText = (EditText) findViewById(R.id.item_price_value);
String price = priceText.getText().toString();
EditText postageText = (EditText) findViewById(R.id.item_postage);
String postage = postageText.getText().toString();
TextView profitlossText = (TextView) findViewById(R.id.actual_pl);
String profitloss = profitlossText.getText().toString();
db.open();
long id = db.insertRecord(name, cost, price, postage,
profitloss);
db.close();
}
});
// activate the view record button
Button viewRecordsDB = (Button) findViewById(R.id.BtnViewRecordsDB);
// register the click event with the add record button
viewRecordsDB.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.open();
Cursor id = db.getAllRecords();
db.close();
// for (id.moveToFirst(); !id.moveToLast(); id.moveToNext()){
// id.getString(
// result = result +
// }
}
});
}
#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;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I wanted it to populate the following view file on xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout
android:id="#+id/table_sales"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow android:id="#+id/tableRow1" >
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/item_name"
android:layout_weight="1" >
</TextView>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/profit_loss"
android:layout_weight="1" >
</TextView>
</TableRow>
</TableLayout>
<TextView
android:id="#+id/sales_info"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="get info from database" >
</TextView>
</LinearLayout>
and i have a java file set up to activate this :
public class ViewSales extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_sales);
}
#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;
}
Use a ListView rather than a TableLayout. A TableLayout is usually used to display static, pre-defined content, while a ListView is much more dynamic and can directly handle the Cursor you get from the SQLite-db: Learn How to Create ListView From SQLite Database in Android Development

Categories