no such column: KEY_PUBNAME - java

Im making an app which stores data in an SQLite database. I want to be able to add, edit and delete data from this database. I can app to it no problem. I am currently working on trying to delete from the database but I keep getting the same error.
(1) no such column: KEY_PUBNAME
Here is my Java file:
package com.example.beer_budget3;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
//Need to update delete layout after deleting row
public class Delete extends Activity
{
//Creating an object name for my database
DatabaseSetup2 db = new DatabaseSetup2(this);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the delete XML file
setContentView(R.layout.delete);//Put one of these in each class
//Delete button that has been created in the delete XML file
Button delete = (Button)findViewById(R.id.deletepub);
delete.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//This page links back to the MainMenu page
Intent i = new Intent(Delete.this, MainMenu.class);
//Calling the deleting function
deleting(v);
//Activating the intent
startActivity(i);
}
});
}
public void deleting(View v)
{
db.open();
//Save user input into rowId
EditText pnametxt = (EditText)findViewById(R.id.delete1);
//Open the database
String pname2 = pnametxt.getText().toString();
db.deletePub(pname2);
db.close();
}
}
Here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
android:background="#color/background"
tools:context="com.example.beer_budget3.delete" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="85dp"
android:layout_marginBottom="20dp"
android:text="#string/app_name"
android:textColor="#color/blue"
android:textStyle="bold"
android:textSize="30sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/details"
android:layout_marginLeft="50dp"
android:layout_marginBottom="30dp"
android:textSize="25sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/pub"
android:textSize="20sp"/>
<EditText
android:id="#+id/delete1"
android:inputType="text"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/deletepub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_marginLeft="130dp"
android:onClick="delete"
android:text="#string/delete" />
</LinearLayout>
And here is my database adapter:
package com.example.beer_budget3;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.EditText;
public class DatabaseSetup2
{
// These are the names of the columns the table will contain
public static final String KEY_ROWID = "_id";
public static final String KEY_PUBNAME = "Pub_Name";
public static final String KEY_LOCATION = "Location";
public static final String KEY_PRICE = "Price";
private static final String DATABASE_NAME = "CillinsAssignment";
private static final String DATABASE_TABLE = "Beer_Budget";
private static final int DATABASE_VERSION = 1;
// This is the string containing the SQL database create statement
private static final String DATABASE_CREATE = "CREATE TABLE " + DATABASE_TABLE +
"( " +KEY_ROWID + " integer primary key autoincrement, "+KEY_PUBNAME +" text not
null, "+KEY_LOCATION+" text not null, "+KEY_PRICE+ " text not null);";
private final Context context;
private DatabaseHelper DBHelper;
// utility class that makes it easy to create and maintain an SQLLite database
private SQLiteDatabase db;//Class containing methods to manage a local SQLLite Database file
// constructor for your class
public DatabaseSetup2(Context ctx)
{
// Context is a way that Android transfers info about Activities and apps.
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
// This is the helper class that will create the dB if it doesn’t exist and
//upgrades it if the structure has changed. It needs a constructor, an
//onCreate() method and an onUpgrade() method
private static class DatabaseHelper extends SQLiteOpenHelper
{
// constructor for your dB helper class. This code is standard. You’ve set
//up the parameter values for the constructor already…database name,etc
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
// The “Database_create” string below needs to contain the SQL
//statement needed to create the dB
try
{
db.execSQL(DATABASE_CREATE);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// If you want to change the structure of your database, e.g.
// Add a new column to a table, the code will go head..
//This method only triggers if the database version number has
//increased
Log.w("test", "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS Beer_Budget");
onCreate(db);
}
}// end of the help class
// from here on, include whatever methods will be used to access or change data
//in the database
//---opens the database--- any activity that uses the dB will need to do this
public DatabaseSetup2 open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database--- any activity that uses the dB will need to do this
public void close()
{
DBHelper.close();
}
//---insert a pub into the database---
public long insertPub(String Pub_Name, String Location, String Price)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_PUBNAME, Pub_Name);
initialValues.put(KEY_LOCATION, Location);
initialValues.put(KEY_PRICE, Price);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
//---retrieves all the rows---
public Cursor getAllPubs()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE},
null,
null,
null,
null,
null);
}
//---retrieves a particular row---
public Cursor getPub(int _id) throws SQLException
{
Cursor mCursor = db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_PUBNAME,
KEY_LOCATION,
KEY_PRICE
},
KEY_ROWID + "=" + _id,
null,
null,
null,
null
);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
KEY_PUBNAME is clearly declared in the database adapter.
Any help would be great.

If you see your DatabaseHelper, you've defined following:
//---deletes a particular pub---
public boolean deletePub(String Pub_Name)
{
//delete statement. If any rows deleted (i.e. >0), returns true
return db.delete(DATABASE_TABLE, "KEY_PUBNAME = "+ Pub_Name+" ", null) > 0;
}
The keyname you've mentioned is KEY_PUBNAME. However where you've created the table, the keyname you've defined is Pub_Name. Over here:
public static final String KEY_PUBNAME = "Pub_Name";
That's why its not found. KEY_PUBNAME is the variable you've declared and not the name of the column. You may want to try to change it in db.delete statement.

Related

Layout shows only CheckBox, does not show the ImageView etc

I have added layout and classes below. The problem I am having is that although I have specified it in the layout, I cannot see the ImageView and TextViews other than checkbox. Layout shows only CheckBox, does not show the ImageView, the TextView and second TextView!
Project page CheckBox clicked:
Project page on emulator:
Project page in AndroidStudio:
Drink Activity Layout is
XML:
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
tools:context="com.hfad.starbuzz.DrinkActivity" >
<ImageView
android:id="#+id/photo"
android:layout_width="190dp"
android:layout_height="190dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<CheckBox android:id="#+id/favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/favorite"
android:onClick="onFavoriteClicked" />
</LinearLayout>
Drink Activity:
package com.hfad.starbuzz;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class DrinkActivity extends Activity {
public static final String EXTRA_DRINKID = "drinkId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
//Getting a drink from an intent
int drinkId = (Integer) Objects.requireNonNull(getIntent().getExtras()).getInt(EXTRA_DRINKID);
//Creating a cursor
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getReadableDatabase();
Cursor cursor = db.query("DRINK",
new String[]{"NAME","DESCRIPTION","IMAGE_RESOURCE_ID","FAVORITE"},
"_id = ?",
new String[]{Integer.toString(drinkId)},null,null,null);
//Move to the first entry in the cursor
if (cursor.moveToFirst()) {
//Get the drink details from the cursor
String nameText = cursor.getString(0);
String descriptionText = cursor.getString(1);
int photoId = cursor.getInt(2);
boolean isFavorite = (cursor.getInt(3) == 1);
//Filling in the name of the drink
TextView name = (TextView) findViewById(R.id.name);
name.setText(nameText);
//Filling in the description of the drink
TextView description = (TextView) findViewById(R.id.description);
description.setText(descriptionText);
//Filling the drink image
ImageView photo = (ImageView) findViewById(R.id.photo);
photo.setImageResource(photoId);
photo.setContentDescription(nameText);
//Filling the Flag for Your Favorite Drink
CheckBox favorite = (CheckBox)findViewById(R.id.favorite);
favorite.setChecked(isFavorite);
}
cursor.close();
db.close();
} catch (SQLiteException e) {
Toast toast = Toast.makeText(this,
" unavailable",
Toast.LENGTH_SHORT);
toast.show();
}
}
//Database refresh on click of a checkbox
public void onFavoriteClicked(View view){
int drinkId = (Integer) Objects.requireNonNull(getIntent().getExtras()).getInt(EXTRA_DRINKID);
//Getting the value of a checkbox
CheckBox favorite = (CheckBox) findViewById(R.id.favorite);
ContentValues drinkValues = new ContentValues();
drinkValues.put("FAVORITE", favorite.isChecked());
//Retrieving a database link and updating the FAVORITE column
SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
try {
SQLiteDatabase db = starbuzzDatabaseHelper.getWritableDatabase();
db.update("DRINK",
drinkValues,
"_id = ?",
new String[] {Integer.toString(drinkId)});
db.close();
} catch(SQLiteException e) {
Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
toast.show();
}
}
}
StarbuzzDatabaseHelper:
package com.hfad.starbuzz;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StarbuzzDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "starbuzz"; // Database name
//Increasing the version number means that the SQLite Assistant will know to update the database.
private static final int DB_VERSION = 12; // Database version and version number.
StarbuzzDatabaseHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
//The onCreate () method is called when the database is first created;
//We use it to create a table and insert data
public void onCreate(SQLiteDatabase db){
updateMyDatabase(db, 0, DB_VERSION);
}
//The updateMyDatabase () method is called from onUpgrade () with parameters passed.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateMyDatabase(db, oldVersion, newVersion);
}
//It is necessary to insert the data of several drinks,
//so we created a separate method for inserting.
private static void insertDrink(SQLiteDatabase db, String name,
String description, int resourceId) {
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceId);
db.insert("DRINK", null, drinkValues);
}
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 1) {
db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Espresso and steamed milk", R.drawable.latte);
insertDrink(db, "Cappuccino", "Espresso, hot milk and steamed-milk foam",
R.drawable.cappuccino);
insertDrink(db, "Filter", "Our best drip coffee", R.drawable.filter);
}
//This code is executed if the user already has version 1 of the database installed
if (oldVersion >= 2) {
}
//Code for adding a new column
}
}
Is your query returning any data? You might want to check the output of cursor.getCount().
Also if you go into Developer Options of your device you can see an option called "Show Layout Bounds". It will show you where your view elements are on the screen.
I finally found a solution, in public class StarbuzzDatabaseHelper
''''
private static final int DB_VERSION = 12;
''''
change to: private static final int DB_VERSION = 2;
''''
if (oldVersion >= 2) {
}
''''
change to: if (oldVersion < 2) {
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC;");
}
''''

Retrieve a specific row data in database Android

I think I have read pretty much all the answers about this topic without getting the right answer for my case.
I have a list view in one activity called Library. When I click on an item, I would like to retrieve the informations about the clicked item in another activity. I would like these information to be in different field.
You will probably understand a bit better with my code.
This is the Library activity, on which I have my listview of what I call "tags":
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
DatabaseHelper.java :
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
// table configuration
public static final String TABLE_NAME = "person_table"; // Table name
private static final String TAG_ID = "_id"; // a column named "_id" is required for cursor
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public DatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aTagName, String aTagId, String aTagData) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(TAG_NAME, aTagName);
contentValues.put(TAG_MID, aTagId);
contentValues.put(TAG_DATA, aTagData);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + TAG_ID + " INTEGER PRIMARY KEY, " +
TAG_NAME + " TEXT, " + TAG_MID + " TEXT, " + TAG_DATA + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
And InfoTagActivity.java , this is in this activity that I want to get the information about the clicked item :
public class InfoTagActivity extends ActionBarActivity {
TextView textTagName;
TextView textTagId;
TextView textTagData;
String tagId;
private static final String TAG_NAME = "tag_name";
private static final String TAG_MID = "tag_mid";
private static final String TAG_DATA = "tag_data";
static SQLiteDatabase db = null;
private DatabaseHelper databaseHelper;
long tag_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info_tag);
getSupportActionBar().hide();
//String tagName = this.getIntent().getStringExtra(TAG_NAME);
databaseHelper = new DatabaseHelper(this);
textTagName = (TextView) findViewById(R.id.tagName);
textTagId = (TextView) findViewById(R.id.tagId);
textTagData = (TextView) findViewById(R.id.tagInfo);
Intent intent = getIntent();
Cursor cursor = databaseHelper.getAllData();
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex("tag_name"));
textTagName.append(name);
String id = cursor.getString(cursor.getColumnIndex("tag_mid"));
textTagId.append(id);
String info = cursor.getString(cursor.getColumnIndex("tag_data"));
textTagData.append(info);
}
}
}
With the associated activity_info_tag.xml :
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/relativeLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/relativeLayout2"
android:paddingTop="10dp">
<TextView
android:id="#+id/tagId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_above="#+id/tagDate"
android:layout_toRightOf="#+id/tagIdText"
android:layout_toEndOf="#+id/tagIdText" />
<TextView
android:id="#+id/tagDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_alignTop="#+id/tagDateText"
android:layout_toRightOf="#+id/tagDateText"
android:layout_toEndOf="#+id/tagDateText"
android:paddingLeft="5dp"
android:paddingRight="5dp"/>
<TextView
android:id="#+id/tagInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/main_theme_blue"
android:layout_below="#+id/tagDate"
android:layout_toRightOf="#+id/tagInfoText"
android:layout_toEndOf="#+id/tagInfoText"
android:paddingLeft="5dp"
android:paddingRight="5dp"
/>
</RelativeLayout>
My problem is that by now, when I click on a tag of the list view, it always give me the information about the first tag only. I would like to get the information about the tag on which I clicked instead.
Could someone help me on that ?
Thank you a lot for your answers !

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.

How to get name from SQLite Database in android

I am developing an android application in when user enters in the app, the first activity asks his name to enter in textfield. By clicking on submit button, the name of the user stores in SQLite database and another activity opens and the name of the user will display in next activity. Now, I want something like that, if user closes the app and when he starts it again, then the name of the user should not be asked again and he should directly move to second activity with his name that he entered first time. This is my complete code below :
DatabaseHandler.java
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="Database1";// Database Name...
private static final String TABLE_NAME = "Name"; // Name of the Table...
private static final String KEY_ID = "id"; // Column1 of the table
private static final String KEY_NAME="UserName";// Column2 of the table
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "(" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null);";
public DatabaseHandler(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(DatabaseHandler.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addName(Name name)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME, name.getUsername());
db.insert(TABLE_NAME, null, values);
db.close();
}
public Name getName(int id)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(TABLE_NAME, new String[]{ KEY_ID,KEY_NAME },KEY_ID +"=?",new String[] { String.valueOf(id) },null,null,null,null);
if(cursor!=null)
{
cursor.moveToFirst();
}
Name name = new Name(Integer.parseInt(cursor.getString(0)),cursor.getString(1));
return name;
}
public List<Name> getAllNames() {
List<Name> nameList = new ArrayList<Name>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Name name = new Name();
name.setId(Integer.parseInt(cursor.getString(0)));
name.setUsername(cursor.getString(1));
// Adding contact to list
nameList.add(name);
} while (cursor.moveToNext());
}
return nameList;
}
}
MainActivity.java
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.os.Build;
public class MainActivity extends Activity
{
Button submit;
EditText et1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit=(Button)findViewById(R.id.button1);
et1=(EditText)findViewById(R.id.editText1);
final DatabaseHandler db = new DatabaseHandler(this);
submit.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v1)
{
if(v1==submit)
{
String name1=et1.getText().toString();
Log.d("Insert: ", "Inserting ..");
db.addName(new Name(et1.getText().toString()));
Log.d("Reading: ", "Reading all contacts..");
List<Name> names = db.getAllNames();
for (Name n : names) {
String log = "Id: "+n.getId()+" ,Name: " + n.getUsername();
Log.d("Name: ", log);
}
Intent i1=new Intent(getApplicationContext(),NextPage.class);
i1.putExtra("name",name1);
startActivity(i1);
}
}
});
}
#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 boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
}
Main.xml
<RelativeLayout 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"
tools:context="com.example.database.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:ems="10"
android:hint="Please Enter Your Name"
android:inputType="textPersonName" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:text=" Submit " />
</RelativeLayout>
I am not getting any idea about this how to do it.Please help me...
You could use Shared Preferences instead of a SQLte database. For just storing a name Shared Preferences are more than enough.
So when your application starts, you just check if the specific Shared Preferences are containing the users name and if not you ask the user about the name.
SharedPreferences settings = getSharedPreferences("PREFERENCES", MODE_PRIVATE);
if(settings.getString("USER_NAME", "").equals("")) {
//User has to enter the name
//Do the specific action
String user_name = ...
SharedPreferences.Editor editor = settings.edit();
editor.putString("USER_NAME", user_name);
editor.commit();
}
You will have to do a check to see if a name already exists in the database before you want to add. Change to:
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1) {
if(v1==submit) {
if( db.db.getAllNames() != null ) {
// Go directly to intent
} else {
// Ask a name
}
} );
}

Android ListView not displaying database information

Attached above is a screenshot of the issue. Will not update with information of the database:
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/categoryChoose"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:entries="#array/catergory_arrays"
android:gravity="right" />
<ListView
android:id="#+id/dbListView"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_marginTop="10dip" >
</ListView>
<Button
android:id="#+id/scanCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dip"
android:text="#string/scan" />
<Button
android:id="#+id/editItemCurrent"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="10dp"
android:text="#string/editItem" />
</LinearLayout>
CurrentItems - Should be displaying current database rows
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class CurrentItems extends Activity {
ItemDatabase db;
Context context;
Button addButton, editButton;
ListView listView;
// the table that displays the data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.current_inventory);
db = new ItemDatabase(this);
// create references and listeners for the GUI interface
setupViews();
// make the buttons clicks perform actions
addButtonListeners();
displaySearch();
}
private void setupViews() {
// bring up current database items
listView = (ListView) findViewById(R.id.dbListView);
// THE BUTTONS
addButton = (Button) findViewById(R.id.scanCurrent);
editButton = (Button) findViewById(R.id.editItemCurrent);
}
private void addButtonListeners() {
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, AddItem.class));
}
});
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CurrentItems.this, EditItems.class));
}
});
}
private void displaySearch() {
// TODO Auto-generated method stub
ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();
final ArrayList<String> items = new ArrayList<String>();
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
for (int position = 0; position < data.size(); position++) {
ArrayList<Object> row = data.get(position);
items.add("\nDate:" + row.get(0).toString() + " Title:"
+ row.get(1).toString() + "\n" + "Quantity:"
+ Integer.parseInt(row.get(2).toString()) + "\n");
aa.notifyDataSetChanged();
}
listView.setAdapter(aa);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
}
ItemsDatabase
package com.example.fooditemmonitor;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public final class ItemDatabase {
// the Activity or Application that is creating an object from this class.
Context context;
// a reference to the database used by this application/object
private SQLiteDatabase db;
// These constants are specific to the database.
private final String DATABASE_NAME = "ItemDatabase.sqlite";
private final int DATABASE_VERSION = 3;
// These constants are specific to the database table.
private final String TABLE_NAME = "foodItems";
private final String COLUMN_NAME_ENTRY_ID = "entryid";
private final String COLUMN_NAME_BARCODE = "barcode";
private final String COLUMN_NAME_TITLE = "title";
private final String COLUMN_NAME_QUANTITY = "quantity";
private final String COLUMN_NAME_DATE = "date";
String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME;
String SQL_CREATE_TABLE = "create table " + TABLE_NAME + " ("
+ COLUMN_NAME_ENTRY_ID
+ " integer primary key autoincrement not null," + COLUMN_NAME_DATE
+ " date," + COLUMN_NAME_BARCODE + " text," + COLUMN_NAME_TITLE
+ " text," + COLUMN_NAME_QUANTITY + " int" + ");";
public ItemDatabase(Context context) {
this.context = context;
// create or open the database
ItemDatabaseHelper helper = new ItemDatabaseHelper(context);
this.db = helper.getWritableDatabase();
}
public void addRow(String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to insert the new data
try {
db.insert(TABLE_NAME, null, values);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo,
String rowStringThree, int rowIntFour) {
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(COLUMN_NAME_DATE, rowStringOne);
values.put(COLUMN_NAME_BARCODE, rowStringTwo);
values.put(COLUMN_NAME_TITLE, rowStringThree);
values.put(COLUMN_NAME_QUANTITY, rowIntFour);
// ask the database object to update the database row of given rowID
try {
db.update(TABLE_NAME, values, COLUMN_NAME_ENTRY_ID + "=" + rowID,
null);
} catch (Exception e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void deleteRow(long rowID) {
// ask the database manager to delete the row of given id
try {
db.delete(TABLE_NAME, COLUMN_NAME_ENTRY_ID + "=" + rowID, null);
} catch (Exception e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
public ArrayList<ArrayList<Object>> getAllRowsAsArrays() {
// create an ArrayList that will hold all of the data collected from
// the database.
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
// this is a database call that creates a "cursor" object.
// the cursor object store the information collected from the
// database and is used to iterate through the data.
Cursor cursor;
try {
// ask the database object to create the cursor.
cursor = db.query(TABLE_NAME, new String[] { COLUMN_NAME_DATE,
COLUMN_NAME_TITLE, COLUMN_NAME_QUANTITY }, null, null,
null, null, COLUMN_NAME_TITLE + " DESC");
// move the cursor's pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it to the
// ArrayList.
while (cursor.moveToNext()) {
// your content
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getColumnIndex(COLUMN_NAME_DATE));
dataList.add(cursor.getColumnIndex(COLUMN_NAME_TITLE));
dataList.add(cursor.getColumnIndex(COLUMN_NAME_QUANTITY));
dataArrays.add(dataList);
}
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from the database.
return dataArrays;
}
public class ItemDatabaseHelper extends SQLiteOpenHelper {
public ItemDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
// execute the query string to the database.
db.execSQL(SQL_CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade
// policy is to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
}
No errors are thrown in the logcat. Should display data in order of Date, Title and then Quantity.
All help will be appreciated.
cursor.getColumnIndex
returns the index of a column by name. So you have indexes as a result. You should do something like:
dataList.add(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_DATE)));
dataList.add(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_TITLE)));
dataList.add(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_QUANTITY)));

Categories