pass data from one activity to another and save it - java

i have two activities, each one have a listview. The first one contain the data and i want the other one to be as a favorite list. Right now i can pass the data with intent but its not saving. it shows when i start the intent but when i exit the second activity and go back to it with a custom button nothing is saved in the listview. Please tell me what to do. here is my code
public class MainActivity extends AppCompatActivity {
DB_Sqlite dbSqlite;
ListView listView;
String fav_name;
long fav_id;
ArrayAdapter adapter;
ArrayList arrayList;
String[] number;
Button button;
StringResourcesHandling srh;
Cursor getAllDataInCurrentLocale,getDataInCurrentLocaleById;
SimpleCursorAdapter favourites_adapter,non_favourites_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
arrayList = new ArrayList<String>();
listView.setAdapter(adapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, cc.class);
startActivity(intent);
}
});
/* Show the resources for demo */
for (String s : StringResourcesHandling.getAllStringResourceNames()) {
Log.d("RESOURCEDATA", "String Resource Name = " + s +
"\n\tValue = " + StringResourcesHandling.getStringByName(this, s)
);
}
dbSqlite = new DB_Sqlite(this);
Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
getAllDataInCurrentLocale.close();
}
#Override
protected void onResume() {
super.onResume();
manageNonFavouritesListView();
}
private void manageNonFavouritesListView() {
getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);
if (non_favourites_adapter == null) {
non_favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
getAllDataInCurrentLocale,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(non_favourites_adapter);
setListViewHandler(listView,false);
} else {
non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
}
}
private void setListViewHandler(ListView listView, boolean favourite_flag) {
if (!favourite_flag) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent = new Intent(MainActivity.this,tc.class);
startActivity(intent);
}
if (i == 1) {
Intent intent = new Intent(MainActivity.this,vc.class);
startActivity(intent);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
startActivity(intent);}
String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
}}
}
public class DB_Sqlite extends SQLiteOpenHelper {
public static final String BDname = "data.db";
public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
public static final String TABLE_FAVOURITES = "mytable";
public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
public static final String FAVOURITES_COL_NAME = "name";
public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */
public DB_Sqlite(#Nullable Context context) {
super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_FAVOURITES + " (" +
FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
FAVOURITES_COL_NAME + " TEXT, " +
FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
")");
/* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
ContentValues cv = new ContentValues();
for (String s: StringResourcesHandling.getAllStringResourceNames()) {
cv.clear();
cv.put(FAVOURITES_COL_NAME,s);
db.insert(TABLE_FAVOURITES,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
onCreate(db);
}
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FAVOURITES_COL_NAME, name);
long result = db.insert(TABLE_FAVOURITES,null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getFavouriteRows(boolean favourites) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
String compare = "<1";
if (favourites) {
compare =">0";
}
return db.query(
TABLE_FAVOURITES,null,
FAVOURITES_COL_FAVOURITEFLAG + compare,
null,null,null,null
);
}
private int setFavourite(long id, boolean favourite_flag) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
}
public int setAsFavourite(long id) {
return setFavourite(id,true);
}
public int setAsNotFavourite(long id) {
return setFavourite(id, false);
}
/* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names */
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
public class cc extends AppCompatActivity {
String fav_name;
long fav_id;
DB_Sqlite dbSqlite;
SimpleCursorAdapter favourites_adapter;
ListView listView1;
ArrayList<String> arrayList1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cc);
listView1 = (ListView) findViewById(R.id.list_view1);
arrayList1 = new ArrayList<String>();
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
if (fav_id == 0) {
}
dbSqlite = new DB_Sqlite(this);
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
if (cursor.moveToFirst()) {
fav_name = cursor.getString(cursor.getColumnIndex(FAVOURITES_COL_NAME));
manageNonFavouritesListView();
}
cursor.close();
}
private void manageNonFavouritesListView() {
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
cursor,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView1.setAdapter(favourites_adapter);
setListViewHandler(listView1,true);
} else {
favourites_adapter.swapCursor(cursor);
}
}
private void setListViewHandler(ListView listView1, boolean b) {
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (fav_id == 1) {
Intent intent = new Intent(cc.this, tc.class);
startActivity(intent);
}
if (fav_id == 2) {
Intent intent = new Intent(cc.this, vc.class);
startActivity(intent);
}
}
});
}
}
public class StringResourcesHandling {
private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
private static boolean loaded = false;
private static Field[] fields = R.string.class.getFields();
private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();
private static void loadStringResources() {
if (loaded) return;
for (Field f: fields) {
if (isResourceNameAllowedPrefix(f.getName())) {
allowedStringResourceNames.add(f.getName());
}
}
loaded = true;
}
private static boolean isResourceNameAllowedPrefix(String resourceName) {
if (allowedStringResourcePrefixes.length < 1) return true;
for (String s: allowedStringResourcePrefixes) {
if (resourceName.substring(0,s.length()).equals(s)) return true;
}
return false;
}
public static String getStringByName(Context context, String name) {
String rv = "";
boolean nameFound = false;
if (!loaded) {
loadStringResources();
}
for (String s: allowedStringResourceNames) {
if (s.equals(name)) {
nameFound = true;
break;
}
}
if (!nameFound) return rv;
return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
}
public static List<String> getAllStringResourceNames() {
if (!loaded) {
loadStringResources();
}
return allowedStringResourceNames;
}
}
note: i get the data in 1st listview from strings.xml
please help me thank u in advance

You can add a column say 'isFavourite' in your db table which has list vew data. When user mark listitem as favourite, save the change in db table . When user navigates to favourite list populate the list from. db table with favourite filter in select query.

I suggest using SharedPreferences. You stated that your value gets overwritten. That won't be the case if you create multiple keys.
Example:
Say you have an ArrayList of String you want to pass from ClassA to ClassB:
ClassA:
for (int i = 0; i < list.size(); i++) {
sharedPref.edit().putString("text" + i, "abcde").apply();
}
ClassB:
for (int i = 0; i < list.size(); i++) {
sharedPref.getString("text" + i, null);
}
If you have problems with the listsize, you can also pass the listsize to sharedpref and retrieve it again.

Related

How to create delete method in SQLite for deleting single item not the whole checklist?

I'll post only relevant code.
This is Activity which adds checklist to database.
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
ArrayList<String> itemList;
ArrayList<String> stateList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView() {
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
etChecklistItem.requestFocus();
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view) {
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
} else
checklistHelper.setStatus("0");
itemList.add(etChecklistItem.getText().toString());
stateList.add(checklistHelper.getStatus());
}
StringBuilder stringBuilder = new StringBuilder();
for (String items : itemList) {
stringBuilder.append(items);
stringBuilder.append("\n");
}
StringBuilder stringBuilder1 = new StringBuilder();
for (String state : stateList) {
stringBuilder1.append(state);
stringBuilder1.append("\n");
}
String items = stringBuilder.toString();
String state = stringBuilder1.toString();
dbHelper.insertChecklist(state, items, DateTime.date(), DateTime.time(), System.currentTimeMillis());
finish();
break;
}
return true;
}
}
This is insert checklist method in SQLiteHelper class.
public boolean insertChecklist(String status, String content, String date, String time, long now){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(CHECKLIST_STATUS, status);
c.put(CHECKLIST_CONTENT, content);
c.put(CHECKLIST_DATE, date);
c.put(CHECKLIST_TIME, time);
c.put(CHECKLIST_NOW, now);
long id = sqLiteDatabase.insert(CHECKLIST_TABLE, null, c);
Log.d("check", "checklist inserted -> ID = " + id);
return true;
}
This is the delete method for deleting the whole checklist, not for individual items.
public void deleteChecklist(long id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(CHECKLIST_TABLE, CHECKLIST_ID + " =? ", new String[] {String.valueOf(id)});
}
Here I want a method like above, but only for deleting selected item, like this image.. Look at this image.
look this image

SQL Lite Data not being inserted (Android Studio in java)

I want to insert data from user input on the click of a button but it does not get added. In my addData function it is always returning false. I don't seem to understand why this is happening nor do I have any clue where the error is since my code isn't producing any.
Here is my Database Helper code:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "nutrition_table";
private static final String COL1 = "ID";
private static final String COL2 = "food";
private static final String COL3 = "calories";
DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase DB) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 + " TEXT" + COL3 + " ,TEXT)" ;
DB.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase DB, int i, int i1) {
DB.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(DB);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
contentValues.put(COL3, item);
Log.d(TAG, "addData: Adding " + item + "to" + TABLE_NAME);
long res = db.insert(TABLE_NAME, null, contentValues);
if (res == -1) {
return false;
} else {
return true;
}
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
}
Here is my addActivity code:
DatabaseHelper mDbhelper;
TextView addFood, addCals;
Button addEntry, deleteEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
addFood = findViewById(R.id.addFoodItemTextView);
addCals = findViewById(R.id.addCaloriesTextView);
addEntry = findViewById(R.id.addBtn);
deleteEntry = findViewById(R.id.deleteBtn);
mDbhelper = new DatabaseHelper(this);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String foodEntry = addFood.getText().toString();
String calsEntry = addCals.getText().toString();
if (foodEntry.length() != 0) {
addData(foodEntry);
addFood.setText("");
} else {
toastMessage("You have to add data in the food/meal text field!");
}
if (calsEntry.length() != 0) {
addData(calsEntry);
addCals.setText("");
} else {
toastMessage("You have to add data in the calorie text field");
}
}
});
}
public void addData(String newEntry) {
boolean insertData = mDbhelper.addData(newEntry);
if (insertData) {
toastMessage("Added to entries");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Here is the code where the data is supposed to be displayed:
private final static String TAG = "listData";
DatabaseHelper dbHelper;
private ListView displayData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_entries);
displayData = findViewById(R.id.listData);
dbHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = dbHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
listData.add(data.getString(1));
listData.add(data.getString(2));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
displayData.setAdapter(adapter);
}
}
Keep in mind that I am using an intent to view the entries (When the user clicks the button it brings him to the View entries page). I'm not sure where my code went wrong. Any help is greatly appreciated.
Thanks!

Android studio: I am trying to change the shared preferences and want to store the data in the SQLite database [closed]

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 1 year ago.
Improve this question
I am new in Java Programming.
Now, I am facing the problem that I want to change the shared preferences and want to use the SQLite database to store these data. I had created the table for store these data and I am trying to save these data in SQLite.
How can I do? Anyone can help me ????
MyDatabase-Table
This is my code that using shared preferences :
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
reg = new AC_Class.Register();
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
// Check preferences/create if nonexistent
prefs = this.getSharedPreferences("com.presoft.androidmobilestock", Context.MODE_PRIVATE);
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
prefs.edit().putString("UUID", uniqueID).commit();
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
finish();
}
//On return of intent
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 7) {
url = data.getStringExtra("URLKey");
urlStr = data.getStringExtra("URLStr");
Log.i("custDebug", url + ", " + urlStr);
binding.txtURL.setText(urlStr);
if (!TextUtils.isEmpty(binding.txtURL.getText().toString())) {
new GetModules(Login.this).execute(url);
new GetLoginList(Login.this).execute(url);
new SetDevice(Login.this).execute(url);
}
}
}
//Open connection settings
public void btnSetClicked(View view) {
Intent intent = new Intent(Login.this, ConnectionSettings.class);
startActivityForResult(intent, 7);
}
//Reset Database
public void btnResetDbClicked(final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Reset DB");
builder.setMessage("Are you sure you want to reset the Database?");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (input.getText().toString().equals("presoftmobile")) {
db.close();
deleteDatabase("AutoCountDatabase");
} else {
// Toast.makeText(getApplicationContext(), "Incorrect Password", Toast.LENGTH_SHORT);
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
//Login button
public void btnLoginBtnClicked(View view) {
if (TextUtils.isEmpty(binding.txtURL.getText().toString())) {
binding.txtURL.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtID.getText().toString())) {
binding.txtID.setError("This field can't be blank.");
//return;
}
if (TextUtils.isEmpty(binding.txtpw.getText().toString())) {
binding.txtpw.setError("This field can't be blank.");
//return;
}
//Non-empty fields
else {
Cursor checkData = db.loginValidate(binding.txtID.getText().toString(),
binding.txtpw.getText().toString().toUpperCase());
if (checkData.getCount() > 0) {
checkData.moveToNext();
//Shared Preferences
prefs.edit().putString("URL", url).apply();
prefs.edit().putString("URLstr", binding.txtURL.getText().toString()).apply();
if (binding.rmbCheckBox.isChecked()) {
prefs.edit().putString("ID", binding.txtID.getText().toString()).apply();
prefs.edit().putString("pwd", binding.txtpw.getText().toString()).apply();
}
prefs.edit().putInt("EnableSetting", checkData.getInt(checkData.getColumnIndex("EnableSetting"))).apply();
prefs.edit().putInt("FilterByAgent", checkData.getInt(checkData.getColumnIndex("FilterByAgent"))).apply();
prefs.edit().putInt("Sales", checkData.getInt(checkData.getColumnIndex("Sales"))).apply();
prefs.edit().putInt("Purchase", checkData.getInt(checkData.getColumnIndex("Purchase"))).apply();
prefs.edit().putInt("Transfer", checkData.getInt(checkData.getColumnIndex("Transfer"))).apply();
if (url != null) {
try {
// Check Connection
new SetDevice(Login.this).execute(url);
// Go to main
Intent intent = new Intent(Login.this, Dashboard.class);
intent.putExtra("URLKey", url);
intent.putExtra("URLStr", binding.txtURL.getText().toString());
startActivity(intent);
finish();
} catch (Exception e) {
Log.i("custDebug", e.getMessage());
Toast.makeText(this, "Unable to connect to server", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show();
binding.txtpw.setText(null);
}
checkData.close();
}
}
This is the code that to save the data in SQLite database (but getting error):
public class Login extends AppCompatActivity {
InputStream inputStream;
ACDatabase db;
SharedPreferences prefs;
ActivityLoginBinding binding;
AC_Class.Connection connection;
AC_Class.Register reg;
String versionNo;
String url;
String urlStr;
String id;
String pwd;
private static String uniqueID = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
getSupportActionBar().hide();
// Placeholder
versionNo = "3.1.6";
connection = new AC_Class.Connection();
binding.setConSettings(connection);
db = new ACDatabase(this);
db = new ACDatabase(this);
uniqueID = db.getReg("8");
uniqueID = prefs.getString("UUID", null);
if (uniqueID == null)
{
uniqueID = UUID.randomUUID().toString();
//uniqueID = "3FDE9813F93A47CBA6CD4F5DAAECEE01";
db.updateREG("8", uniqueID);
}
binding.lblUUID.setText(uniqueID);
binding.lblVersion.setText(versionNo);
if (prefs.getString("ID", id) != null) {
binding.rmbCheckBox.setChecked(true);
url = prefs.getString("URL", url);
binding.txtURL.setText(prefs.getString("URLstr", urlStr));
binding.txtID.setText(prefs.getString("ID", id));
binding.txtpw.setText(prefs.getString("pwd", pwd));
}
if (prefs.getString("Default_curr", null) == null) {
prefs.edit().putString("Default_curr", "RM").apply();
}
if (prefs.getString("Default_loc", null) == null) {
Cursor tempCursor = db.getLocation();
if (tempCursor.moveToNext()) {
prefs.edit().putString("Default_loc", tempCursor
.getString(tempCursor.getColumnIndex("Location"))).apply();
}
}
// Version number
if (prefs.getString("Version ", null) == null) {
prefs.edit().putString("Version", versionNo).apply();
}
// Tax Inclusive
if (!prefs.getBoolean("taxInclusive", false)) {
prefs.edit().putBoolean("taxInclusive", false).apply();
}
if (Build.MODEL.equals("HC720"))
{
Snackbar.make(findViewById(android.R.id.content), "RFID Detected.", Snackbar.LENGTH_SHORT).show();
}
}
mydatabasehelper
//GET value by id
public Cursor getReg(String id) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT Value FROM " + TABLE_NAME_REG + " WHERE ID ='" + id + "'",null);
return data;
}
//update value
public boolean updateREG(String ID, String Value) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Value", Value);
String[] args = new String[]{ID};
database.update("Reg", cv, "ID = ?", args);
return true;
}
The following is a working example that acts very similar to shared prefs but stores the prefs in an SQLite database.
The table is very simple 2 columns. The key (name of the stored value) and the value itself. Which can be String, boolean, int, long or Float.
It includes methods to; insert (add) a key/value pair, update a key/value pair and to get a value according to the key and also to return a default value as passed (making it easy to detect if the value was retrieved).
The DatabaseHelper (sub class of SQLiteOpenHelper) has most of the code and is :-
class DBHelper extends SQLiteOpenHelper {
private static volatile DBHelper instance = null;
private SQLiteDatabase db = null;
public static final String DBNAME = "sharedpreferences.db";
public static final int DBVERSION = 1;
public static final String TBLNAME_SP = "_shared_preferences";
public static final String COLNAME_SP_KEY = "_key";
public static final String COLNAME_SP_VALUE = "_value";
private DBHelper(#Nullable Context context) {
super(context, DBNAME, null, DBVERSION);
db = this.getWritableDatabase();
}
public static DBHelper getInstance(Context context) {
if (instance == null) {
instance = new DBHelper(context);
}
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TBLNAME_SP +
"(" +
COLNAME_SP_KEY + " PRIMARY KEY," +
COLNAME_SP_VALUE + " TEXT" +
")");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
private long insertPrefsRow(ContentValues cv, String key) {
cv.put(COLNAME_SP_KEY,key);
return db.insertWithOnConflict(TBLNAME_SP,null,cv, SQLiteDatabase.CONFLICT_IGNORE);
}
public long insertPrefsValue (String key, int value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, String value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, long value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, boolean value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
public long insertPrefsValue (String key, float value) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,value);
return insertPrefsRow(cv,key);
}
private long updatePrefs(String key, ContentValues cv) {
return db.update(TBLNAME_SP,cv,COLNAME_SP_KEY + "=?",new String[]{key} );
}
public long updatePrefsStringValue(String key, String newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, boolean newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, int newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, long newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
public long updatePrefsStringValue(String key, Float newValue) {
ContentValues cv = new ContentValues();
cv.put(COLNAME_SP_VALUE,newValue);
return updatePrefs(key,cv);
}
private Cursor getPrefsValue(String key) {
return db.query(TBLNAME_SP,new String[]{COLNAME_SP_VALUE},COLNAME_SP_KEY + "=?",new String[]{key},null,null,null);
}
public String getPrefsStringValue(String key, String default_value) {
String rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Boolean getPrefsBooleanValue(String key, boolean default_value ) {
Boolean rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE)) != 0;
csr.close();
}
return rv;
}
public int getPrefsIntValue(String key, int default_value) {
int rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public long getPrefsLongValue(String key, long default_value) {
long rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getLong(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
public Float getPrefsFLoatValue(String key, Float default_value) {
Float rv = default_value;
Cursor csr;
if ((csr = getPrefsValue(key)).moveToFirst()) {
rv = csr.getFloat(csr.getColumnIndex(COLNAME_SP_VALUE));
csr.close();
}
return rv;
}
}
The following is an activity that demonstrates usage:-
public class MainActivity extends AppCompatActivity {
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = DBHelper.getInstance(this);
db.insertPrefsValue("UUID","3FDE9813F93A47CBA6CD4F5DAAECEE01");
db.insertPrefsValue("taxInclusive",false);
db.insertPrefsValue("myprefs_int",100);
db.insertPrefsValue("myprefs_long",100L);
db.insertPrefsValue("myprefs_float",10.567F);
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
db.updatePrefsStringValue("UUID","FFFF9813F93A47CBA6CD4F5DAAECEE01");
Log.d("PREFSINFO",
"Stored UUID is " + db.getPrefsStringValue("UUID","000000000000000000000000") +
" Stored taxinclusive is " + db.getPrefsBooleanValue("taxInclusive",true) +
" Stored mpint is " + db.getPrefsIntValue("myprefs_int",-99) +
" Stored mplong is " + db.getPrefsLongValue("myprefs_long",-99999999) +
" Stored mpfloat is " + db.getPrefsFLoatValue("myprefs_float",-999999.999999F) +
" NOT STORED is " + db.getPrefsFLoatValue("NOT A SET KEY",-3333.3333F)
);
}
}
When run (or rerun BUT when rerun the updated UUID rather than the original is retrieved) the log contains :-
D/PREFSINFO: Stored UUID is 3FDE9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
D/PREFSINFO: Stored UUID is FFFF9813F93A47CBA6CD4F5DAAECEE01 Stored taxinclusive is false Stored mpint is 100 Stored mplong is 100 Stored mpfloat is 10.567 NOT STORED is -3333.3333
NOT STORED demonstrates the default value being returned when the Key/Name isn't stored.
As you can see UUID has been updated in the second line (if rerun both lines would show the updated value)

Database refusing to delete item

I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.
But when I ran the code, the Item refused to delete.
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
init();
mHelper = new InputDbHelper(this);
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
setupListViewListener();
}
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{"Name of entry you want deleted"});
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void init(){
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.hide();
list = (ListView)findViewById(R.id.list);
displayText = (TextView)findViewById(R.id.displayText);
amt = (TextView)findViewById(R.id.amt);
itms = (TextView)findViewById(R.id.itms);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
l1 = (ConstraintLayout)findViewById(R.id.one);
l2 = (ConstraintLayout)findViewById(R.id.two);
Typeface regular = Typeface.createFromAsset(getAssets(), "fonts/regular.ttf");
Typeface bold = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf");
amt.setTypeface(bold);
itms.setTypeface(regular);
displayText.setTypeface(regular);
}
public void add(View v){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add Item");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String txt = edt.getText().toString();
items.add(txt);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, txt);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
public void play(View v){
Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);
l1.startAnimation(fadeOut);
l1.setVisibility(View.GONE);
l2.setVisibility(View.VISIBLE);
l2.startAnimation(fadeIn);
String[] array = new String[items.size()];
final String[] mStringArray = items.toArray(array);
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
displayText.setText(mStringArray[i]);
i++;
if (i == mStringArray.length) {
handler.removeCallbacks(this);
} else {
handler.postDelayed(this, TIME);
}
}
});
}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (itemsAdapter== null) {
itemsAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
taskList);
list.setAdapter(itemsAdapter);
} else {
itemsAdapter.clear();
itemsAdapter.addAll(taskList);
itemsAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?
I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.
So try using :-
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{title_of_row_to_delete}); //<<<<<<<<
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.
//<<<<<<<< indicates changed lines.

Detect changes on SQLite database for loader

I have been building a simple note app and have successfully SQlite database and loaders to load data on a listview. Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how. I've search but mainly tutorials are for Content provider, I read this: http://developer.android.com/reference/android/content/AsyncTaskLoader.html#q=addAll
but not understand much because they use BroadcastReceiver to get change on sd card.
Im all ears to any suggestion and thanks for any help in advance!
this is my code: WhiteNote.java
public class WhiteNote extends Fragment implements LoaderManager.LoaderCallbacks<ArrayList<NoteItems>> {
private NoteDatabase note_database;
private int i=0;
public Context context;
public NoteListAdapter noteListAdapter;
public ListView note_listview_container;
public SQLiteDatabase note_sqldb;
public Cursor c;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.white_note, container, false);
context=getActivity();
note_database = new NoteDatabase(context);
final EditText text_ed_1;
final EditText text_ed_2;
Button button_addNote;
Button button_listallNote;
Button button_delallNote;
text_ed_1 = (EditText)rootView.findViewById(R.id.textedit1);
text_ed_2 = (EditText)rootView.findViewById(R.id.textedit2);
button_addNote = (Button)rootView.findViewById(R.id.button1);
button_listallNote = (Button)rootView.findViewById(R.id.button2);
button_delallNote = (Button)rootView.findViewById(R.id.button3);
note_listview_container=(ListView)rootView.findViewById(R.id.note_listview);
noteListAdapter=new NoteListAdapter(context, new ArrayList<NoteItems>());
note_database.open();
getLoaderManager().initLoader(0, null,WhiteNote.this);
note_database.close();
button_addNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.createData(text_ed_1.getText().toString(),text_ed_2.getText().toString());
//i++;
note_database.close();
}
});
button_listallNote.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
note_database.open();
note_database.get_NoteListAdapter();
note_listview_container.setAdapter(note_database.dbnoteListAdapter);
note_database.close();
//note_list.setText(ds);
}
});
button_delallNote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
note_database.open();
note_database.deleteAllNote();
note_database.close();
}
});
return rootView;
}
#Override
public Loader<ArrayList<NoteItems>> onCreateLoader(int id, Bundle args) {
return new NoteItemsLoader(context,note_database);
}
#Override
public void onLoadFinished(Loader<ArrayList<NoteItems>> loader,
ArrayList<NoteItems> data) {
note_listview_container.setAdapter(new NoteListAdapter(context, data));
}
#Override
public void onLoaderReset(Loader<ArrayList<NoteItems>> loader) {
note_listview_container.setAdapter(null);
}
}
class NoteItemsLoader extends AsyncTaskLoader<ArrayList<NoteItems>> {
private ArrayList<NoteItems> loader_noteitems= new ArrayList<NoteItems>();
private NoteDatabase loader_db;
public NoteItemsLoader(Context context, NoteDatabase db) {
super(context);
loader_db = db;
loader_noteitems=loader_db.get_NoteListArray(loader_noteitems,loader_db);
}
#Override
protected void onStartLoading() {
if (loader_noteitems != null) {
deliverResult(loader_noteitems); // Use the cache
}
else
forceLoad();
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
public ArrayList<NoteItems> loadInBackground() {
loader_db.open();
ArrayList<NoteItems> note_items = new ArrayList<NoteItems>();
loader_db.get_NoteListArray(note_items,loader_db);
loader_db.close();
return note_items;
}
#Override
public void deliverResult(ArrayList<NoteItems> data) {
if (isReset()) {
if (data != null) {
onReleaseResources(data);
}
}
ArrayList<NoteItems> oldNotes = loader_noteitems;
loader_noteitems = data;
if (isStarted()) {
super.deliverResult(data);
}
if (oldNotes != null) {
onReleaseResources(oldNotes);
}
}
#Override
protected void onReset() {
super.onReset();
onStopLoading();
loader_noteitems = null;
}
#Override
public void onCanceled(ArrayList<NoteItems> data) {
super.onCanceled(data);
loader_noteitems = null;
}
protected void onReleaseResources(ArrayList<NoteItems> data) {}
}
my NoteDatabase.java
public class NoteDatabase {
private static final String DATABASE_NAME = "DB_NOTE";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NOTE = "NOTE";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TOPIC = "Topic";
public static final String COLUMN_NOTECONTENT = "Content";
public static final String COLUMN_NAME = "Name";
public NoteListAdapter dbnoteListAdapter;
private static Context my_context;
static SQLiteDatabase note_sqldb;
private OpenHelper noteopenHelper;
public NoteDatabase(Context c){
NoteDatabase.my_context = c;
}
public NoteDatabase open() throws SQLException{
noteopenHelper = new OpenHelper(my_context);
note_sqldb = noteopenHelper.getWritableDatabase();
return this;
}
public void close(){
noteopenHelper.close();
}
public long createData(String chude_note, String noidung_note) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_TOPIC, chude_note);
cv.put(COLUMN_NOTECONTENT, noidung_note);
cv.put(COLUMN_NAME, "by Black");
return note_sqldb.insert(TABLE_NOTE, null, cv);
}
public String getData() {
String[] columns = new String[] {COLUMN_ID,COLUMN_TOPIC,COLUMN_NOTECONTENT,COLUMN_NAME};
Cursor c = note_sqldb.query(TABLE_NOTE, columns, null, null, null, null, null);
/*if(c==null)
Log.v("Cursor", "C is NULL");*/
String result="";
int iRow = c.getColumnIndex(COLUMN_ID);
int iTopic = c.getColumnIndex(COLUMN_TOPIC);
int iContent = c.getColumnIndex(COLUMN_NOTECONTENT);
int iOwner = c.getColumnIndex(COLUMN_NAME);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result +" \n"+ c.getString(iRow)
+ "\n - Topic: " + c.getString(iTopic)
+ "\n - Content: " + c.getString(iContent)
+ "\n - Owner: " + c.getString(iOwner) + "\n";
}
c.close();
//Log.v("Result", result);
return result;
}
public Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (note_sqldb.isOpen()) {
note_sqldb.close();
}
note_sqldb = noteopenHelper.getWritableDatabase();
c1 = note_sqldb.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
public void get_NoteListAdapter() {
ArrayList<NoteItems> noteList = new ArrayList<NoteItems>();
noteList.clear();
open();
String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
note_sqldb = noteopenHelper.getWritableDatabase();
Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){
NoteItems one_rowItems = new NoteItems();
one_rowItems.set_rowTopic(c1.getString(iTopic));
one_rowItems.set_rowContent(c1.getString(iContent));
one_rowItems.set_rowOwner(c1.getString(iOwner));
noteList.add(one_rowItems);
}
c1.close();
close();
dbnoteListAdapter = new NoteListAdapter(my_context, noteList);
}
public ArrayList<NoteItems> get_NoteListArray(ArrayList<NoteItems> noteitems_list,NoteDatabase db) {
noteitems_list.clear();
db.open();
String[] columns = new String[] {NoteDatabase.COLUMN_ID,NoteDatabase.COLUMN_TOPIC,NoteDatabase.COLUMN_NOTECONTENT,NoteDatabase.COLUMN_NAME};
note_sqldb = noteopenHelper.getWritableDatabase();
Cursor c1 = note_sqldb.query(NoteDatabase.TABLE_NOTE, columns, null, null, null, null, null);
int iRow = c1.getColumnIndex(NoteDatabase.COLUMN_ID);
int iTopic = c1.getColumnIndex(NoteDatabase.COLUMN_TOPIC);
int iContent = c1.getColumnIndex(NoteDatabase.COLUMN_NOTECONTENT);
int iOwner = c1.getColumnIndex(NoteDatabase.COLUMN_NAME);
for(c1.moveToFirst(); !c1.isAfterLast(); c1.moveToNext()){
NoteItems one_rowItems = new NoteItems();
one_rowItems.set_rowTopic(c1.getString(iTopic));
one_rowItems.set_rowContent(c1.getString(iContent));
one_rowItems.set_rowOwner(c1.getString(iOwner));
noteitems_list.add(one_rowItems);
}
c1.close();
db.close();
return noteitems_list;
}
public int deleteNote(String topic) {
return note_sqldb.delete(TABLE_NOTE, COLUMN_TOPIC + "='" + topic + "'", null);
}
public int deleteAllNote() {
return note_sqldb.delete(TABLE_NOTE, null, null);
}
}
Next thing I want to do is make loader automatically reload when I add, change or delete a note in database but don't know how.
There is no way to make that happen automatically. Either:
Something tells the loader that the data changed, so it knows to reload, or
The Loader is the one that is doing the "add, change, or delete a note in database"
I went with the latter approach with my CWAC-LoaderEx project and its SQLiteCursorLoader.

Categories

Resources