so I've been trying to make a sqlite database in Android Studio with pre-existing data. I'm also trying to display that data to the user, although every time I launch the application it crashes when I search for the items in the database, so I am not sure if I am creating the database correctly. Anything helps, and many Thanks.
here is my database helper
public class MyDBHandler {
myDbHelper myhelper;
public MyDBHandler(Context context)
{
myhelper = new myDbHelper(context);
}
public void addBear(Bears bear)
{
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(myhelper.COLUMN_ID, bear.getID());
values.put(myhelper.COLUMN_BEARNAME, bear.getbearname());
values.put(myhelper.COLUMN_STUFFING, bear.getstuffing());
values.put(myhelper.COLUMN_BEARHEALTH, bear.getbearhealth());
values.put(myhelper.COLUMN_HEALTHCOST, bear.gethpcost());
values.put(myhelper.COLUMN_HEALTHCOUNT, bear.gethpcount());
values.put(myhelper.COLUMN_BEARATTACK, bear.getbearattack());
dbb.insert(myDbHelper.TABLE_BEARS, null , values);
}
public Bears findBear(int bearID)
{
SQLiteDatabase db = myhelper.getWritableDatabase();
Bears bear = new Bears();
String[] columns =
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST,
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK,};
String query = myDbHelper.COLUMN_ID + " = ?";
String[] selections = {String.valueOf(bearID)};
Cursor cursor =
db.query(myDbHelper.TABLE_BEARS,columns,query,
selections,null,null,null,null);
if(null != cursor) {
bear.setID(Integer.parseInt(cursor.getString(0)));
bear.setbearname(cursor.getString(1));
bear.setstuffing(Integer.parseInt(cursor.getString(2)));
bear.setbearhealth(Integer.parseInt(cursor.getString(3)));
bear.sethpcost(Integer.parseInt(cursor.getString(4)));
bear.sethpcount(Integer.parseInt(cursor.getString(5)));
bear.setbearattack(Integer.parseInt(cursor.getString(6)));
}
db.close();
return bear;
}
static class myDbHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME = "bearDB.db"; // Database
private static final String TABLE_BEARS = "bears"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String COLUMN_ID="_id"; // Column I (Primary Key)
public static final String COLUMN_BEARNAME = "bearname";
public static final String COLUMN_STUFFING = "stuffing";
public static final String COLUMN_BEARHEALTH = "bearhealth";
public static final String COLUMN_HEALTHCOST = "healthcost";
public static final String COLUMN_HEALTHCOUNT = "healthcount";
public static final String COLUMN_BEARATTACK = "bearattack"; // Column III
String CREATE_BEARS_TABLE = "CREATE TABLE " +
TABLE_BEARS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_BEARNAME + " TEXT," +
COLUMN_STUFFING + " INTEGER," +
COLUMN_BEARHEALTH + " INTEGER," +
COLUMN_HEALTHCOST + " INTEGER, " +
COLUMN_HEALTHCOUNT + " INTEGER, "+
COLUMN_BEARATTACK + " INTEGER" +
")";
private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_BEARS;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_BEARS_TABLE);
ContentValues beary = new ContentValues();
beary.put(COLUMN_ID, 1 );
beary.put(COLUMN_BEARNAME, "Beary");
beary.put(COLUMN_STUFFING, 5);
beary.put(COLUMN_BEARHEALTH, 10);
beary.put(COLUMN_HEALTHCOST, 1);
beary.put(COLUMN_HEALTHCOUNT, 0);
beary.put(COLUMN_BEARATTACK,4);
db.insert(TABLE_BEARS, null, beary);
ContentValues honey = new ContentValues();
honey.put(COLUMN_ID, 2 );
honey.put(COLUMN_BEARNAME, "Honey");
honey.put(COLUMN_STUFFING, 5);
honey.put(COLUMN_BEARHEALTH, 8);
honey.put(COLUMN_HEALTHCOST, 1);
honey.put(COLUMN_HEALTHCOUNT, 0);
honey.put(COLUMN_BEARATTACK, 3);
db.insert(TABLE_BEARS, null, honey);
ContentValues baobao = new ContentValues();
baobao.put(COLUMN_ID, 3 );
baobao.put(COLUMN_BEARNAME, "BaoBao");
baobao.put(COLUMN_STUFFING, 5);
baobao.put(COLUMN_BEARHEALTH,11);
baobao.put(COLUMN_HEALTHCOST, 1);
baobao.put(COLUMN_HEALTHCOUNT, 0);
baobao.put(COLUMN_BEARATTACK, 3);
db.insert(TABLE_BEARS, null, baobao);
} catch (Exception e) {
// do nothing
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
// do nothing
}
}
}
and here is my activity page,
public class BearSelectActivity extends AppCompatActivity {
TextView idBear, healthBear, hpcost, attackBear, abilityBear, stuffingBear;
public int hpcount;
EditText nameBear;
public int beartype = 1;
public String Fighter = "Fighter";
public String Healer = "Healer";
public String Tank = "Tank";
MyDBHandler helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bear_select);
helper = new MyDBHandler(this);
Button changeBear = (Button)findViewById(R.id.bearChange);
idBear = (TextView) findViewById(R.id.bearID);
nameBear = (EditText) findViewById(R.id.bearName);
stuffingBear = (TextView) findViewById(R.id.bearStuffing);
healthBear = (TextView) findViewById(R.id.bearHealth);
hpcost = (TextView)findViewById(R.id.HPCOST);
Button plushp = (Button)findViewById(R.id.plusbearhp);
Button minushp = (Button)findViewById(R.id.minusbearhp);
attackBear = (TextView) findViewById(R.id.bearAttack);
abilityBear = (TextView) findViewById(R.id.bearAbility);
abilityBear.setText(Fighter);
Bears bear = helper.findBear(beartype);
idBear.setText(String.valueOf(bear.getID()));
nameBear.setText(String.valueOf(bear.getbearname()));
healthBear.setText(String.valueOf(bear.getbearhealth()));
attackBear.setText(String.valueOf(bear.getbearattack()));
stuffingBear.setText(String.valueOf(bear.getstuffing()));
}
public void changeBearClick (View view){
//MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
ImageView image = (ImageView) findViewById(R.id.bearimage);
//Bears bear;
beartype++;
beartype = bearmod(beartype, 3);
if(beartype == 2) {
image.setImageResource(R.drawable.bear2);
abilityBear.setText(Healer);
}
else if(beartype == 3){
image.setImageResource(R.drawable.bear3);
abilityBear.setText(Tank);
}
else if(beartype == 1){
image.setImageResource(R.drawable.bear1);
abilityBear.setText(Fighter);
}
lookupBear(view);
}
public int bearmod(int a, int b){
if (a < b && a > 0){
return a;
}
else if(a == b){
return a;
}
else if(a == 0 || a > b){
a = 1;
}
return a;
}
public void lookupBear (View view) {
Bears bear = helper.findBear(beartype);
if(bear == null) {
if (beartype == 1) {
bear = new Bears(1, "Beary", 5, 10, 1, 0, 4);
helper.addBear(bear);
} else if (beartype == 2) {
bear = new Bears(2, "Honey", 5, 8, 1, 0, 3);
helper.addBear(bear);
} else if (beartype == 3) {
bear = new Bears(3, "Baobao", 5, 11, 1, 0, 2);
helper.addBear(bear);
}
}
if(bear != null) {
idBear.setText(String.valueOf(bear.getID()));
nameBear.setText(String.valueOf(bear.getbearname()));
stuffingBear.setText(String.valueOf(bear.getstuffing()));
healthBear.setText(String.valueOf(bear.getbearhealth()));
hpcost.setText(String.valueOf(bear.gethpcost()));
hpcount = bear.gethpcount();
attackBear.setText(String.valueOf(bear.getbearattack()));
}
}
}
You have a number of issues that I have spotted.
The following line, defining the columns has an extra trailing comma so :-
String[] columns =
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST,
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK,};
Should be :-
String[] columns =
{myDbHelper.COLUMN_ID,myDbHelper.COLUMN_BEARNAME,myDbHelper.COLUMN_STUFFING,
myDbHelper.COLUMN_BEARHEALTH,myDbHelper.COLUMN_HEALTHCOST,
myDbHelper.COLUMN_HEALTHCOUNT, myDbHelper.COLUMN_BEARATTACK};
When a Cursor is returned it is positioned at before the first row (-1). To access data from the cursor you need to move to a row within the Cursor. You are not doing this.
Additionally a returned Cursor will not be null. So checking for a null Cursor is useless.
Furthermore, using hard coded offsets may well be problematic and inflexible. A Cursor has a getColumnIndex method that will return the offset according to the column name.
A Cursor also has methods other than getString for directly extracting data as other types e.g. getInt, getLong, getBlob ...... Cursor
I'd suggest changing :-
if(null != cursor) {
bear.setID(Integer.parseInt(cursor.getString(0)));
bear.setbearname(cursor.getString(1));
bear.setstuffing(Integer.parseInt(cursor.getString(2)));
bear.setbearhealth(Integer.parseInt(cursor.getString(3)));
bear.sethpcost(Integer.parseInt(cursor.getString(4)));
bear.sethpcount(Integer.parseInt(cursor.getString(5)));
bear.setbearattack(Integer.parseInt(cursor.getString(6)));
}
db.close();
return bear;
to be :-
if(cursor.moveToFirst) {
bear.setID(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_ID)));
bear.setbearname(cursor.getString(cursor.getColumnIndex(myDbHelper.COLUMN_BEARNAME)));
bear.setstuffing(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_STUFFING)));
bear.setbearhealth(cursor.getInt(cursor.getColumnIndex(myhelper.COLUMN_BEARHEALTH)));
bear.sethpcost(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_HEALTHCOST)));
bear.sethpcount(cursor.getInt(cursor.getColumnIndex(myhelper.COLUMN_HEALTHCOUNT))));
bear.setbearattack(cursor.getInt(cursor.getColumnIndex(myDbHelper.COLUMN_BEARATTACK))));
}
cursor.close(); //<<< ADDED SHOULD ALWAYS CLOSE CURSORS WHEN DONE WITH THEM
db.close();
return bear;
so I am not sure if I am creating the database correctly.
The class here at :- Are there any methods that assist with resolving common SQLite issues?
, that you can add, includes some methods that can assist with knowing what the database contains.
All you have to do is add the class by copying and pasting the code (from the second answer) and to then use add the following after the line helper = new MyDBHandler(this); :-
CommonSQLiteUtilities.logDatabaseInfo(helper.getWitableDatabase());
When you run the App, check the Log and it will display DatabaseInformation in the log.
Note the code above is in-principle code and has not been tested, so it may contain simple errors.
Related
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 saw this tutorial: https://www.youtube.com/watch?v=gaOsl2TtMHs
but it seem that when i see the activity there isn't any item listview :\
What can be the problem? I put my code under below
The Main Activity.java
public class Prova2 extends Activity {
int[] imageIDs = {
R.drawable.spaghettiscoglio,
R.drawable.abbacchioascottadito,
R.drawable.agnellocacioeova,
R.drawable.agnolotti,
R.drawable.alettedipollo,
R.drawable.amaretti,
R.drawable.anatraarancia,
R.drawable.alberinatale
};
int nextImageIndex = 0;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prova2);
openDB();
populateListViewFromDB();
registerListClickCallback();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
public void onClick_AddRecord(View v) {
int imageId = imageIDs[nextImageIndex];
nextImageIndex = (nextImageIndex + 1) % imageIDs.length;
// Add it to the DB and re-draw the ListView
myDb.insertRow("Jenny" + nextImageIndex, imageId, "Green");
populateListViewFromDB();
}
public void onClick_ClearAll(View v) {
myDb.deleteAll();
populateListViewFromDB();
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM, DBAdapter.KEY_FAVCOLOUR, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.tvFruitPrice, R.id.ivFruit, R.id.tvFruitPrice, R.id.smalltext};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.sis, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void registerListClickCallback() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
displayToastForId(idInDB);
}
});
}
private void updateItemForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
favColour += "!";
myDb.updateRow(idInDB, name, studentNum, favColour);
}
cursor.close();
populateListViewFromDB();
}
private void displayToastForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
String message = "ID: " + idDB + "\n"
+ "Name: " + name + "\n"
+ "Std#: " + studentNum + "\n"
+ "FavColour: " + favColour;
Toast.makeText(Prova2.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
The DBAdaptor.java
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_STUDENTNUM = "studentnum";
public static final String KEY_FAVCOLOUR = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_STUDENTNUM = 2;
public static final int COL_FAVCOLOUR = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_STUDENTNUM, KEY_FAVCOLOUR};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_STUDENTNUM + " integer not null, "
+ KEY_FAVCOLOUR + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// 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 name, int studentNum, String favColour) {
/*
* 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_NAME, name);
initialValues.put(KEY_STUDENTNUM, studentNum);
initialValues.put(KEY_FAVCOLOUR, favColour);
// 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 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 name, int studentNum, String favColour) {
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_NAME, name);
newValues.put(KEY_STUDENTNUM, studentNum);
newValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
Question Following tutorial, trying to put some simple string into a database every time I press a button. I believe that the "usernames" are being entered into the database, while debugging it doesn't do anything funny. My problem is when I want to call databaseToString(), I set a Cursor to the first entry. But subsequently it doesn't even enter while(!c.isAfterLast()). What is going on? I want it dbString to pretty much be equal to the database in plaintext, but that's not happening. Thanks
Attempts
Checked around SO/Google/API guide/thenewboston source code
Tried viewing my SQLite database, but I'm not sure how to do that so I couldn't
If you comment out databaseToString then I guess it runs, but it just sits there.
It also crashes when I set Text.setText(dbString); but that's completely unrelated
LogCat It doesn't crash, if needed I'll post.
SearchActivity.Java INSERT GETS CALLED WHEN THE BUTTON IS CLICKED
public class SearchActivity extends ActionBarActivity {
EditText Input;
TextView Text;
Database dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Input = (EditText) findViewById(R.id.Input);
dbHandler = new Database(this, null, null, 1);
// printDatabase();
}
// Add a user to database
public void insert(View view) {
Users user = new Users(Input.getText().toString());
dbHandler.addUser(user);
printDatabase();
}
public void printDatabase() {
// dbString is returning null
String dbString = dbHandler.databaseToString();
//Technically it starts to crash right at this line
Text.setText(dbString);
Input.setText("");
}
}
Users.java
public class Users {
private int _id;
private String _username;
public Users() {
}
public Users(String username){
this._username = username;
}
public String get_username() {
return _username;
}
public void set_username(String username) {
this._username = username;
}
public int get_id() {
return _id;
}
public void set_id(int id) {
this._id = id;
}
}
Database.java aka Handler. Look at databaseToString() and the while loop isn't entered whatsoever for some reason.
public class Database extends SQLiteOpenHelper {
// Version number to upgrade database version
// each time if you Add, Edit table, you need to change
// the version number
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "users.db";
private static final String TABLE_USERS = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public Database(Context context, String DATABASE_NAME, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// There must be a ',' in between every column definition
String query = "CREATE TABLE " + TABLE_USERS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USERNAME + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_USERS);
onCreate(db);
}
//Add a new row to the db
public void addUser(Users user){
ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, user.get_username());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_USERS, null, values);
db.close();
}
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_USERS + " WHERE 1";
// Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
// Move to the first row in your results
c.moveToFirst();
while(!c.isAfterLast()) {
if(c.getString(c.getColumnIndex("username")) != null) {
dbString += c.getString(c.getColumnIndex("username"));
dbString += "\n";
}
}
db.close();
return dbString;
}
}
Fixing the NullPointerException:
First, to fix the NullPointerException, initialize Text in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Input = (EditText) findViewById(R.id.Input);
Text = (TextView) findViewById(R.id.Text); //added
dbHandler = new Database(this, null, null, 1);
// printDatabase();
}
Debugging tips:
In order to make sure that insertion into the database is successful, capture the return value of insert():
long retVal = db.insert(TABLE_USERS, null, values);
Then, to verify that data is present in the Cursor, get the count of the Cursor:
Cursor c = db.rawQuery(query, null);
int count = c.getCount(); //added
Solution:
Finally, there are a few things to add here. First, you need to progress the Cursor in order to not have an infinite loop. Also, you should check the return value of moveToFirst(), and do nothing if it returns false.
Lastly, you should close the Cursor when you're done with it, otherwise you'll have a memory leak.
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_USERS + " WHERE 1";
// Cursor point to a location in your results
Cursor c = db.rawQuery(query, null);
// Move to the first row in your results
//check that moveToFirst returns true
if (c.moveToFirst()){
while(!c.isAfterLast()) {
if(c.getString(c.getColumnIndex("username")) != null) {
dbString += c.getString(c.getColumnIndex("username"));
dbString += "\n";
}
c.moveToNext(); //added
}
}
c.close(); //added
db.close();
return dbString;
}
Maybe this helps you:
The simplest way is this:
while (cursor.moveToNext()) {
...
}
The cursor starts before the first result row, so on the first
iteration this moves to the first result if it exists. If the
cursor is empty, or the last row has already been processed, then the
loop exits neatly.
What's the best way to iterate an Android Cursor?
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.
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.