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

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;
}

Related

Android Studio + Database - Multiple check data to insert data if not exists

I'm having a problem with my code. I don't know how to check multiple columns in the database to insert different data on every not existing data.
For example:
1st input
Name: Raymond Jay Berin
Event: INTRAMURALS
FACILITATOR: CSG
2nd input
Name: Raymond Jay Berin
Event: LOVE SYMPOSIUM
FACILITATOR: DSSC
the thing here is that. Raymond Jay Berin already existed in the database, but I want Raymond Jay Berin will be inserted into a different event...
also, I already tried to create multiple tables but my project crashes when I click the attendance button to add data.
Code for DatabaseHelper.class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.sqlite";
public static final String TABLE_NAME = "attendance";
public static final String COL_1 = "ID";
public static final String COL_2 = "FULLNAME";
public static final String COL_EVENT_2 = "EVENT_NAME";
public static final String COL_EVENT_3 = "FACILITATOR_NAME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
//ATTENDANCE
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"FULLNAME TEXT NOT NULL, EVENT_NAME TEXT NOT NULL, FACILITATOR_NAME TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//ATTENDANCE
db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME );
//recreate
onCreate(db);
}
//ATTENDANCE
public boolean insertData (String fullname, String event, String facilitator){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,fullname);
contentValues.put(COL_EVENT_2,event);
contentValues.put(COL_EVENT_3,facilitator);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean checkIfRecordExist(String nameOfTable,String columnName,String columnValue) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT "+columnName+" FROM "+nameOfTable+" WHERE "+columnName+"='"+columnValue+"'",null);
if (cursor.moveToFirst()) {
db.close();
Log.d("Record Already Exists", "Table is:" + nameOfTable + " ColumnName:" + columnName);
return true;//record Exists
}
Log.d("New Record ", "Table is:" + nameOfTable + " ColumnName:" + columnName + " Column Value:" + columnValue);
db.close();
} catch (Exception errorException) {
Log.d("Exception occured", "Exception occured " + errorException);
db.close();
}
return false;
} }
Code for the Attendance.java class
public class Attendance extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DatabaseHelper myDb;
EditText fname , eventname, faciname;
Button attendance;
Button view;
Switch lock;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
myDb = new DatabaseHelper(this);
fname = findViewById(R.id.txtFullname);
eventname = findViewById(R.id.eventname);
faciname = findViewById(R.id.faciname);
attendance = findViewById(R.id.btnatt);
view = findViewById(R.id.btnview);
lock = findViewById(R.id.switchLock);
viewAll();
AddData();
lock.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (lock.isChecked()){
eventname.setEnabled(false);
faciname.setEnabled(false);
}else{
eventname.setEnabled(true);
faciname.setEnabled(true);
}
}
public void viewAll() {
view.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
// show message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("ID :" + res.getString(0) + "\n");
buffer.append("NAME :" + res.getString(1) + "\n");
buffer.append("EVENT :" + res.getString(2) + "\n");
buffer.append("FACILITATOR :" + res.getString(3) + "\n"+"\n");
}
// Show all data
showMessage("ATTENDANCE LIST", buffer.toString());
}
}
);
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
public void AddData() {
attendance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String valInput = fname.getText().toString();
final String valInput1 = eventname.getText().toString();
final String valInput2 = faciname.getText().toString();
boolean valid = true;
if (TextUtils.isEmpty(valInput)) {
fname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput1)) {
eventname.setError("This Item must not be empty!");
valid = false;
}
if (TextUtils.isEmpty(valInput2)) {
faciname.setError("This Item must not be empty!");
valid = false;
}
if (valid) {
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString());
if (!isExist) {
boolean isInserted = myDb.insertData(fname.getText().toString(), eventname.getText().toString(), faciname.getText().toString());
if (isInserted) {
Toast.makeText(Attendance.this, "Attendance Success", Toast.LENGTH_LONG).show();
fname.setText(null);
} else if (isInserted == false) {
Toast.makeText(Attendance.this, "Failed to Attendance", Toast.LENGTH_LONG).show();
}
}else if (isExist == true){
Toast.makeText(Attendance.this, "Failed to Attendance "+fname+" Already Existed", Toast.LENGTH_LONG).show();
}
}
}
}); }
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.Logout)
.setMessage(R.string.really_logout)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
Intent intent = new Intent(Attendance.this, MainActivity.class);
startActivity(intent);
Attendance.this.finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}}
change checkIfRecordExist method like this
public boolean checkIfRecordExist(String nameOfTable,String columnName1,String columnValue1,String columnName2,String columnValue2) {
SQLiteDatabase db = null;
try {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+nameOfTable+" WHERE "+columnName1+"='"+columnValue1+"' and "+ columnName2 +"='"+columnValue2+"'",null);
.......................
change below line like this
boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString(),DatabaseHelper.COL_2, eventname.getText().toString())

How to insert and retrieve data display button using sqlite

I cant't get all data to display in button when click on button get. please help me.
public class DBHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
private static final String DATABASE = "Test";
private static final String TABLE_NAME = "savedata";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_SEX = "sex";
public DBHelper(Context context) {
super(context, DATABASE, null,VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS " +TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NAME + " TEXT,"
+ KEY_SEX + " TEXT)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" +TABLE_NAME);
onCreate(db);
}
public void Insertdata(Data data){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, data.getName());
values.put(KEY_SEX, data.getSex());
db.insert(TABLE_NAME, null, values);
}
public List<Data> getAllData(){
List<Data> listData = new ArrayList<Data>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM " +TABLE_NAME, null);
if (c.moveToFirst()){
do {
Data data = new Data();
data.setId(c.getInt(0));
data.setName(c.getString(1));
data.setSex(c.getString(2));
listData.add(data);
}while (c.moveToNext());
}
return listData;
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
SaveData();
getData();
}
public void SaveData(){
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void getData(){
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
You've messed up badly. That's all I can suggest-
1. Create a class (for example "MyClass") that will extend AppCompatActivity and contains the view.
2. You've already created a class named DBHelper for your Database manipulation. It extends SQLiteOpenHelper.
3. Create object of DBHelper class inside the onCreate method of MyClass and access your database. onCreate method in MyClass will be looking similar to this-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.edit_name);
sex = (EditText)findViewById(R.id.edit_sex);
btn_get = (Button)findViewById(R.id.btn_get);
btn_name = (Button)findViewById(R.id.btn_name);
btn_sex = (Button)findViewById(R.id.btn_sex);
btn_id = (Button)findViewById(R.id.btn_id);
db = new DBHelper(this);
_name = name.getText().toString();
_sex = sex.getText().toString();
data = new Data(_name,_sex);
btn_save =( Button)findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
db.Insertdata(data);
Toast.makeText(getApplicationContext(), "SuccessFull",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
btn_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (currentData == null){
Toast.makeText(getApplicationContext(),"Null", Toast.LENGTH_SHORT).show();
}else {
currentData = db.getAllData();
btn_id.setText(String.valueOf(data.getId()));
btn_name.setText(data.getName());
btn_sex.setText(data.getSex());
}
}catch (Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
Hope that, this might help.

How to store and fetch list view data from sqlite in android?

I have created a simple demo in which I have simply stored the two value that is first name and last name in sqlite and display that in list view.But when I tried two add more value like phone no.address,state,country etc . I got error.and it display the message like could not read the row and column data.
please help me two add 9 or 10 value and display in list view.here is my code.
AddActivity.Java
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,phoneNo;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,pno;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
phoneNo=(EditText)findViewById(R.id.phoneNo);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
pno=getIntent().getExtras().getString("Pno");
edit_first.setText(fname);
edit_last.setText(lname);
phoneNo.setText(pno);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
pno=phoneNo.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_PHONENO,pno );
System.out.println("");
if(isUpdate)
{
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
dataBase.close();
finish();
}
}
DisplayAdapter.java
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> phoneNo;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname,ArrayList<String> pno) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.phoneNo = pno;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.phoneTextView = (TextView) child.findViewById(R.id.phoneTextView);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.phoneTextView.setText(phoneNo.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView phoneTextView;
}
}
Database Helper.java
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_PHONENO="pno";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_PHONENO+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
DisplayActivity.java
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_phoneNo = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("Lname", user_phoneNo.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+user_phoneNo.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_phoneNo.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_phoneNo.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_PHONENO)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName,user_phoneNo);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Below is an example of storing and fetching data from database.
public class Database extends SQLiteOpenHelper {
public static final String KEY_ID= "id";
public static final String KEY_SURVEY_UPLOAD = "IS_SURVEY_UPLOAD";
public static final String KEY_SURVEY_COMPLETE = "IS_SURVEY_COMPLETE";
public static final String KEY_DEVICE_ID = "DEVICE_ID";
public static final String KEY_LATITUDE = "LATITUDE";
public static final String KEY_LONGITUDE = "LONGITUDE";
public static final String KEY_FILE_ID = "FILE_ID";
public static final String DATABASE_NAME = "DatabaseName";
public static final String DATABASE_TABLE_one = "Table1";
private static final String CREATE_TABLE__NUM = "create table "+DATABASE_TABLE_SURVEY+
" ("+KEY_SURVEY_COMPLETE+" TEXT,"+KEY_FILE_ID+" INTEGER,"+KEY_DEVICE_ID+" TEXT,"+KEY_LATITUDE+" TEXT, "+KEY_LONGITUDE+" TEXT, "+KEY_SURVEY_UPLOAD+" TEXT, "+KEY_SURVEYID+" INTEGER PRIMARY KEY AUTOINCREMENT )";
public Database(Context context, String name, CursorFactory factory,
int version) {
super(context, name, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
System.out.println("crteate table");
db.execSQL(CREATE_TABLE_SURVEY_CONTENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_one);
onCreate(db);
}
public boolean insertData(SurveyBean bean)
{
System.out.println("insert_SURVEY");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURVEY_COMPLETE, "false");
contentValues.put(KEY_SURVEY_UPLOAD, "0");
contentValues.put(KEY_LATITUDE, bean.getLatitude());
contentValues.put(KEY_LONGITUDE, bean.getLongitude());
contentValues.put(KEY_DEVICE_ID, bean.getDeviceId());
contentValues.put(KEY_FILE_ID, Integer.getInteger(bean.getFileId()));
long id=db.insert(DATABASE_TABLE_SURVEY, null, contentValues);
System.out.println("last inserted ID"+id);
db.close();
return true;
}
public ArrayList<SurveyBean> getAllData(){
ArrayList<SurveyBean> arrayList = new ArrayList<SurveyBean>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cc = db.rawQuery("SELECT *" + " FROM " + DATABASE_TABLE_SURVEY, null);
cc.moveToFirst();
while(cc.isAfterLast() == false){
SurveyBean bean = new SurveyBean();
bean.set_isSurveyComplete(cc.getString(cc.getColumnIndex(KEY_SURVEY_COMPLETE)));
bean.set_isSurveyUpload(cc.getString(cc.getColumnIndex(KEY_SURVEY_UPLOAD)));
bean.set_surveyId(Integer.parseInt(cc.getString(cc.getColumnIndex(KEY_SURVEYID))));
bean.setDeviceId(cc.getString(cc.getColumnIndex(KEY_DEVICE_ID)));
bean.setLatitude(cc.getString(cc.getColumnIndex(KEY_LATITUDE)));
bean.setLongitude(cc.getString(cc.getColumnIndex(KEY_LONGITUDE)));
bean.setFileId(String.valueOf(cc.getInt(cc.getColumnIndex(KEY_FILE_ID))));
arrayList.add(bean);
cc.moveToNext();
}
db.close();
return arrayList ;
}
}
Look i had done a simple app to create a list view from sqlite database in android. Have a look at it.It may help you.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "testdb";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "tbl_details";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
} else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
tableName +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('A','vijay','India',20);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('B','ajay','Pakistan',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C','suraj','Bangladesh',30);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D','jayesh','China',35);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('E','ramesh','Nepal',40);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('F','suresh','SriLanka',45);");
}
}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ListViewFromSQLiteDB"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="com.example.ListViewFromSQLiteDB.DataListView"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ListViewFromSQLiteDB.java
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class DataListView extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
}

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.

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);

Categories

Resources