SQlite null database - java

I am building a simple bank app (no security what so ever) and have a login activity that verifies the input with an SQLite database. My method returns 1 if is a match and 0 if not. The problem is it always returns 0 because the database is null according to debug. I'm not sure why the variable I use in the login method is null. The data insert is working as I've checked using SQLite browser.
Here is the SQLite database with the login() method at the bottom:
public class CustomerDatabase{
private SQLiteDatabase database;
private SQLiteOpenHelper openHelper;
//Database constants
public static final String DB_Name = "customers.db";
public static final int DB_Version = 1;
public static final String CUSTOMER_TABLE = "Customers";
public static final String CARD_ACCESS_NO = "accessNo";
public static final int CARD_ACCESS_NO_COLUMN = 0;
public static final String CUSTOMER_PASSWORD = "password";
public static final int CUSTOMER_PASSWORD_COLUMN = 2;
public static final String CUSTOMER_NAME = "custName";
public static final int CUSTOMER_NAME_COLUMN = 1;
public static final String CHECKING_ACCOUNT_FUNDS = "checkAccFunds";
public static final int CHECKING_ACCOUNT_FUNDS_COLUMN = 3;
public static final String SAVINGS_ACCOUNT_FUNDS = "saveAccFunds";
public static final int SAVINGS_ACCOUNT_FUNDS_COLUMN = 4;
public static final String CHECKING_ACCOUNT_NO = "checkAccNo";
public static final int CHECKING_ACCOUNT_NO_COLUMN = 5;
public static final String SAVINGS_ACCOUNT_NO = "saveAccNo";
public static final int SAVINGS_ACCOUNT_NO_COLUMN = 6;
//DDL for creating the db
public static final String CREATE_CUSTOMER_TABLE =
"CREATE TABLE " + CUSTOMER_TABLE + " (" +
CARD_ACCESS_NO + " INTEGER PRIMARY KEY, " +
CUSTOMER_NAME + " TEXT, " +
CHECKING_ACCOUNT_NO + " TEXT, " +
CUSTOMER_PASSWORD + " TEXT, " +
CHECKING_ACCOUNT_FUNDS + " TEXT, " +
SAVINGS_ACCOUNT_NO + " TEXT, " +
SAVINGS_ACCOUNT_FUNDS + " TEXT)";
public CustomerDatabase(Context context){
openHelper = new DBHelper(context, DB_Name, DB_Version);
}
//method to store accountHolder objects into the database
public AccountHolder saveAccHolder(AccountHolder holder){
database = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CARD_ACCESS_NO, holder.getAccessCardNo());
values.put(CUSTOMER_NAME, holder.getName());
values.put(CUSTOMER_PASSWORD, holder.getPassword());
values.put(CHECKING_ACCOUNT_FUNDS, holder.getCheckingAccountFunds());
values.put(CHECKING_ACCOUNT_NO, holder.getCheckingAccountNo());
values.put(SAVINGS_ACCOUNT_NO, holder.getSavingsAccountNo());
values.put(SAVINGS_ACCOUNT_FUNDS, holder.getSavingsAccountFunds());
long id = database.insert(CUSTOMER_TABLE, null, values);
holder.setDbId(id);
database.close();
return holder;
}
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context, String name, int version){
super(context, name, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + CUSTOMER_TABLE);
db.execSQL(CREATE_CUSTOMER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
db.execSQL("DROP TABLE IF EXISTS " + CUSTOMER_TABLE);
onCreate(db);
}
}
/**Method will be used by the bank to check if user is authorized */
public int login(String accessNo, String password){
String[] selectArgs = new String[]{accessNo,password};
try{
int i = 0;
Cursor cursor = null;
cursor = database.rawQuery("SELECT * FROM CUSTOMER_TABLE WHERE accessNo =? AND password=?",selectArgs);
cursor.moveToFirst();
i = cursor.getCount();
cursor.close();
return i;
}
catch (Exception e){ e.printStackTrace();}
return 0;
}
}
Debug says that the database variable is null at login() at line cursor = database.rawQuery()...
Here is the login activity logic:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtAccessCardNo.length() != 0 || edtPassword.length() != 0){
String accessNoInput = edtAccessCardNo.getText().toString();
String passwordInput = edtPassword.getText().toString();
boolean checkVerify = isVerifiedUser(accessNoInput, passwordInput);
if(checkVerify){
Intent intent = new Intent(getApplicationContext(), BankActivity.class);
startActivity(intent);
}else{
txtErrorDisplay.setText("Unable to login.");
}
}else{
edtAccessCardNo.setHint("This is a required field");
edtPassword.setHint("This is a required field");
}
}
});
}
//Method to create dummy accountHolder objects
public void getAndSaveDummyHolders(){
CustomerDatabase custDb = new CustomerDatabase(this);
for(int i = 0; i < 5; i++){
AccountHolder holder = new AccountHolder(
holderNames[i], accessNo[i],
passwords[i], checkAccNo[i], savAccNo[i],
checkAccFunds[i], savAccFunds[i]);
custDb.saveAccHolder(holder);
}
}
//verify the user using method in customer database
public boolean isVerifiedUser(String userAccessCard, String userPassword){
CustomerDatabase custDb = new CustomerDatabase(getApplicationContext());
int check = custDb.login(userAccessCard, userPassword);
if(check == 1){
return true;
}else{
return false;
}
}

Related

Difficult to store Shared preferences value to SQLIte in Android and having null value stored

I think i ran out from ideas about how to do this. I am building and TODO app with register and login feature. Once a user is logged, can create new todos task in SQLite(for now), later i want to delete and rename todos as well.
This is my DB class with SQliteHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id"; //autoincrement
private final static String user_Id = "userId";
private final static String TITLE = "title";
private final static String CONTENT = "content";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" +
")";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// this.ctx = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_mTODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
Adding new Task to second table
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(ctx);
// String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
// values.put(user_Id,todoTask.getUserID(d));
// Inserting Row
db.insert(mTODO, null, values);
db.close();
}
ToDo.java
public class ToDo {
private int id;
private String userID;
private String title;
private String content;
public ToDo(String content, int id, String title, String userID) {
this.content = content;
this.id = id;
this.title = title;
this.userID = userID;
}
public ToDo(String content, String title, String userID) {
this.content = content;
this.title = title;
this.userID = userID;
}
public ToDo() {
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId(String name) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUserID(String userID) {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
Add activity class with inputs and add method
public class addTask extends AppCompatActivity {
private EditText titleUser;
private EditText contentDesc;
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
Button btnAdd = (Button) findViewById(R.id.addToDo);
titleUser = (EditText) findViewById(R.id.titleID);
contentDesc = (EditText) findViewById(R.id.contentDescId);
db = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddItem();
}
});
}
private void AddItem() {
ToDo todo = new ToDo();
todo.setTitle(titleUser.getText().toString().trim());
todo.setContent(contentDesc.getText().toString().trim());
db.add(todo);
finish();
}
The current user that is logged, i am putting that user id to Shared preferences
In my second Table i have something like this
task_Id user_id title content
1 null Eat go to Mc
user_id is null here, and i don't know why
i want something like this
task_Id user_id title content
1 2 Eat go to Mc
user_id- should be which user id make the todo
Supposing that you already know how to store and get the userid from the shared preferences.
In your addTask activity, add:
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
userId = sharedPreference.getString("USER_ID",null);
...
}
in the addItem() add:
private void AddItem() {
...
todo.setUserId(userId);
...
}
in the DB add() use this:
public void add(ToDo todoTask) {
...
values.put(USERID, todoTask.getUserId());
...
}
OR:
Another approach is to get the value directly from the DB class if you are sure that you will never insert task for other users.
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
values.put(user_Id,todoTask.getUserID(d));
db.insert(mTODO, null, values);
db.close();
}
and in the constructor save the context for further use.
private Context ctx;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.ctx = context;
}
You are creating ToDo Table using user_id. while static String refrenced is userid: hence in database when entered it goes null by default
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id";
private final static String user_Id = "userId"; //<----Wrong Here
private final static String TITLE = "title";
private final static String CONTENT = "content";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
Also here is something more for you, Simply you must supply the User Id value to the Field. Below are Some Examples How to do So
private static final String TAG = "DB_HANDLER";
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "ElmexContactsManager.db";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
private static final String TABLE_BIZ_SEGMENT = "BizSegment";
/*01*/private static final String KEY_LOCAL_BIZ_SEGMENT_ID = "LocalBizSegmentId";
/*02*/private static final String KEY_BIZ_SEGMENT_ID = "BizSegmentId";
/*03*/private static final String KEY_BIZ_SEGMENT = "BizSegment";
/*04*/private static final String KEY_ADDED_ON = "AddedOn";
/*05*/private static final String KEY_UPDATED_ON = "UpdatedOn";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
String CREATE_TABLE_BIZ_SEGMENT = "CREATE TABLE " + TABLE_BIZ_SEGMENT + "("
/*01*/ + KEY_LOCAL_BIZ_SEGMENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
/*02*/ + KEY_BIZ_SEGMENT_ID + " INTEGER,"
/*03*/ + KEY_BIZ_SEGMENT + " TEXT,"
/*04*/ + KEY_ADDED_ON + " TEXT,"
/*05*/ + KEY_UPDATED_ON + " TEXT"
+ ")";
public ContactDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { try {
sqLiteDatabase.execSQL(CREATE_TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_DET);
} catch (SQLException e) {
e.printStackTrace();
}
Log.d(TAG, "Table Craeted ");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// Drop older table if existed
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_DET);
// Create tables again
onCreate(sqLiteDatabase);
Log.d(TAG, "Table Udgraded to Version :" + i1);
}
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
public void addBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.insert(TABLE_BIZ_SEGMENT, null, values);
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public void updateBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
//values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.update(TABLE_BIZ_SEGMENT, values, KEY_BIZ_SEGMENT_ID + " = ?", new String[]{String.valueOf(bizSegment.getBizSegmentId())});
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public List<BizSegment> getBizSegmentAll() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
List<BizSegment> bizSegmentList = new ArrayList<BizSegment>();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_BIZ_SEGMENT;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
try {
BizSegment bizSegment = new BizSegment(cursor.getInt(0),
cursor.getInt(1),
cursor.getString(2),
df.parse(cursor.getString(3)),
df.parse(cursor.getString(4)));
bizSegmentList.add(bizSegment);
} catch (ParseException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
//2nd argument is String containing nullColumnHack
return bizSegmentList;
}
public void deleteBizSegment(BizSegment bizSegment) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_BIZ_SEGMENT, KEY_BIZ_SEGMENT_ID + " = ?",
new String[]{String.valueOf(bizSegment.getBizSegmentId())});
db.close();
}
Other method is Using Shared Preference suitable for limited Data. It does not provide any relationships. I use this to store basic User related Data. Not for complicated/Relational Large Data. For That Sqlite is preferred.
public class AppPreference {
SharedPreferences pref;
SharedPreferences.Editor edit;
/**
* #param clientMaster object to set preference
* #param context Context of call
*/
public void putPreference(ClientMaster clientMaster, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putInt("ClientId", clientMaster.getClientId());
edit.putString("FirstName", clientMaster.getFirstName());
edit.putString("LastName", clientMaster.getLastName());
edit.putString("Mobile", clientMaster.getMobile());
edit.putInt("PincodeId", clientMaster.getPincodeId());
edit.putString("Email", clientMaster.getEmail());
edit.putString("Password", clientMaster.getPassword());
edit.putString("MembershipCode", clientMaster.getMembershipCode());
edit.putString("MembershipIssueDate", clientMaster.getMembershipIssueDate().toString());
edit.putString("MembershipExpiryDate", clientMaster.getMembershipExpiryDate().toString());
edit.putString("MemberShipUpdatedOn", clientMaster.getMemberShipUpdatedOn().toString());
edit.putString("MemberShipQRCode", clientMaster.getMemberShipQRCode());
edit.putInt("ReferredByTypeID", clientMaster.getReferredByTypeID());
edit.putInt("ReferredByID", clientMaster.getReferredByID());
//edit.putString("LastPasswordUpdatedOn", clientMaster.getLastPasswordUpdatedOn().toString());
edit.putString("TempMembershipCode", clientMaster.getTempMembershipCode());
edit.putString("AddedOn", clientMaster.getAddedOn().toString());
//edit.putString("UpdatedOn", clientMaster.getUpdatedOn().toString());
edit.putBoolean("Login", true);
edit.putBoolean("Skip", false);
edit.commit();
}
/**
*
* #param appLanguage
* #param context
*/
public void putLanguagePreference(String appLanguage, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("AppLanguage", appLanguage);
edit.commit();
}
/**
* To clear All Object preference & Login False
*
* #param context Context call
*/
public void clearPreference(Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.clear();
edit.putBoolean("Login", false);
edit.commit();
}
/**
* #param InstanceId Instance Id
* #param context
*/
public void putPreferenceInstance(String InstanceId, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("InstanceId", InstanceId);
edit.commit();
}
}

Show SQL data in android layout

I have a problem with the following issue:
I have build an Android app which saves data into a SQL database (SQLite). I managed so the current date, time and the category is saved down and shown in a different menu. Somehow I am not able to get the value saved down and shown in the other layout. The data should come from an EditText: android:id="#+id/edit_betrag
The SQL column is defined like: public static final String BUDGET_BETRAG = "betrag";
and then should be shown in textView_betrag in the class BudgetRechnerAdapter respectively the other layout.
Can you please help me with this issue? Thanks a lot!!!
public class BudgetRechnerOpenHandler extends SQLiteOpenHelper {
private static final String TAG = BudgetRechnerOpenHandler.class
.getSimpleName();
// Name und Version der Datenbank
private static final String DATABASE_NAME = "budgetrechner.db";
private static final int DATABASE_VERSION = 1;
// Name und Attribute der Tabelle "Budget"
public static final String _ID = "_id";
public static final String TABELLE_NAME_BUDGET = "budget";
public static final String BUDGET_ZEIT = "zeitStempel";
public static final String BUDGET_AUSGABENART = "ausgabenArt";
public static final String BUDGET_BETRAG = "betrag";
// Konstanten für die Stimmungen
public static final int BUDGET_ESSEN = 1;
public static final int BUDGET_GETRAENK = 2;
public static final int BUDGET_SONSTIGES = 3;
// Tabelle Budget anlegen
private static final String TABELLE_BUDGET_ERSTELLEN = "CREATE TABLE "
+ TABELLE_NAME_BUDGET + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + BUDGET_ZEIT + " INTEGER, "
+ BUDGET_BETRAG + " INTEGER," + BUDGET_AUSGABENART + " INTEGER);";
// Tabelle Budget löschen
private static final String TABELLE_BUDGET_DROP = "DROP TABLE IF EXISTS "
+ TABELLE_NAME_BUDGET;
BudgetRechnerOpenHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABELLE_BUDGET_ERSTELLEN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrade der Datenbank von Version " + oldVersion + " zu "
+ newVersion + "; alle Daten werden gelöscht");
db.execSQL(TABELLE_BUDGET_DROP);
onCreate(db);
}
public void insert(int art, String beschreibung, long zeit) {
long rowId = -1;
try {
// Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
// die zu speichernden Werte
ContentValues wert = new ContentValues();
wert.put(BUDGET_AUSGABENART, art);
wert.put(BUDGET_BETRAG, beschreibung);
wert.put(BUDGET_ZEIT, zeit);
// in die Tabelle Budget einfügen
rowId = db.insert(TABELLE_NAME_BUDGET, null, wert);
} catch (SQLiteException e) {
Log.e(TAG, "insert()", e);
} finally {
Log.d(TAG, "insert(): rowId=" + rowId);
}
}
public Cursor query() {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
return db.query(TABELLE_NAME_BUDGET, null, null, null, null, null,
BUDGET_ZEIT + " DESC"
);
}
public void update(long id, int ausgabe_art_zahl) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BUDGET_AUSGABENART, ausgabe_art_zahl);
int numUpdated = db.update(TABELLE_NAME_BUDGET, values, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "update(): id=" + id + " -> " + numUpdated);
}
public void delete(long id) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
int numDeleted = db.delete(TABELLE_NAME_BUDGET, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "delete(): id=" + id + " -> " + numDeleted);
}
}
public class BudgetRechnerAdapter extends CursorAdapter {
private final Date datum;
private static final DateFormat DF_DATE = SimpleDateFormat
.getDateInstance(DateFormat.MEDIUM);
private static final DateFormat DF_TIME = SimpleDateFormat
.getTimeInstance(DateFormat.MEDIUM);
private Integer betrag;
private static final Integer DF_BETRAG = R.id.edit_betrag;
private LayoutInflater inflator;
private int ciAusgabenArt, ciZeit, ciBetrag;
public BudgetRechnerAdapter(Context context, Cursor c) {
super(context, c);
datum = new Date();
betrag = null;
inflator = LayoutInflater.from(context);
ciAusgabenArt = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_AUSGABENART);
ciZeit = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_ZEIT);
ciBetrag = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_BETRAG);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView image = (ImageView) view.findViewById(R.id.icon);
int art = cursor.getInt(ciAusgabenArt);
TextView textView_art = (TextView) view.findViewById(R.id.text3);
if (art == BudgetRechnerOpenHandler.BUDGET_ESSEN) {
image.setImageResource(R.drawable.bild_essen);
textView_art.setText("Essen");
} else if (art == BudgetRechnerOpenHandler.BUDGET_GETRAENK) {
image.setImageResource(R.drawable.bild_getraenk);
textView_art.setText("Getränk");
} else {
image.setImageResource(R.drawable.bild_sonstiges);
textView_art.setText("Sonstiges");
}
TextView textView_Datum = (TextView) view.findViewById(R.id.text1);
TextView textView_Zeit = (TextView) view.findViewById(R.id.text2);
TextView textView_betrag = (TextView) view.findViewById(R.id.text4);
long zeitStempel = cursor.getLong(ciZeit);
datum.setTime(zeitStempel);
textView_Datum.setText(DF_DATE.format(datum));
textView_Zeit.setText(DF_TIME.format(datum));
textView_betrag.setText(DF_BETRAG.toString());
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflator.inflate(R.layout.verlauf, null);
}
}

My program can not find tables in sqlite database on Android

I have SQLite database file (which I did not create in this program, and it has its tables and datas), I open it in my android program, but when I write SELECT statement program can not find tables and I get error:
Error: no such table: Person
This is code:
public class SQLiteAdapter {
private DbDatabaseHelper databaseHelper;
private static String dbfile = "/data/data/com.example.searchpersons/databases/";
private static String DB_NAME = "Person.db";
static String myPath = dbfile + DB_NAME;
private static SQLiteDatabase database;
private static final int DATABASE_VERSION = 3;
private static String table = "Person";
private static Context myContext;
public SQLiteAdapter(Context ctx) {
SQLiteAdapter.myContext = ctx;
databaseHelper = new DbDatabaseHelper(SQLiteAdapter.myContext);
}
public static class DbDatabaseHelper extends SQLiteOpenHelper {
public DbDatabaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
dbfile = "/data/data/" + context.getPackageName() + "/databases/";
myPath = dbfile + DB_NAME;
//this.myContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public SQLiteDatabase open() {
try {
database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Log.v("db log", "database exist open");
} catch (SQLiteException e) {
Log.v("db log", "database does't exist");
}
if (database != null && database.isOpen())
return database;
else {
database = databaseHelper.getReadableDatabase();
Log.v("db log", "database exist helper");
}
return database;
}
public Cursor onSelect(String firstname, String lastname) {
Log.v("db log", "database exist select");
Cursor c = database.rawQuery("SELECT * FROM " + table + " where Firstname='" + firstname + "' And Lastname='" + lastname + "'", null);
c.moveToFirst();
return c;
}
public void close() {
if (database != null && database.isOpen()) {
database.close();
}
}
}
And this is button click function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button btn1 = (Button) rootView.findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText t = (EditText) rootView.findViewById(R.id.editText1);
String name = t.getText().toString();
EditText tt = (EditText) rootView.findViewById(R.id.editText2);
String lastname = tt.getText().toString();
if (name.length() == 0 || lastname.length() == 0) {
Toast.makeText(rootView.getContext(), "Please fill both box", Toast.LENGTH_LONG).show();
} else {
GridView gridview = (GridView) rootView.findViewById(R.id.gridView1);
List < String > li = new ArrayList < String > ();
ArrayAdapter < String > adapter = new ArrayAdapter < String > (rootView.getContext(), android.R.layout.simple_gallery_item, li);
try {
SQLiteAdapter s = new SQLiteAdapter(rootView.getContext());
s.open();
Cursor c = s.onSelect(name, lastname);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(c.getColumnIndex("ID"));
String name1 = c.getString(c.getColumnIndex("Firstname"));
String lastname1 = c.getString(c.getColumnIndex("Lastname"));
String personal = c.getString(c.getColumnIndex("PersonalID"));
li.add(id);
li.add(name1);
li.add(lastname1);
li.add(personal);
gridview.setAdapter(adapter);
} while (c.moveToNext());
}
} else {
Toast.makeText(rootView.getContext(), "There is no data", Toast.LENGTH_LONG).show();
}
c.close();
s.close();
} catch (Exception e) {
Toast.makeText(rootView.getContext(), "Error : " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
return rootView;
}
I check database in SQLite Database Browser, everything is normal (There are tables and data), but program still can not find them.
I added sqlitemanager to eclipse and it can not see tables too:
There is only one table android_metadata and there are no my tables.
Can anyone help me?
I thought about it for about a week, the answer is very simple. I resolved the problem so:
from sqlitemanager
I added database from that button.
And now everything works fine ;)
In oncreate you have to create your db. I am sending you my db class.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapter extends SQLiteOpenHelper {
private static DbAdapter mDbHelper;
public static final String DATABASE_NAME = "demoDb";
public static final String TABLE_Coin= "coin_table";
public static final String TABLE_Inbox= "inbox";
public static final String TABLE_Feature= "feature";
public static final String TABLE_Time= "time";
public static final String TABLE_Deduct_money= "deduct_time";
public static final String TABLE_Unread_message= "unread_message";
public static final String COLUMN_Email= "email";
public static final String COLUMN_Appearence= "appearence";
public static final String COLUMN_Drivability= "drivability";
public static final String COLUMN_Fuel= "fuel";
public static final String COLUMN_Insurance= "insurance";
public static final String COLUMN_Wow= "wow";
public static final String COLUMN_CurrentValue= "current_value";
public static final String COLUMN_coin = "name";
public static final String COLUMN_seenTime = "seen";
public static final String COLUMN_number_of_times = "number_of_times";
public static final String COLUMN_name = "name";
public static final String COLUMN_type = "type";
public static final String COLUMN_text = "text";
public static final String COLUMN_image = "image";
public static final String COLUMN_created_time = "created_time";
public static final String COLUMN_unread = "unread";
// ****************************************
private static final int DATABASE_VERSION = 1;
private final String DATABASE_CREATE_BOOKMARK = "CREATE TABLE "
+ TABLE_Coin + "(" + COLUMN_coin
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK1 = "CREATE TABLE "
+ TABLE_Feature + "(" + COLUMN_Appearence
+ " Integer,"+COLUMN_Email +" Varchar ,"+COLUMN_name +" Varchar ,"+COLUMN_Drivability +" Integer ,"+COLUMN_Wow +" Integer,"+COLUMN_CurrentValue +" Integer,"+COLUMN_Fuel +" Integer,"+COLUMN_Insurance +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK2 = "CREATE TABLE "
+ TABLE_Time + "(" + COLUMN_Email +" Varchar ,"+COLUMN_seenTime +" Integer,"+COLUMN_number_of_times +" Integer, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK3 = "CREATE TABLE "
+ TABLE_Deduct_money + "(" + COLUMN_seenTime
+ " Varchar,"+ COLUMN_number_of_times
+ " Integer,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private final String DATABASE_CREATE_BOOKMARK4 = "CREATE TABLE "
+ TABLE_Inbox + "(" + COLUMN_created_time
+ " DATETIME,"+ COLUMN_image
+ " Varchar,"
+ COLUMN_type
+ " Varchar,"+ COLUMN_name
+ " Varchar,"+ COLUMN_text
+ " Varchar,"+COLUMN_Email +" Varchar)";
private final String DATABASE_CREATE_BOOKMARK5 = "CREATE TABLE "
+ TABLE_Unread_message + "(" + COLUMN_unread
+ " Varchar,"+COLUMN_Email +" Varchar, UNIQUE("
+ COLUMN_Email + ") ON CONFLICT REPLACE)";
private DbAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DbAdapter getInstance(Context context) {
if (mDbHelper == null) {
mDbHelper = new DbAdapter(context);
}
return mDbHelper;
}
/**
* Tries to insert data into table
*
* #param contentValues
* #param tablename
* #throws SQLException
* on insert error
*/
public void insertQuery(ContentValues contentValues, String tablename)
throws SQLException {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.insert(tablename, null, contentValues);
// writableDatabase.insertWithOnConflict(tablename, null,
// contentValues,SQLiteDatabase.CONFLICT_REPLACE);
} catch (Exception e) {
e.printStackTrace();
}
}
// public void insertReplaceQuery(ContentValues contentValues, String tablename)
// throws SQLException {
//
// try {
// final SQLiteDatabase writableDatabase = getWritableDatabase();
// writableDatabase.insertOrThrow(tablename, null, contentValues);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Update record by ID with contentValues
// *
// * #param id
// * #param contentValues
// * #param tableName
// * #param whereclause
// * #param whereargs
// */
public void updateQuery(ContentValues contentValues, String tableName,
String whereclause, String[] whereargs) {
try {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.update(tableName, contentValues, whereclause,
whereargs);
} catch (Exception e) {
e.printStackTrace();
}
}
public Cursor fetchQuery(String query) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public Cursor fetchQuery(String query, String[] selectionArgs) {
final SQLiteDatabase readableDatabase = getReadableDatabase();
final Cursor cursor = readableDatabase.rawQuery(query, selectionArgs);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public void delete(String table) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, null, null);
}
public void delete(String table, String whereClause, String[] selectionArgs) {
final SQLiteDatabase writableDatabase = getWritableDatabase();
writableDatabase.delete(table, whereClause, selectionArgs);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_BOOKMARK);
db.execSQL(DATABASE_CREATE_BOOKMARK1);
db.execSQL(DATABASE_CREATE_BOOKMARK2);
db.execSQL(DATABASE_CREATE_BOOKMARK3);
db.execSQL(DATABASE_CREATE_BOOKMARK4);
db.execSQL(DATABASE_CREATE_BOOKMARK5);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Coin);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Feature);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Time);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Deduct_money);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Inbox);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_Unread_message);
onCreate(db);
}
}
You are messing up the paths.
Please clean up every definition or reference to dbfile and myPath.You are initializing them in the definition with some values (probably copy-pasted), then giving them new different values in the DbDatabaseHelper constructor. And the helper will not use these paths, it will just create the database in the default directory.
Then after this, in the open method you are calling SQLiteDatabase.openDatabase with your intended paths. Use instead getReadableDatabase and getWritableDatabase from the Helper.

Having problems creating db conneection and creating db table

i have two class one is MainActivity.java and DBadapter.java
Main Activity looks like this Code:
public class MainActivity extends Activity {
DBadapter myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
openDB();
populateListFromDB();
}
private void onDistroy(){
super.onDestroy();
closeDB();
}
private void openDB(){
myDB = new DBadapter(this);
myDB.open();
}
public void closeDB(){
myDB.close();
}
private void populateListFromDB(){
Cursor cursor = myDB.getAllRows();
startManagingCursor(cursor);
String[] columnFromTable = new String[]
{DBadapter.KEY_NAME, DBadapter.KEY_GAMES, DBadapter.KEY_WON,
DBadapter.KEY_LOST, DBadapter.KEY_DIFF, DBadapter.KEY_POINTS};
int[] toLayoutElement = new int[]
{R.id.txtview_name, R.id.txtview_gameno, R.id.txtview_won,
R.id.txtview_lost, R.id.txtview_difference, R.id.txtview_points};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(
this, R.layout.item_layout, cursor, columnFromTable, toLayoutElement);
ListView mylistview = (ListView) findViewById(R.id.listview_tabela);
mylistview.setAdapter(myCursorAdapter);
}
}
and the DBadapter Code:
public class DBadapter {
private static final String TAG = "DBadapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "name";
public static final String KEY_GAMES = "games_no";
public static final String KEY_WON = "won";
public static final String KEY_LOST= "lost";
public static final String KEY_DIFF="difference";
public static final String KEY_POINTS="points";
public static final int COL_NAME = 1;
public static final int COL_GAMES = 2;
public static final int COL_WON = 3;
public static final int COL_LOST= 4;
public static final int COL_DIFF= 5;
public static final int COL_POINTS= 6;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_GAMES, KEY_WON, KEY_LOST, KEY_DIFF, KEY_POINTS};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "mydaatabase";
public static final String DATABASE_TABLE = "baske_tbl";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_GAMES + " integer not null, "
+ KEY_WON + " integer not null"
+ KEY_LOST + " integer not null, "
+ KEY_DIFF + " integer not null, "
+ KEY_POINTS + " integer not null "
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
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();
}
// 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;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase database, 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:
database.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(database);
}
}
}
also have two layouts one is row layout called item_layout.xml and list_activity.xml with listView in it.
every time i try to run it it shows "process has stopped unexpectedly". Any solution ?

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