I saw this tutorial: https://www.youtube.com/watch?v=gaOsl2TtMHs
but it seem that when i see the activity there isn't any item listview :\
What can be the problem? I put my code under below
The Main Activity.java
public class Prova2 extends Activity {
int[] imageIDs = {
R.drawable.spaghettiscoglio,
R.drawable.abbacchioascottadito,
R.drawable.agnellocacioeova,
R.drawable.agnolotti,
R.drawable.alettedipollo,
R.drawable.amaretti,
R.drawable.anatraarancia,
R.drawable.alberinatale
};
int nextImageIndex = 0;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prova2);
openDB();
populateListViewFromDB();
registerListClickCallback();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
public void onClick_AddRecord(View v) {
int imageId = imageIDs[nextImageIndex];
nextImageIndex = (nextImageIndex + 1) % imageIDs.length;
// Add it to the DB and re-draw the ListView
myDb.insertRow("Jenny" + nextImageIndex, imageId, "Green");
populateListViewFromDB();
}
public void onClick_ClearAll(View v) {
myDb.deleteAll();
populateListViewFromDB();
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM, DBAdapter.KEY_FAVCOLOUR, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.tvFruitPrice, R.id.ivFruit, R.id.tvFruitPrice, R.id.smalltext};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.sis, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void registerListClickCallback() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
displayToastForId(idInDB);
}
});
}
private void updateItemForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
favColour += "!";
myDb.updateRow(idInDB, name, studentNum, favColour);
}
cursor.close();
populateListViewFromDB();
}
private void displayToastForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
String message = "ID: " + idDB + "\n"
+ "Name: " + name + "\n"
+ "Std#: " + studentNum + "\n"
+ "FavColour: " + favColour;
Toast.makeText(Prova2.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
The DBAdaptor.java
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_STUDENTNUM = "studentnum";
public static final String KEY_FAVCOLOUR = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_STUDENTNUM = 2;
public static final int COL_FAVCOLOUR = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_STUDENTNUM, KEY_FAVCOLOUR};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_STUDENTNUM + " integer not null, "
+ KEY_FAVCOLOUR + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, int studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_STUDENTNUM, studentNum);
initialValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_STUDENTNUM, studentNum);
newValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
Related
I am trying to save the button's state in a certain item of RecyclerView whenever a user clicks that button. At the time it was clicked, it's visibility will be gone and another button will be visible. How can I save the button's state so that whenever the app is entirely closed, when I open it again the state of the button is still there?
I tried making a database for the button's visibility state but I couldn't figure out where to put the right code to add the data and save it.
onBindViewHolder() inside RecyclerView class, this is where I put my button click listener.
#Override
public void onBindViewHolder(final MyViewHolder holder, int position){
MakerAdapter h = makerList.get(position);
final String macString = h.getHMac();
holder.rIcon.setImageResource(h.getHIcon());
holder.rDevice.setText(h.getHDevice());
holder.rBrand.setText(h.getHBrand());
holder.rIp.setText(h.getHIp());
holder.rMac.setText(h.getHMac());
holder.rDate.setText(h.getHDate());
holder.rWifi.setText(h.getHWifi());
holder.rMark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSafeDB = new SafeDB(getApplicationContext(), null,null,1);
holder.rMark.setVisibility(GONE);
holder.rUnsafe.setVisibility(VISIBLE);
mSafeDB.addSafeMaker(macString, holder.rMark.getVisibility());
}
});
holder.rUnsafe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSafeDB = new SafeDB(getApplicationContext(), null,null,1);
holder.rUnsafe.setVisibility(GONE);
holder.rMark.setVisibility(VISIBLE);
mSafeDB.addSafeMaker(macString, holder.rUnsafe.getVisibility());
}
});
}
These are my imports specific to this(onBindViewHolder) method:
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.facebook.FacebookSdk.getApplicationContext;
This is my database
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SafeDB extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "safedb.db";
private static final String TABLE_NAME = "marked_safe";
private static final String COL_ID = "id";
private static final String COL_MAC = "mac";
private static final String COL_MARK = "mark";
//////////Housekeeping START
public SafeDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DB_NAME, factory, DB_VERSION);
}
public SafeDB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
// this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_MAC + " TEXT, " +
COL_MARK + " INTEGER " +
");";
db.execSQL(query);
}
public void open() throws SQLException {
close();
this.getWritableDatabase();
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//////////Housekeeping END
public void deleteTable(){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
//IF FIRST TIME. THIS WILL BE TRIGGERED
public void addSafeMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MAC, mac);
values.put(COL_MARK, mark);
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
}
//UPDATE THE Arp
public void updateMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MAC, mac);
values.put(COL_MARK, mark);
SQLiteDatabase db = getWritableDatabase();
db.update(TABLE_NAME, values, "id = 1", null);
}
//GET THE MAC
public String getMac(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mac = c.getString(c.getColumnIndex("mac"));
return mac;
}
//GET THE BUTTON VISIBILITY VALUE
public String getSafeValue(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mark = c.getString(c.getColumnIndex("mark"));
return mark;
}
//CHECK IF EMPTY
public boolean isEmpty() {
boolean e = true;
SQLiteDatabase db = getWritableDatabase();
String count = "SELECT count(*) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(count, null);
c.moveToFirst();
int icount = c.getInt(0);
e = icount <= 0;
return e;
}
public int getCount(){
int count = 0;
SQLiteDatabase db = getWritableDatabase();
String c = "SELECT count(*) FROM " + TABLE_NAME;
Cursor x = db.rawQuery(c, null);
x.moveToFirst();
count = x.getInt(0);
return count;
}
}
The following is a working example based upon your code, albeit that the Adapter is probably quite different. Some assumptions/guesswork were made. So the code is very much in-principle code and would need to be adapted.
The above adds a mac (assuming a mac is unique) when the adapter is instantiated, a specific mac will only be added once.
In the onBindView method the status/mark is retrieved from the db to determine which button is displayed.
When a button is clicked the displayed button is toggled and the respective mac (the button's tag is used to store the mac) is used to update the respective row according to the mac.
SafeDB.java
public class SafeDB extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "safedb.db";
private static final String TABLE_NAME = "marked_safe";
private static final String COL_ID = "id";
private static final String COL_MAC = "mac";
private static final String COL_MARK = "mark";
//////////Housekeeping START
public SafeDB(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context, DB_NAME, factory, DB_VERSION);
}
public SafeDB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COL_ID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT REMOVED NOT NECESSARY
COL_MAC + " TEXT UNIQUE, " + // Probably should be unique
COL_MARK + " INTEGER " +
");";
db.execSQL(query);
}
public void open() throws SQLException {
close();
this.getWritableDatabase();
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1){
deleteTable(); // might as well use the deleteTable method as it exists
onCreate(db);
}
//////////Housekeeping END
public void deleteTable(){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
//IF FIRST TIME. THIS WILL BE TRIGGERED
// wont hurt to return the id of the inserted row (-1 if no row inserted)
public long addSafeMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MAC, mac);
values.put(COL_MARK, mark);
SQLiteDatabase db = getWritableDatabase();
return db.insert(TABLE_NAME, null, values);
}
//UPDATE THE Arp
public int updateMaker(String mac, int mark){
ContentValues values = new ContentValues();
values.put(COL_MARK, mark);
//values.put(COL_MARK, mark); // guess this wont change rather that it will be used to determine the row to be updated
SQLiteDatabase db = getWritableDatabase();
//db.update(TABLE_NAME, values, "id = 1", null); // Will only ever update 1 specific row
String whereclause = COL_MAC + "=?";
String[] whereargs = new String[]{mac};
return db.update(TABLE_NAME,values,whereclause,whereargs);
}
//GET THE MAC
public String getMac(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mac = c.getString(c.getColumnIndex("mac"));
return mac;
}
public boolean getSafeValue(String mac) {
int mark = 0; // assume marked safe if row not found
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = COL_MAC + "=?";
String[] whereargs = new String[]{mac};
Cursor c = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (c.moveToFirst()) {
mark = c.getInt(c.getColumnIndex(COL_MARK));
}
return mark < 1;
}
//GET THE BUTTON VISIBILITY VALUE
/*
public String getSafeValue(String x) {
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM "+ TABLE_NAME+" WHERE "+ COL_ID+" = '" + x+"'" + " LIMIT 1;" ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
String mark = c.getString(c.getColumnIndex("mark"));
return mark;
}
*/
//CHECK IF EMPTY
/*
public boolean isEmpty() {
boolean e = true;
SQLiteDatabase db = getWritableDatabase();
String count = "SELECT count(*) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(count, null);
c.moveToFirst(); // WARINING if no rows then next line will crash INDEX OUT OF BOUNDS
int icount = c.getInt(0);
e = icount <= 0;
return e;
}
*/
public long getCount(){
int count = 0;
SQLiteDatabase db = getWritableDatabase();
return DatabaseUtils.queryNumEntries(this.getWritableDatabase(),TABLE_NAME);
/*
quick form used as above
String c = "SELECT count(*) FROM " + TABLE_NAME;
Cursor x = db.rawQuery(c, null);
x.moveToFirst();
count = x.getInt(0);
return count;
*/
}
}
You should note the comments, there were some issues with your code.
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
ArrayList<String> mMacList;
SafeDB mDB;
Context mContext;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mMac;
public Button mSafe;
public Button mUnsafe;
public MyViewHolder(View view) {
super(view);
mMac = view.findViewById(R.id.name);
mSafe = view.findViewById(R.id.marksafe);
mUnsafe = view.findViewById(R.id.markunsafe);
}
}
public MyAdapter(Context context,ArrayList<String> maclist) {
mMacList = maclist;
mContext = context;
mDB = new SafeDB(context);
// Could add the mac's to the DB here (note DB changed so mac is unqiue so same mac won't be added)
for (String mac: maclist) {
mDB.addSafeMaker(mac,0);
}
}
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.mylist_item,viewGroup, false);
MyViewHolder vh = new MyViewHolder(v);
mContext = viewGroup.getContext();
return vh;
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder viewHolder, int i) {
viewHolder.mMac.setText(mMacList.get(i));
if (mDB == null) {
mDB = new SafeDB(viewHolder.mMac.getContext());
}
//Set the Tag for the buttons with the mac so it can be retrieved
viewHolder.mSafe.setTag(mMacList.get(i));
viewHolder.mUnsafe.setTag(mMacList.get(i));
// Display the buttons according to the database
if (mDB.getSafeValue(mMacList.get(i))) {
viewHolder.mSafe.setVisibility(View.GONE);
viewHolder.mUnsafe.setVisibility(View.VISIBLE);
} else {
viewHolder.mSafe.setVisibility(View.VISIBLE);
viewHolder.mUnsafe.setVisibility(View.GONE);
}
// Add the onCLickListeners
viewHolder.mSafe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.mSafe.setVisibility(View.GONE);
viewHolder.mUnsafe.setVisibility(View.VISIBLE);
String mac = (String) ((Button) viewHolder.mSafe).getTag();
changeSafeMark((String)viewHolder.mSafe.getTag(),0);
}
});
viewHolder.mUnsafe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.mSafe.setVisibility(View.VISIBLE);
viewHolder.mUnsafe.setVisibility(View.GONE);
changeSafeMark((String)viewHolder.mUnsafe.getTag(),1);
}
});
}
#Override
public int getItemCount() {
return mMacList.size();
}
public int changeSafeMark(String mac, int mark) {
int result = mDB.updateMaker(mac,mark);
return result;
}
}
This is probably quite different and only the simplest of layouts was used.
mylistitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:id="#+id/marksafe"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Make Safe"
/>
<Button
android:id="#+id/markunsafe"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Make Unsafe"
/>
</LinearLayout>
MainActivity.java
The invoking activity used to test :-
public class MainActivity extends AppCompatActivity {
RecyclerView mList;
RecyclerView.LayoutManager mLayoutManager;
MyAdapter mMyAdapter;
// The underlying data (just a list of strings for the macs)
ArrayList<String> mymacliist = new ArrayList<>(Arrays.asList("M1","M2","M3"));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = this.findViewById(R.id.mylist);
mLayoutManager = new LinearLayoutManager(this);
mList.setLayoutManager(mLayoutManager);
mMyAdapter = new MyAdapter(this,mymacliist);
mList.setAdapter(mMyAdapter);
}
}
Results
When First run :-
After M2 and M3 are clicked (buttons are changed to Make Safe when clicked), then the App is stopped and then started :-
database is your best option, you should put the code inside onclicklistiner.
if you want to "toggle" so save a boolean in the database that if it true than the user have been clicked on the item, and if its false, the user didn't clicked the item.
than in your onclicklistiner you do an if statement on the boolean.
I am generating an events dynamically. These events data I am storing in sqlite database. Now I want to retrieve data of the clicked event. I tried to retrieve data but always getting 0th id data.
Generating events function :
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
This is my attempt to get data:
db = new EventTableHelper(getApplication());
eventData = new EventData();
if(editMode)//true
{
eventData = events.get(id);
Toast.makeText(getApplicationContext(),String.valueOf(id),Toast.LENGTH_LONG).show();
title.setText(eventData.getTitle());
eventTitle = title.getText().toString();
db.updateEvent(eventData);
Toast.makeText(getApplicationContext(),"Edit mode",Toast.LENGTH_LONG).show();
Log.i("Log","save mode");
}
I have EventTableHelper in that i have created functions to get event,update and delete events.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE,KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I want to show data and update data if changes made.
Whats going wrong?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to get the price value from the database and try to make a grand total. I used the rawQuery but always crashed.I think theres a problem in my rawQuery..i still cant get the total after many times i've tried..
this is the code:
DBAdapter
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
// ------------------------------------ DBAdapter.java ---------------------------------------------
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
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_QUANTITY = "studentnum";
public static final String KEY_PRICE = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_QUANTITY = 2;
public static final int COL_PRICE = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_PRICE};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_QUANTITY + " integer not null, "
+ KEY_PRICE + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_QUANTITY, studentNum);
initialValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public Cursor getTotalPrice() {
Cursor c = db.rawQuery("SELECT SUM("+ KEY_PRICE +")from " + DATABASE_TABLE, null);
return c;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_QUANTITY, studentNum);
newValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Listprice:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
/**
* Created by User on 6/2/2015.
*/
public class Listprice extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listprice);
openDB();
TextView textView = (TextView) findViewById(R.id.order90);
TextView textView1 = (TextView) findViewById(R.id.quan90);
TextView textView2 = (TextView) findViewById(R.id.price90);
TextView textView3 = (TextView) findViewById(R.id.totalprice);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newText = extras.getString("firstmessage");
String newText1 = extras.getString("secondmessage");
String newText2 = extras.getString("thirdmessage");
if (newText != null) {
textView.setText(newText);
}
if (newText1 != null) {
textView1.setText(newText1);
}
if (newText2 != null) {
textView2.setText(newText2);
}
}
String num1 = textView.getText().toString().trim();
int num2 = Integer.parseInt(textView1.getText().toString());
int num3 = Integer.parseInt(textView2.getText().toString());
int num4 = num2 * num3;
registerListClickCallBack();
myDb.insertRow(num1, "Quantity = " + num2, ""+num4);
populateListViewFromDB();
Cursor sum=myDb.getTotalPrice();
textView3.setText(""+sum);
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
//Query for the record we just added.
//Use the ID:
startManagingCursor(cursor);
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_QUANTITY, DBAdapter.KEY_PRICE};
int[] toViewIDs = new int[]
{R.id.item_name, R.id.quantities, R.id.pricest};
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void openDB(){
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void closeDB() {
myDb.close();
}
private void registerListClickCallBack() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
}
});
}
private void updateItemForId(final long idInDB) {
final Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Listprice.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
myDb.deleteRow(idInDB);
populateListViewFromDB();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
cursor.close();
populateListViewFromDB();
}
public void clear(View view) {
myDb.deleteAll();
populateListViewFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addFood(View view) {
Intent gotofood = new Intent(this, food.class);
startActivity(gotofood);
}
public void addDrinks(View view) {
Intent gotodrinks = new Intent(this, drink.class);
startActivity(gotodrinks);
}
public void gotomainmaenu(View view) {
Intent gotomain = new Intent(this, MainActivity.class);
startActivity(gotomain);
}
}
It sounds like you want the sum of each item's price multiplied by that item's quantity. If so, this should work:
public double getTotalPrice() {
String sql = "select sum(" + KEY_QUANTITY + " * " + KEY_PRICE + ") from "
+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
return cursor.getDouble(0);
}
return 0;
}
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.
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);