Eclipse data not inserting into SQLite Database and crashing - java

When I click on the button, it's supposed to store the typed data into the database, along with the longitude and latitude that has been collected from a separate activity. I'm unsure what I did wrong, my other database works fine. Any help would be appreciated. I'll post the code below:
This is the activity java.
public class NoteActivity extends Activity implements OnClickListener {
Button buttonLeaveNote;
private EditText mTitle;
private EditText mDesc;
protected NoteDBHelper noteDB = new NoteDBHelper(NoteActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
buttonLeaveNote = (Button) findViewById(R.id.buttonLeaveNote);
buttonLeaveNote.setOnClickListener(this);
mTitle = (EditText)findViewById(R.id.etitle);
mDesc = (EditText)findViewById(R.id.edesc);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.note, menu);
return true;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonLeaveNote:
String title = mTitle.getText().toString();
String desc = mDesc.getText().toString();
Intent intent = getIntent();
String lati = intent.getExtras().getString("lati");
String lng = intent.getExtras().getString("lng");
boolean invalid = false;
if(title.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter a title", Toast.LENGTH_SHORT).show();
}
else
if(desc.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter description", Toast.LENGTH_SHORT).show();
}
else
if(invalid == false)
{
addEntry(title, desc, lati, lng);
Intent i_note = new Intent(NoteActivity.this, JustWanderingActivity.class);
startActivity(i_note);
//finish();
}
break;
}
}
public void onDestroy()
{
super.onDestroy();
noteDB.close();
}
private void addEntry(String title, String desc, String lati, String lng)
{
SQLiteDatabase notedb = noteDB.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", title);
values.put("desc", desc);
values.put("lati", lati);
values.put("lng", lng);
try
{
long newRowId;
newRowId = notedb.insert(NoteDBHelper.DATABASE_TABLE_NAME, null, values);
Toast.makeText(getApplicationContext(), "Note successfully added", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This is the SQLite DB Java
public class NoteDBHelper extends SQLiteOpenHelper
{
private SQLiteDatabase notedb;
public static final String NOTE_ID = "_nid";
public static final String NOTE_TITLE = "title";
public static final String NOTE_DESC = "desc";
public static final String NOTE_LAT = "lati";
public static final String NOTE_LONG = "lng";
NoteDBHelper noteDB = null;
private static final String DATABASE_NAME = "stepsaway.db";
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_TABLE_NAME = "notes";
private static final String DATABASE_TABLE_CREATE =
"CREATE TABLE" + DATABASE_TABLE_NAME + "(" +
"_nid INTEGER PRIMARY KEY AUTOINCREMENT," +
"title TEXT NOT NULL, desc LONGTEXT NOT NULL, lati TEXT NOT NULL, lng, TEXT NOT NULL);";
public NoteDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
#Override
public void onCreate(SQLiteDatabase notedb) {
try{
notedb.execSQL(DATABASE_TABLE_CREATE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase notedb, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public Cursor rawQuery(String string, String[] strings) {
// TODO Auto-generated method stub
return null;
}
public void open() {
getWritableDatabase();
}
public Cursor getDetails(String text) throws SQLException
{
Cursor mCursor =
notedb.query(true, DATABASE_TABLE_NAME,
new String[]{NOTE_ID, NOTE_TITLE, NOTE_DESC, NOTE_LAT, NOTE_LONG},
NOTE_TITLE + "=" + text,
null, null, null, null, null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
}
Here's the logcat
FATAL EXCEPTION: main
java.lang.NullPointerException
atcom.example.stepsaway.NoteActivity.onClick(NoteActivity.java:53)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Here's the putExtra() calls.
tvLatitude.setText("Latitude:" + location.getLatitude());
tvLongitude.setText("Longitude:" + location.getLongitude());
String lati = tvLatitude.getText().toString();
String lng = tvLongitude.getText().toString();
Intent i = new Intent(this, NoteActivity.class);
i.putExtra("lati", lati);
i.putExtra("lng", lng);

Without logcat its very difficult to help you... so also post logcat
One mistake is in your create table query inside your NoteDBHelper class...
you are forgetting to put space between keyword table and table name (DATABASE_TABLE_NAME)
So either change to:
private static final String DATABASE_TABLE_CREATE =
"CREATE TABLE " + DATABASE_TABLE_NAME + "(" +
"_nid INTEGER PRIMARY KEY AUTOINCREMENT," +
"title TEXT NOT NULL, desc LONGTEXT NOT NULL, lati TEXT NOT NULL, lng, TEXT NOT NULL);";
Or to:
public static final String DATABASE_TABLE_NAME = " notes";
PS.
NullPointerException
Check for null before using intent.getExtras() and also make sure you are passing String Not double in intent.putExtra()
intent.putExtra("lati","CheckHere it must be String not double");
intent.putExtra("lng","CheckHere it must be String not double");
And also following code would avoid the crash and will help you to debug properly
Intent intent = getIntent();
if(intent != null)
{
String lati = intent.getExtras().getString("lati");
String lng = intent.getExtras().getString("lng");
if(lati == null)
{
Log.e("Checking lati","Its Null");
lati="0";
}
if(lng == null)
{
Log.e("Checking lng","Its Null");
lng="0";
}
}
else
{
Log.e("Checking intent","Its Null");
}

The addentry method should be called as follows:
noteDB.addEntry(title, desc, lati, lng);

Related

Receive data from database based on user input in EditText

I have a quick question, I'm sure I'm just making a small mistake but I can't figure it out.I'm trying to get information from the database based on what the user inputs in an EditText. I'm getting error
"java.lang.IllegalStateException: Couldn't read row 0, col 1 from
CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.".
Here's My Main Activity Class
public class MainActivity extends AppCompatActivity {
Button create;
Button retrieve;
Button save;
Button clear;
EditText listName;
EditText listDetails;
ToDoListDatabase myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new ToDoListDatabase(this);
create = (Button)findViewById(R.id.createButton);
retrieve = (Button)findViewById(R.id.retrieveButton);
save = (Button)findViewById(R.id.saveButton);
clear = (Button)findViewById(R.id.clearButton);
listName = (EditText)findViewById(R.id.listName);
listDetails = (EditText)findViewById(R.id.listDetails);
create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddList();
}
});
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
}
//Method Resets EditText back to default
public void resetEditText(){
listName.setText("");
listDetails.setText("");
}
//Method Adds List Entered By User To DataBase
public void AddList(){
boolean isInserted = myDb.insertData(listName.getText().toString(), listDetails.getText().toString());
if(isInserted == true){
Toast.makeText(MainActivity.this,"List " + listName.getText().toString() + " successfully created", Toast.LENGTH_LONG).show();
resetEditText();
}
else
Toast.makeText(MainActivity.this,"Error creating list", Toast.LENGTH_LONG).show();
}
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
}
Here's My DataBase Class
public class ToDoListDatabase extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "List_db";
public static final String TABLE_NAME = "List_Table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LIST";
public ToDoListDatabase(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,LIST TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXITS" + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String list) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_3, list);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) { //returns -1 if not inserted
return false;
} else
return true;
}
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME = '" +listName+"'" , null);
return res;
}
}
Here's my Android Monitor
10-10 13:11:41.618 2643-2643/com.example.stephen.todolist E/AndroidRuntime: FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at com.example.stephen.todolist.MainActivity.showList(MainActivity.java:79)
at com.example.stephen.todolist.MainActivity$2.onClick(MainActivity.java:47)
at android.view.View.performClick(View.java:4439)
at android.widget.Button.performClick(Button.java:139)
at android.view.View$PerformClick.run(View.java:18395)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Your ToDoListDatabase class does not contain any field with name listName on which you are calling getText(). Also you are not passing any parameter in your getList(). You should pass your EditText query in this getList() and then create query on this param.
Changes:
MainActivy.java
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showList(listName.getText().toString());
}
});
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
//return;
}
}
StringBuffer buffer = new StringBuffer();
buffer.append(res.getString(2));
listDetails.setText(buffer); //Not working yet!!!!
}
ToDoListDatabase.java
public Cursor getList(String listName) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT LIST FROM " + TABLE_NAME + " WHERE NAME ='" + listName+"'" , null);
return res;
}
Update
Change your showList as
public void showList(String listName){
Cursor res = myDb.getList(listName);
if(res.getCount() == 0){
Toast.makeText(MainActivity.this,"Error finding list", Toast.LENGTH_LONG).show();
return;
}
res.moveToFirst();
StringBuffer buffer = new StringBuffer();
while (!res.isAfterLast()) {
buffer.append(res.getString(0));
res.moveToNext();
}
res.close();
listDetails.setText(buffer); //Not working yet!!!!
}
You are using listName (Edidtext) in your SQLiteOpenHelper class so u r getting error kindly pass the value of listName from your activity to method like.
//call and pass value like this.
showList(listName.getText().toString());
//or like this
String mListname = listName.getText().toString();
if(!TextUtils().isEmpty(mListname))//check if not empty
{
showList(mListname);
}else{
//handle error
}
// your method
public void showList(String listName)
{
//your implementation
}
SQLiteOpenHelper doesnt extends View so u cannot use view there.
but u can pass it to method parameter to access it.
showList(EditText listName)
{
String val = listName.getText().toString();
}
//and pass your editText
showList(listName);
Good programming practice for database and databesehelper to wrap them around another class, open database when needed not on every query and making queries with strings not with views themselves. Check this thread for creating a singleton DatabaseManager and execute queries with it.

Cant Find Database file in Eclipse for Android

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.

Android SQL query nullpointer can't get the data from database

here is the LogCat
I can't post image so i put it in google drive
link here
////////And here is the DB///////
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;
public class UserDB {
public static final String TABLE_USER = "User";
public static final String ID = "ID";
public static final String USERNAME = "USERNAME";
public static final String PASSWORD = "PASSWORD";
public static final String CHKPASSWORD = "CHKPASSWORD";
public static final String SEX = "SEX";
public static final String eat = "eat";
public static final String drink = "drink";
public static final String smoke = "smoke";
public static final String conctrolweigh = "conctrolweigh";
public static final String blosuger = "blosuger";
public static final String hospital = "hospital";
private Context Context = null;
public static final String Education = "Education";
public static class DatabaseHelper extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "diabetes.db";
private static final int DATABASE_VERSION = 1;
//usertable
public DatabaseHelper(Context context, CursorFactory factory) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public static final String TABLE_USER_CREATE =
"CREATE TABLE " + TABLE_USER
+ "("
+ ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ USERNAME + " text , "
+ PASSWORD+ " text ,"
+ CHKPASSWORD+ " text ,"
+ SEX+ " text ,"
+ eat + " text , "
+ drink + " text, "
+ smoke + " text, "
+ conctrolweigh + " text, "
+ blosuger + " text, "
+ hospital + " text, "
+ Education + " text);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
// 每次成功打開資料庫後首先被執行
}
#Override
public synchronized void close() {
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_USER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROPB TABLE IF EXISTS " + TABLE_USER);
onCreate(db);
}
}
public DatabaseHelper dbHelper;
public SQLiteDatabase db;
public UserDB(Context context){
this.Context = context;
DatabaseHelper openHelper = new DatabaseHelper(this.Context);
this.db = openHelper.getWritableDatabase();
}
public UserDB open() throws SQLException{
dbHelper = new DatabaseHelper(Context);
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
//add user
public void insertEntry(String ID, String PWD,String CHPW,String SEX,String eat,String drink,String smoke,String conctrolweigh,String blosuger,String hospital,String Education){
if (PWD.equals(CHPW)){
ContentValues newValues = new ContentValues();
newValues.put("USERNAME", ID);
newValues.put("PASSWORD", PWD);
newValues.put("CHKPASSWORD", CHPW);
newValues.put("SEX", SEX);
newValues.put("eat", eat);
newValues.put("drink", drink);
newValues.put("smoke", smoke);
newValues.put("conctrolweigh", conctrolweigh);
newValues.put("blosuger", blosuger);
newValues.put("hospital", hospital);
newValues.put("Education", Education);
db.insert(TABLE_USER, null, newValues);
}else{
}
}
public String getSinlgeEntry(String userName) {
Cursor cursor = db.query("User", null, " USERNAME=?",
new String[] { userName }, null, null, null);
if (cursor.getCount() < 1) // UserName Not Exist
return "Not Exist";
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
return password;
}
public SQLiteDatabase getReadableDatabase() {
// TODO Auto-generated method stub
return null;
}
}
//////here is the Activity//////////
public class SelfteachingActivity extends Activity {
Button btnselback,tvartical ,tvfood,tvhealth,tvexcise;
TextView tvid,tvstore,tveat,tvhospital,tvblosuger,tvconctrolweigh,tvdrink,tvsmoke,tvSEX,tvEducation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selfteaching);
findViews();
setListeners();
//openDatabase();
String username= (this.getIntent().getExtras().getString("username"));
tvstore.setText(username);
tvid.setText(tvstore.getText().toString());
query();
}
private void query() {
UserDB helper = new UserDB(this);
SQLiteDatabase db = helper.getReadableDatabase();
helper.open();
if(helper.getReadableDatabase() == null){
Log.i("Log Activity Test", "helper is null!!!!!!!!!");
}
String user = tvstore.getText().toString();
try {
Log.i("Log Activity Test", "start db!!");
Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);
if(cursor!=null){
int rows_num = cursor.getCount();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Integer Id = cursor.getInt(cursor.getColumnIndex("id"));
tvSEX.setText(cursor.getString(cursor.getColumnIndex("SEX")));
tvhospital.setText(cursor.getString(cursor.getColumnIndex("hospital")));
tvblosuger.setText(cursor.getString(cursor.getColumnIndex("blosuger")));
tvdrink.setText(cursor.getString(cursor.getColumnIndex("drink")));
tvconctrolweigh.setText(cursor.getString(cursor.getColumnIndex("conctrolweigh")));
tvsmoke.setText(cursor.getString(cursor.getColumnIndex("smoke")));
tvEducation.setText(cursor.getString(cursor.getColumnIndex("Education")));
tveat.setText(cursor.getString(cursor.getColumnIndex("eat")));
cursor.moveToNext();
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
}
private long exitTime = 0;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
if((System.currentTimeMillis()-exitTime) > 2000){
Toast.makeText(getApplicationContext(), "再按一次返回鍵退出", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void findViews(){
btnselback = (Button)findViewById(R.id.buttonselback);
tvartical = (Button)findViewById(R.id.buttonartical);
tvfood = (Button)findViewById(R.id.buttonfood);
tvhealth = (Button)findViewById(R.id.buttonhealth);
tvexcise = (Button)findViewById(R.id.buttonescise);
tvid = (TextView)findViewById(R.id.tVsid);
tvstore = (TextView)findViewById(R.id.tvstore);
tveat = (TextView)findViewById(R.id.tveat);
tvhospital= (TextView)findViewById(R.id.tvhospital);
tvblosuger= (TextView)findViewById(R.id.tvblosuger);
tvconctrolweigh= (TextView)findViewById(R.id.tvconctrolweigh);
tvdrink= (TextView)findViewById(R.id.tvdrink);
tvsmoke= (TextView)findViewById(R.id.tvsmoke);
tvSEX= (TextView)findViewById(R.id.tvSEX);
tvEducation= (TextView)findViewById(R.id.tvEducation);
}
private void setListeners(){
//回上一頁
btnselback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, LoginActivity.class);
intent.putExtra("username", username );
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//衛教文章
tvartical.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, ArticalActivity.class);
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("username", username );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//食物衛教
tvfood.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, FoodActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//健康衛教
tvhealth.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, HealthActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
//運動衛教
tvexcise.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = tvstore.getText().toString();
Intent intent = new Intent();
intent.setClass(SelfteachingActivity.this, ExciseActivity.class);
intent.putExtra("username", username );
intent.putExtra("SEX", tvSEX.getText().toString() );
intent.putExtra("hospital", tvhospital.getText().toString());
intent.putExtra("blosuger", tvblosuger.getText().toString() );
intent.putExtra("drink", tvdrink.getText().toString() );
intent.putExtra("conctrolweigh", tvconctrolweigh.getText().toString());
intent.putExtra("smoke", tvsmoke.getText().toString());
intent.putExtra("Education", tvEducation.getText().toString());
intent.putExtra("eat", tveat.getText().toString());
startActivity(intent);
SelfteachingActivity.this.finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.selfteaching, menu);
return true;
}
}
Problem:
1.i don't get any data from SQL but no crash
what is the problem with my code?
the program stop in here
Cursor cursor = db.rawQuery("SELECT SEX,hospital,blosuger,drink,conctrolweigh,smoke,Education,eat FROM User Where USERNAME ='"+user+"'", null);
and say null pointer , i check the db and is null , i don't know how this happen.
plz help me
Method that you call
SQLiteDatabase db = helper.getReadableDatabase();
returns your null due to your code:
public SQLiteDatabase getReadableDatabase() {
// TODO Auto-generated method stub
return null;
}

Order of list items populated from SQLLite DB is incorrect

I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
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_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// 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 + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer 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, String address, String user,
String pass, int port, int passive) {
/*
* 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_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// 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, String address,
String username, String password, int port, int passive) {
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_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// 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);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);

problem in database in android

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.

Categories

Resources