I'm new to Java and just tried to make a database. I managed to make a DB and all but when I want to read the values it seems to get an error.
This is my code for my settings activity (which asks for setting values and add them in the DB on a specific ID)
public class Settings extends Activity{
Button Save;
static Switch SwitchCalculations;
public static String bool;
public static List<Integer> list_id = new ArrayList<Integer>();
public static List<String> list_idname = new ArrayList<String>();
public static List<String> list_kind = new ArrayList<String>();
public static List<String> list_value = new ArrayList<String>();
static Integer[] arr_id;
static String[] arr_idname;
static String[] arr_kind;
static String[] arr_value;
public static final String TAG = "Settings";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Save = (Button) findViewById(R.id.btnSave);
SwitchCalculations = (Switch) findViewById(R.id.switchCalcOnOff);
readData();
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
writeData();
//Toast.makeText(this, "Data has been saved.", Toast.LENGTH_SHORT).show();
readData();
Save.setText("Opgeslagen");
}
});
}
public void writeData() {
int id = 1;
String idname = "switchCalcOnOff";
String kind = "switch";
boolean val = SwitchCalculations.isChecked();
String value = new Boolean(val).toString();
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(dbh.C_ID, id);
cv.put(dbh.C_IDNAME, idname);
cv.put(dbh.C_KIND, kind);
cv.put(dbh.C_VALUE, value);
if (dbh.C_ID.isEmpty() == true) {
db.insert(dbh.TABLE, null, cv);
Log.d(TAG, "Insert: Data has been saved.");
} else if (dbh.C_ID.isEmpty() == false) {
db.update(dbh.TABLE, cv, "n_id='1'", null);
Log.d(TAG, "Update: Data has been saved.");
} else {
Log.d(TAG, "gefaald");
}
db.close();
}
public void readData() {
dbHelper_Settings dbh = new dbHelper_Settings(this);
SQLiteDatabase db = dbh.getWritableDatabase();
List<String> list_value = new ArrayList<String>();
String[] arr_value;
list_value.clear();
Cursor cursor = db.rawQuery("SELECT " + dbh.C_VALUE + " FROM " + dbh.TABLE + ";", null);
if (cursor.moveToFirst()) {
do {
list_value.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()){
cursor.close();
}
db.close();
arr_value = new String[list_value.size()];
for (int i = 0; i < list_value.size(); i++){
arr_value[i] = list_value.get(i);
}
}
}
Then I have my dbHelper activity see below:
package com.amd.nutrixilium;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class dbHelper_Settings extends SQLiteOpenHelper{
private static final String TAG="dbHelper_Settings";
public static final String DB_NAME = "settings.db";
public static final int DB_VERSION = 10;
public final String TABLE = "settings";
public final String C_ID = "n_id"; // Special for id
public final String C_IDNAME = "n_idname";
public final String C_KIND = "n_kind";
public final String C_VALUE = "n_value";
Context context;
public dbHelper_Settings(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
// oncreate wordt maar 1malig uitgevoerd per user voor aanmaken van database
#Override
public void onCreate(SQLiteDatabase db) {
String sql = String.format("create table %s (%s int primary key, %s TEXT, %s TEXT, %s TEXT)", TABLE, C_ID, C_IDNAME, C_KIND, C_VALUE);
Log.d(TAG, "onCreate sql: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + TABLE); // wist een oudere database versie
Log.d(TAG, "onUpgrate dropped table " + TABLE);
this.onCreate(db);
}
}
And the weird thing is I don't get any error messages here.
But I used Log.d(TAG, text) to check where the script is being skipped and that is at cursor.moveToFirst().
So can anyone help me with this problem?
Here, contrary to what you seem to expect, you actually check that a text constant is not empty:
if (dbh.C_ID.isEmpty() == true) {
It isn't : it always contains "n_id"
I think your intent was to find a record with that id and, depending on the result, either insert or update.
You should do just that: attempt a select via the helper, then insert or update as in the code above.
Edit:
Add to your helper something like this:
public boolean someRowsExist(SQLiteDatabase db) {
Cursor cursor = db.rawQuery("select EXISTS ( select 1 from " + TABLE + " )", new String[] {});
cursor.moveToFirst();
boolean exists = (cursor.getInt(0) == 1);
cursor.close();
return exists;
}
And use it to check if you have any rows in the DB:
if (dbh.someRowsExist(db)) { // instead of (dbh.C_ID.isEmpty() == true) {
Looks like you're having trouble debugging your query. Android provides a handy method DatabaseUtils.dumpCursorToString() that formats the entire Cursor into a String. You can then output the dump to LogCat and see if any rows were actually skipped.
Related
I want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 + " TEXT" + COL3 + " ,TEXT)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!
I am trying to save the button's state in a certain item of RecyclerView whenever a user clicks that button. At the time it was clicked, it's visibility will be gone and another button will be visible. How can I save the button's state so that whenever the app is entirely closed, when I open it again the state of the button is still there?
I tried making a database for the button's visibility state but I couldn't figure out where to put the right code to add the data and save it.
onBindViewHolder() inside RecyclerView class, this is where I put my button click listener.
#Override
public void onBindViewHolder(final MyViewHolder holder, int position){
MakerAdapter h = makerList.get(position);
final String macString = h.getHMac();
holder.rIcon.setImageResource(h.getHIcon());
holder.rDevice.setText(h.getHDevice());
holder.rBrand.setText(h.getHBrand());
holder.rIp.setText(h.getHIp());
holder.rMac.setText(h.getHMac());
holder.rDate.setText(h.getHDate());
holder.rWifi.setText(h.getHWifi());
holder.rMark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSafeDB = new SafeDB(getApplicationContext(), null,null,1);
holder.rMark.setVisibility(GONE);
holder.rUnsafe.setVisibility(VISIBLE);
mSafeDB.addSafeMaker(macString, holder.rMark.getVisibility());
}
});
holder.rUnsafe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSafeDB = new SafeDB(getApplicationContext(), null,null,1);
holder.rUnsafe.setVisibility(GONE);
holder.rMark.setVisibility(VISIBLE);
mSafeDB.addSafeMaker(macString, holder.rUnsafe.getVisibility());
}
});
}
These are my imports specific to this(onBindViewHolder) method:
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.facebook.FacebookSdk.getApplicationContext;
This is my database
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;
public class SafeDB extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "safedb.db";
private static final String TABLE_NAME = "marked_safe";
private static final String COL_ID = "id";
private static final String COL_MAC = "mac";
private static final String COL_MARK = "mark";
//////////Housekeeping START
public SafeDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DB_NAME, factory, DB_VERSION);
}
public SafeDB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
// this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_MAC + " TEXT, " +
COL_MARK + " INTEGER " +
");";
db.execSQL(query);
}
public void open() throws SQLException {
close();
this.getWritableDatabase();
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//////////Housekeeping END
public void deleteTable(){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
//IF FIRST TIME. THIS WILL BE TRIGGERED
public void addSafeMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MAC, mac);
values.put(COL_MARK, mark);
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
}
//UPDATE THE Arp
public void updateMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MAC, mac);
values.put(COL_MARK, mark);
SQLiteDatabase db = getWritableDatabase();
db.update(TABLE_NAME, values, "id = 1", null);
}
//GET THE MAC
public String getMac(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mac = c.getString(c.getColumnIndex("mac"));
return mac;
}
//GET THE BUTTON VISIBILITY VALUE
public String getSafeValue(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mark = c.getString(c.getColumnIndex("mark"));
return mark;
}
//CHECK IF EMPTY
public boolean isEmpty() {
boolean e = true;
SQLiteDatabase db = getWritableDatabase();
String count = "SELECT count(*) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(count, null);
c.moveToFirst();
int icount = c.getInt(0);
e = icount <= 0;
return e;
}
public int getCount(){
int count = 0;
SQLiteDatabase db = getWritableDatabase();
String c = "SELECT count(*) FROM " + TABLE_NAME;
Cursor x = db.rawQuery(c, null);
x.moveToFirst();
count = x.getInt(0);
return count;
}
}
The following is a working example based upon your code, albeit that the Adapter is probably quite different. Some assumptions/guesswork were made. So the code is very much in-principle code and would need to be adapted.
The above adds a mac (assuming a mac is unique) when the adapter is instantiated, a specific mac will only be added once.
In the onBindView method the status/mark is retrieved from the db to determine which button is displayed.
When a button is clicked the displayed button is toggled and the respective mac (the button's tag is used to store the mac) is used to update the respective row according to the mac.
SafeDB.java
public class SafeDB extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "safedb.db";
private static final String TABLE_NAME = "marked_safe";
private static final String COL_ID = "id";
private static final String COL_MAC = "mac";
private static final String COL_MARK = "mark";
//////////Housekeeping START
public SafeDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DB_NAME, factory, DB_VERSION);
}
public SafeDB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COL_ID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT REMOVED NOT NECESSARY
COL_MAC + " TEXT UNIQUE, " + // Probably should be unique
COL_MARK + " INTEGER " +
");";
db.execSQL(query);
}
public void open() throws SQLException {
close();
this.getWritableDatabase();
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1){
deleteTable(); // might as well use the deleteTable method as it exists
onCreate(db);
}
//////////Housekeeping END
public void deleteTable(){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
//IF FIRST TIME. THIS WILL BE TRIGGERED
// wont hurt to return the id of the inserted row (-1 if no row inserted)
public long addSafeMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MAC, mac);
values.put(COL_MARK, mark);
SQLiteDatabase db = getWritableDatabase();
return db.insert(TABLE_NAME, null, values);
}
//UPDATE THE Arp
public int updateMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MARK, mark);
//values.put(COL_MARK, mark); // guess this wont change rather that it will be used to determine the row to be updated
SQLiteDatabase db = getWritableDatabase();
//db.update(TABLE_NAME, values, "id = 1", null); // Will only ever update 1 specific row
String whereclause = COL_MAC + "=?";
String[] whereargs = new String[]{mac};
return db.update(TABLE_NAME,values,whereclause,whereargs);
}
//GET THE MAC
public String getMac(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mac = c.getString(c.getColumnIndex("mac"));
return mac;
}
public boolean getSafeValue(String mac) {
int mark = 0; // assume marked safe if row not found
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = COL_MAC + "=?";
String[] whereargs = new String[]{mac};
Cursor c = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (c.moveToFirst()) {
mark = c.getInt(c.getColumnIndex(COL_MARK));
}
return mark < 1;
}
//GET THE BUTTON VISIBILITY VALUE
/*
public String getSafeValue(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mark = c.getString(c.getColumnIndex("mark"));
return mark;
}
*/
//CHECK IF EMPTY
/*
public boolean isEmpty() {
boolean e = true;
SQLiteDatabase db = getWritableDatabase();
String count = "SELECT count(*) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(count, null);
c.moveToFirst(); // WARINING if no rows then next line will crash INDEX OUT OF BOUNDS
int icount = c.getInt(0);
e = icount <= 0;
return e;
}
*/
public long getCount(){
int count = 0;
SQLiteDatabase db = getWritableDatabase();
return DatabaseUtils.queryNumEntries(this.getWritableDatabase(),TABLE_NAME);
/*
quick form used as above
String c = "SELECT count(*) FROM " + TABLE_NAME;
Cursor x = db.rawQuery(c, null);
x.moveToFirst();
count = x.getInt(0);
return count;
*/
}
}
You should note the comments, there were some issues with your code.
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<String> mMacList;
SafeDB mDB;
Context mContext;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mMac;
public Button mSafe;
public Button mUnsafe;
public MyViewHolder(View view) {
super(view);
mMac = view.findViewById(R.id.name);
mSafe = view.findViewById(R.id.marksafe);
mUnsafe = view.findViewById(R.id.markunsafe);
}
}
public MyAdapter(Context context,ArrayList<String> maclist) {
mMacList = maclist;
mContext = context;
mDB = new SafeDB(context);
// Could add the mac's to the DB here (note DB changed so mac is unqiue so same mac won't be added)
for (String mac: maclist) {
mDB.addSafeMaker(mac,0);
}
}
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.mylist_item,viewGroup, false);
MyViewHolder vh = new MyViewHolder(v);
mContext = viewGroup.getContext();
return vh;
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder viewHolder, int i) {
viewHolder.mMac.setText(mMacList.get(i));
if (mDB == null) {
mDB = new SafeDB(viewHolder.mMac.getContext());
}
//Set the Tag for the buttons with the mac so it can be retrieved
viewHolder.mSafe.setTag(mMacList.get(i));
viewHolder.mUnsafe.setTag(mMacList.get(i));
// Display the buttons according to the database
if (mDB.getSafeValue(mMacList.get(i))) {
viewHolder.mSafe.setVisibility(View.GONE);
viewHolder.mUnsafe.setVisibility(View.VISIBLE);
} else {
viewHolder.mSafe.setVisibility(View.VISIBLE);
viewHolder.mUnsafe.setVisibility(View.GONE);
}
// Add the onCLickListeners
viewHolder.mSafe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.mSafe.setVisibility(View.GONE);
viewHolder.mUnsafe.setVisibility(View.VISIBLE);
String mac = (String) ((Button) viewHolder.mSafe).getTag();
changeSafeMark((String)viewHolder.mSafe.getTag(),0);
}
});
viewHolder.mUnsafe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.mSafe.setVisibility(View.VISIBLE);
viewHolder.mUnsafe.setVisibility(View.GONE);
changeSafeMark((String)viewHolder.mUnsafe.getTag(),1);
}
});
}
#Override
public int getItemCount() {
return mMacList.size();
}
public int changeSafeMark(String mac, int mark) {
int result = mDB.updateMaker(mac,mark);
return result;
}
}
This is probably quite different and only the simplest of layouts was used.
mylistitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:id="#+id/marksafe"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Make Safe"
/>
<Button
android:id="#+id/markunsafe"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Make Unsafe"
/>
</LinearLayout>
MainActivity.java
The invoking activity used to test :-
public class MainActivity extends AppCompatActivity {
RecyclerView mList;
RecyclerView.LayoutManager mLayoutManager;
MyAdapter mMyAdapter;
// The underlying data (just a list of strings for the macs)
ArrayList<String> mymacliist = new ArrayList<>(Arrays.asList("M1","M2","M3"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = this.findViewById(R.id.mylist);
mLayoutManager = new LinearLayoutManager(this);
mList.setLayoutManager(mLayoutManager);
mMyAdapter = new MyAdapter(this,mymacliist);
mList.setAdapter(mMyAdapter);
}
}
Results
When First run :-
After M2 and M3 are clicked (buttons are changed to Make Safe when clicked), then the App is stopped and then started :-
database is your best option, you should put the code inside onclicklistiner.
if you want to "toggle" so save a boolean in the database that if it true than the user have been clicked on the item, and if its false, the user didn't clicked the item.
than in your onclicklistiner you do an if statement on the boolean.
I have been doing an android database application project recently.When i tried to execute. I cant find the folder 'databases' in the file explorer of the DDMS. I checked the following path /data/data/packagename/databases,but there i could not find databases folder and my database file.
I have attached the code for database helper class
please help me if there is any error that is preventing me from creating the database or is it wrong with my eclipse. Because even some of my existing projects also don't show up with the databases folder inside them.
DBclass.java:
package pack.andyxdb;
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 class DBclass {
public static final String KEY_TIMESTAMP = "Timestamp";
public static final String KEY_UNIQUEID = "UniqueID";
public static final String KEY_DEVICETYPE = "Devicetype";
public static final String KEY_RSSI = "RSSI";
private static final String DATABASE_NAME = "DannyZ.db";
private static final String DATABASE_TABLE = "Data";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;
private static final String USER_MASTER_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
+ KEY_TIMESTAMP + " INTEGER ,"
+ KEY_UNIQUEID + " INTEGER, " + KEY_DEVICETYPE + " TEXT, " + KEY_RSSI + " INTEGER PRIMARY KEY )";
//CREATE TABLE `DannyZ` (
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(USER_MASTER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if DATABASE VERSION changes
// Drop old tables and call super.onCreate()
}
}
public DBclass(Context c) {
ourContext = c;
dbh = new DbHelper(ourContext);
}
public DBclass open() throws SQLException {
odb = dbh.getWritableDatabase();
return this;
}
public void close() {
dbh.close();
}
public long insertrecord(int timestamp, int uniqueID,String Device, int RSSI) throws SQLException{
// Log.d("", col1);
// Log.d("", col2);
ContentValues IV = new ContentValues();
IV.put(KEY_TIMESTAMP, timestamp);
IV.put(KEY_UNIQUEID, uniqueID );
IV.put(KEY_DEVICETYPE, Device != "");
IV.put(KEY_RSSI, RSSI );
return odb.insert(DATABASE_TABLE, null, IV);
// returns a number >0 if inserting data is successful
}
public void updateRow(long rowID, String col1, String col2,String col3,String col4) {
ContentValues values = new ContentValues();
values.put(KEY_TIMESTAMP, col1);
values.put(KEY_UNIQUEID, col2);
values.put(KEY_DEVICETYPE, col3);
values.put(KEY_RSSI, col4);
try {
odb.update(DATABASE_TABLE, values, KEY_RSSI + "=" + rowID, null);
} catch (Exception e) {
}
}
public boolean delete() {
return odb.delete(DATABASE_TABLE, null, null) > 0;
}
public Cursor getAllTitles() {
// using simple SQL query
return odb.rawQuery("select * from " + DATABASE_TABLE + "ORDER BY "+KEY_RSSI, null);
}
public Cursor getallCols(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID, KEY_DEVICETYPE, KEY_RSSI }, null, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
public Cursor getColsById(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID,KEY_DEVICETYPE }, KEY_RSSI + " = " + id, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
}
also my MainActivity.java code is here. Here i try to insert the data into database by making use of submit button. When i hit submit button the app does not stay for long time and says unfortunately myapp has stopped.my curious concern has been is my database being created or not?
please do help me thanks
MainActivity:
public class MainActivity extends Activity {
private ListView list_lv;
private EditText txt1;
private EditText txt2;
private EditText txt3;
private EditText txt4;
private Button btn1;
private Button btn2;
private DBclass db;
private ArrayList<String> collist_1;
private ArrayList<String> collist_2;
private ArrayList<String> collist_3;
private ArrayList<String> collist_4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collist_1 = new ArrayList<String>();
collist_2 = new ArrayList<String>();
collist_3 = new ArrayList<String>();
collist_4 = new ArrayList<String>();
items();
// getData();
}
private void items() {
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
txt1 = (EditText) findViewById(R.id.editText1);
txt2 = (EditText) findViewById(R.id.editText2);
txt3 = (EditText) findViewById(R.id.editText3);
txt4 = (EditText) findViewById(R.id.editText4);
// list_lv = (ListView) findViewById(R.id.dblist);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//getData();
viewData();
}
private void viewData() {
Intent i = new Intent(MainActivity.this, viewActivity.class);
startActivity(i);
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitData();
}
});
}
protected void submitData() {
int a = Integer.parseInt( txt1.getText().toString());
int b = Integer.parseInt( txt2.getText().toString());
String c = txt3.getText().toString();
int d = Integer.parseInt( txt4.getText().toString());
db = new DBclass(this);
long num = 0;
try {
db.open();
num = db.insertrecord(a, b,c,d);
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Error Duplicate value"+e,2000).show();
} finally {
//getData();
}
if (num > 0)
Toast.makeText(this, "Row number: " + num, 2000).show();
else if (num == -1)
Toast.makeText(this, "Error Duplicate value", 4000).show();
else
Toast.makeText(this, "Error while inserting", 2000).show();
}
}
Create object of helper class in your activity onCreate method for creating the database file in android app
DBclass db=new DBclass(context);
Hope this will help.
So this is my code:
public void onItemClick(AdapterView<?> listView, View view, int position, long id)
{
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
int _id = cursor.getInt(0);
String _recipe = cursor.getString(1);
Intent intent = new Intent(Luzon1Activity.this,RecipeInstruction.class);
intent.putExtra("id", _id);
intent.putExtra("recipe", _recipe);
startActivity(intent);
}
This is my code for the next activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipeinstruction);
dbHelper = new Dbadapter(this);
dbHelper.open();
bg = (RelativeLayout) findViewById(R.id.relativeLayout1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id = extras.getInt("id");
recipe = extras.getString("recipe");
}
Toast.makeText(this, id+"\n"+recipe, Toast.LENGTH_SHORT).show();
bg.setBackgroundResource(getImageId(this, recipe));
}
My problem is on this part: String _recipe = cursor.getString(1).
It always gives me the wrong data. I tried to change the number but still it gives me the wrong data.
This is my database:
package com.pinoycookbook;
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 class Dbadapter
{
public static final String ROWID = "_id";
public static final String NAME = "foodname";
public static final String ORIGIN = "origin";
public static final String RECIPE = "recipe";
public static final String CATEGORY = "category";
private static final String TAG = "Dbadapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "PinoyCookbook.sqlite";
public static final String SQLITE_TABLE = "Food";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
ROWID + " integer PRIMARY KEY autoincrement," +
NAME + " TEXT," +
RECIPE + " TEXT," +
ORIGIN + " TEXT," +
CATEGORY+ " TEXT,"+
" UNIQUE (" + ROWID +"));";
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
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 " + SQLITE_TABLE);
onCreate(db);
}
}
public Dbadapter(Context ctx) {
this.mCtx = ctx;
}
public Dbadapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createData(String foodname, String recipe, String origin, int i) {
ContentValues initialValues = new ContentValues();
initialValues.put(NAME, foodname);
initialValues.put(RECIPE, recipe);
initialValues.put(ORIGIN, origin);
initialValues.put(CATEGORY, i);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public boolean deleteAllData() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertData() {
createData("Adobong Manok","adobongmanok","Manila",1);
createData("Lechon","lechon","Cebu",2);
createData("Crispy Pata","crispypata","Cebu",2);
createData("Bulalo","bulalo","Batangas",1);
createData("Taba ng Talangka Rice","talangkarice","Roxas",2);
createData("Arroz Caldo","arrozcaldo","Roxas",2);
createData("Sinigang","sinigang","Manila",1);
}
}
So i recommend you to use getColumnIndex() method rather than hardcode it.
String _recipe = cursor.getString(cursor.getColumnIndex(Dbadapter.RECIPE));
It will ensure that you will get always right field. And if it still get wrong data problem is in query not in Cursor
Note: An usage of static fields that hold column names is always the best practise.
Update:
I've tried it before and it gives me this error:
java.lang.IllegalArgumentException: column 'recipe' does not exist
You need to find out your actual table structure. Try to perform this statement:
PRAGMA table_info(Dbadapter.SQLITE_TABLE);
What says docs(source):
This pragma returns one row for each column in the named table.
Columns in the result set include the column name, data type, whether
or not the column can be NULL, and the default value for the column.
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.
Example:
Here i created for you method for getting tableinfo via PRAGMA:
public String getTableInfo() {
StringBuilder b = new StringBuilder("");
Cursor c = null;
try {
db = helper.getReadableDatabase();
String query = "pragma table_info(" + Dbadapter.SQLITE_TABLE + ")";
c = db.rawQuery(query, null);
if (c.moveToFirst()) {
do {
b.append("Col:" + c.getString(c.getColumnIndex("name")) + " ");
b.append(c.getString(c.getColumnIndex("type")));
b.append("\n");
} while (c.moveToNext());
}
return b.toString();
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
Output will be something like this:
Column: type text
Column: date text
Only for imagination i will give you screen:
you can try it this way:
cursor.getString(cursor.getColumnIndex("recipe"));
it returns you the correct index and as result the correct value.
hi i am an SEO and i am in currently practicing android development of my own. i studied about database storing in android developers site and found an example code that to be in a notepad.
I tried using it in my project. In my project i have placed 2 edit boxes with a OK button, when the OK button is clicked the data in the edit box gets stored and it is shown in a new page.
the following is the code of my project's main class file,
{
b = (Button)findViewById(R.id.widget30);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(NotesDbAdapter.KEY_ET1);
String body = extras.getString(NotesDbAdapter.KEY_ET2);
mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (title != null) {
et1.setText(title);
}
if (body != null) {
et2.setText(body);
}
}
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(et1.getText().toString().length() == 0 && et2.getText().toString().length() == 0)
{
et.setVisibility(View.VISIBLE);
alertbox();
}
else
{
main.this.finish();
Intent myIntent = new Intent(v.getContext(), T.class);
startActivityForResult(myIntent, 0);
}
}
});
}
public void alertbox()
{
et = new TextView(this);
Builder alert =new AlertDialog.Builder(main.this);
alert.setTitle("Alert");
alert.setMessage("Required all fields");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
}
});
AlertDialog alert1 = alert.create();
alert1.show();
}
}
the following is the code of the DataBaseAdapter
public class NotesDbAdapter {
public static final String KEY_ET1 = "a";
public static final String KEY_ET2 = "b";
public static final String KEY_ROWID = "_id";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;
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 notes");
onCreate(db);
}
}
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(String a, String b) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ET1, a);
initialValues.put(KEY_ET2, b);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_ET1,
KEY_ET2}, null, null, null, null, null);
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_ET1, KEY_ET2}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String a, String b) {
ContentValues args = new ContentValues();
args.put(KEY_ET1, a);
args.put(KEY_ET2, b);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
when i run the project the new page is opening but the data's entered is not shown there.
what is to be the error. pls teach me
You are going to need to get an instance of your database adapter
NotesDbAdapter adapter = new NotesDbAdapter(this); //pass activity context as a param
then you need to use the open method of the new database object to open the database
adapter.open();
now call the store method
String str = myEditText.getText().toString();
String str1 = "random other string";
adapter.createNote(str, str1);
I notice that your createNote method takes two params. I dont know where you want to get the other data from, so I just used 'random other string'. Sub in the data you want to store as appropriate.
Finally you will need to close the database:
adapter.close();
And you have successfully stored the information. See this for help on how to use the console to view the data that you have entered into the database. (See specifically the sqlite3 portion of the page) Alternatively you could write some code to display it on the screen after retrieving it. You are going to need to read about cursors if you want to retrieve info. See here for some information on that.