I am using Recyclerview ,Here is Json file the insert query written in Json array though the json data is not stored in SQLite.When we destroy the app and again restart it will only show
blank rows and again press a button and it will show json data aftr emptyrow ie:after destroy data gets lost.Do help me thank you
public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;
ArrayList<Employee> arr, arr1;
Toolbar toolbar;
TextView t1, t2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setHasFixedSize(true);
arr = new ArrayList<Employee>();
arr = InitializeData();
final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
cu = new CustomAdapter(Recyclerview.this, arr);
rv.setAdapter(cu);
registerForContextMenu(rv);
final bank ban = new bank(Recyclerview.this);
ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = ConstantValues.BASE_URL;
RequestBody formBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", "value3")
.build();
try {
post(url, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String JSON = response.body().string();
Log.e("res", " " + JSON);
try {
JSONObject jsonObj = new JSONObject(JSON);
JSONArray resultarr = jsonObj.getJSONArray("result");
final JSONArray resultarr1 = jsonObj.getJSONArray("result1");
ban.OpenDB();
ban.OpenDB();
for (int i = 0; i < resultarr1.length(); i++) {
Employee emp = new Employee();
JSONObject result1obj = resultarr1.getJSONObject(i);
String result1Id = result1obj.getString(ConstantValues.Bank_ID);
String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
Log.e("result", " " + result1Id);
Log.e("result", " " + result1NAME);
emp.setId(result1obj.getString(ConstantValues.Bank_ID));
emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
arr.add(emp);
long l = 0;
l=ban.InsertQryForTabEmpData(ConstantValues.Bank_ID,ConstantValues.Bank_NAME);
}
ban.CloseDB();
runOnUiThread(new Runnable() {
#Override
public void run() {
cu.notifyDataSetChanged();
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
} else {
Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
}
}
});
}
private ArrayList<Employee> InitializeData() {
ArrayList<Employee> arr_emp = new ArrayList<Employee>();
bank ban = new bank(Recyclerview.this);
long l = 0;
ban.OpenDB();
arr_emp = ban.AllSelectQryForTabEmpData1();
ban.CloseDB();
return arr_emp;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
It is the query of all SQLite:
public class bank {
private Context context;
private SQLiteDatabase SQLiteDb;
public bank(Context context){
this.context=context;
}
public static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, ConstantValues.DBName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
}
public void OpenDB() {
SQLiteDb = new DBHelper(context).getWritableDatabase();
}
public void CloseDB() {
if (SQLiteDb.isOpen()) {
SQLiteDb.close();
}
}
public long InsertQryForTabEmpData(String ID, String NAME) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.insert(ConstantValues.TabEmpData, null, cv);
return l;
}
public long UpdateQryForTabEmpData(String ID
, String NAME
) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.update(ConstantValues.TabEmpData, cv, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public long DeleteQryForTabEmpData(String ID) {
long l = SQLiteDb.delete(ConstantValues.TabEmpData, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public ArrayList SelectQryForTabEmpData(String ID) {
ArrayList<String> data = new ArrayList();
String[] arg = {
"ID"
, "NAME"
};
String selection = " ID= " + ID;
String QRY = " SELECT ID,NAME FROM TabEmpData WHERE ID = " + ID;// +" AND EmpFName = 'test' grup by empid,fname,lastname having Empsalary > = 2000 order by fname asc,salry desc limit 100";
Cursor cursor = SQLiteDb.rawQuery(QRY, null);//
SQLiteDb.query(ConstantValues.TabEmpData, arg, selection, null, null, null, null, null);
while (cursor.moveToNext()) {
data.add(0, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID)));
data.add(1, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME)));
}
cursor.close();
return data;
}
public ArrayList AllSelectQryForTabEmpData1() {
ArrayList<Employee> data = new ArrayList();
Cursor cursor = SQLiteDb.query(ConstantValues.TabEmpData, null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID));
String name = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME));
data.add(new Employee(id, name));
}
cursor.close();
return data;
}
}
Its my Custom Adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.EmpDataViewHolder> {
final bank ban = new bank(CustomAdapter.this.context);
private ArrayList<Employee> arr,filterlist;
private Context context;
public CustomAdapter(Context context, ArrayList<Employee> arr) {
this.arr=arr;
this.context=context;
Toast.makeText(context,""+arr.size(),Toast.LENGTH_LONG).show();
}
#Override
public EmpDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.cardview, parent, false);
EmpDataViewHolder edvh = new EmpDataViewHolder(v);
return edvh;
}
#Override
public void onBindViewHolder(EmpDataViewHolder holder, int position) {
Employee emp=arr.get(position) ;
holder.id.setText(emp.getId());
holder.name.setText(emp.getName());
holder.cv.setTag(R.string.KeyForCV,position);
}
#Override
public int getItemCount() {
return arr.size();
}
public class EmpDataViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView id;
TextView name;
public EmpDataViewHolder(View itemView) {
super(itemView);
cv= (CardView) itemView.findViewById(R.id.cv);
id= (TextView) itemView.findViewById(R.id.id);
name= (TextView) itemView.findViewById(R.id.name);
}
}
}
Do help me i want to get rid out of this problem thank you in advance
Related
I need your help. I want to delete data from my Database by actionModeCallbacks inside the RecyclerView.
remove a users from my recyclerview/database.
This is my logcat.
Process: com.andylab.recovermessages, PID: 24576
android.database.sqlite.SQLiteException: near "=": syntax error (code 1 SQLITE_ERROR): , while compiling: DELETE FROM users = com.andylab.recovermessages.models.UserModel#dff4685;
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:939)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:550)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1770)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
at com.andylab.recovermessages.db.recentNumberDB.deleteItem(recentNumberDB.java:367)
at com.andylab.recovermessages.adapters.UsersAdapter$1.onActionItemClicked(UsersAdapter.java:70)
at androidx.appcompat.app.AppCompatDelegateImpl$ActionModeCallbackWrapperV9.onActionItemClicked(AppCompatDelegateImpl.java:2171)
at androidx.appcompat.view.StandaloneActionMode.onMenuItemSelected(StandaloneActionMode.java:141)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)
at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
at android.view.View.performClick(View.java:6608)
at android.view.View.performClickInternal(View.java:6585)
at android.view.View.access$3100(View.java:785)
at android.view.View$PerformClick.run(View.java:25921)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
2020-05-10 02:55:30.109 24576-24576/com.andylab.recovermessages I/Process: Sending signal. PID: 24576 SIG: 9
This is my datadb.
private class datadb extends SQLiteOpenHelper {
private static final String CREATE_TABLE_ADDED_PACKAGES = "CREATE TABLE table_packages (ID INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT unique);";
static final String CREATE_TABLE_FILES = "CREATE TABLE files (_id INTEGER PRIMARY KEY AUTOINCREMENT, files TEXT, whole_time LONG);";
static final String CREATE_TABLE_MSG = "CREATE TABLE messeges (_id INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT, username TEXT, msg TEXT, small_time TEXT, whole_time LONG);";
private static final String CREATE_TEBLE_COOL = "CREATE TABLE cool_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, cool_text TEXT unique);";
private static final String CREATE_TEBLE_QUICK_REPLY = "CREATE TABLE quick_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, quick_reply TEXT);";
private static final String CREATE_TEBLE_REPEATER = "CREATE TABLE repeater_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, text_repeater TEXT);";
private static final String CREATE_TEBLE_UNSAVED = "CREATE TABLE num_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, nums TEXT unique);";
static final String CREATE_USER_WITH_ID = "CREATE TABLE users (_id INTEGER PRIMARY KEY AUTOINCREMENT, package TEXT, username TEXT UNIQUE, read_unread boolean, whole_time DATETIME DEFAULT CURRENT_TIMESTAMP);";
private static final String ID = "_id";
private static final String NAME = "recover.db";
private static final int version = 1;
public void onUpgrade(SQLiteDatabase sQLiteDatabase, int i, int i2) {
}
public datadb(Context context) {
super(context, NAME, null, version);
}
public void onCreate(SQLiteDatabase sQLiteDatabase) {
sQLiteDatabase.execSQL(CREATE_TEBLE_UNSAVED);
sQLiteDatabase.execSQL(CREATE_TEBLE_QUICK_REPLY);
sQLiteDatabase.execSQL(CREATE_TEBLE_REPEATER);
sQLiteDatabase.execSQL(CREATE_TEBLE_COOL);
sQLiteDatabase.execSQL(CREATE_USER_WITH_ID);
sQLiteDatabase.execSQL(CREATE_TABLE_MSG);
sQLiteDatabase.execSQL(CREATE_TABLE_FILES);
sQLiteDatabase.execSQL(CREATE_TABLE_ADDED_PACKAGES);
}
}
public recentNumberDB(Context context) {
this.context = context;
}
public long addData(String str, String str2, String str3, String str4, String str5) {
Long l = null;
try {
addUser(str2, str, str5);
SQLiteDatabase writableDatabase = new datadb(this.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username", str);
contentValues.put("small_time", str4);
contentValues.put("whole_time", str5);
contentValues.put(NotificationCompat.CATEGORY_MESSAGE, str3);
contentValues.put("package", str2);
l = writableDatabase.insert("messeges", null, contentValues);
writableDatabase.close();
} catch (Exception str6) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str6.toString());
Log.d("dblog", stringBuilder.toString());
}
return l;
}
public void addUser(String str, String str2, String str3) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
String str4 = str;
String str5 = str2;
String str6 = str3;
String str7 = "package";
String str8 = "read_unread";
String str9 = "whole_time";
String str10 = "username";
String str11 = "addedusrsnum";
Log.d(str11, "adding started");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("current time ");
stringBuilder.append(str6);
Log.d(str11, stringBuilder.toString());
try {
SQLiteDatabase writableDatabase = new datadb(view_deleted_messages_dbs_recentNumberDB.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(str10, str5);
contentValues.put(str9, str6);
contentValues.put(str8, Boolean.valueOf(false));
contentValues.put(str7, str4);
String str12 = "users";
if (writableDatabase.query("users", new String[]{str10, str7}, "username=? AND package=?", new String[]{str5, str4}, null, null, null).getCount() == 0) {
writableDatabase.insert(str12, null, contentValues);
Log.d(str11, "greater 0");
} else {
contentValues.clear();
contentValues.put(str9, str6);
contentValues.put(str8, Boolean.valueOf(false));
writableDatabase.update(str12, contentValues, "username=? AND package=?", new String[]{str5, str4});
Log.d(str11, "updates");
}
writableDatabase.close();
} catch (Exception e) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("error: ");
stringBuilder2.append(e.toString());
Log.d(str11, stringBuilder2.toString());
}
}
public List<HashMap> getUsers(String str) {
String str2 = "username";
String str3 = "read_unread";
List<HashMap> arrayList = new ArrayList();
try {
SQLiteDatabase readableDatabase = new datadb(this.context).getReadableDatabase();
SQLiteDatabase sQLiteDatabase = readableDatabase;
Cursor query = sQLiteDatabase.query("users", new String[]{str3, str2}, "package=?", new String[]{str}, null, null, "whole_time DESC");
while (query.moveToNext()) {
HashMap hashMap = new HashMap();
Log.d("readunr", query.getString(query.getColumnIndex(str3)));
hashMap.put("boolean", query.getString(query.getColumnIndex(str3)));
hashMap.put("string", query.getString(query.getColumnIndex(str2)));
arrayList.add(hashMap);
}
query.close();
readableDatabase.close();
} catch (Exception str4) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str4.toString());
Log.d("dblog", stringBuilder.toString());
}
return arrayList;
}
public List<DataModel> getMsg(String str, String str2) {
String str3 = "small_time";
String str4 = NotificationCompat.CATEGORY_MESSAGE;
List<DataModel> arrayList = new ArrayList();
try {
SQLiteDatabase writableDatabase = new datadb(this.context).getWritableDatabase();
SQLiteDatabase sQLiteDatabase = writableDatabase;
Cursor query = sQLiteDatabase.query("messeges", new String[]{str4, str3}, "username=? AND package=?", new String[]{str, str2}, null, null, null);
while (query.moveToNext()) {
arrayList.add(new DataModel(query.getString(query.getColumnIndex(str4)), query.getString(query.getColumnIndex(str3))));
}
query.close();
writableDatabase.close();
} catch (Exception str5) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("error: ");
stringBuilder.append(str5.toString());
Log.d("dblog", stringBuilder.toString());
}
return arrayList;
}
public boolean isPresent(String str, String str2, String str3) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
String str4 = str;
String str5 = NotificationCompat.CATEGORY_MESSAGE;
String str6 = "dblog";
boolean z = false;
try {
SQLiteDatabase readableDatabase = new datadb(view_deleted_messages_dbs_recentNumberDB.context).getReadableDatabase();
SQLiteDatabase sQLiteDatabase = readableDatabase;
Cursor query = sQLiteDatabase.query("messeges", new String[]{str5}, "username=? AND package=?", new String[]{str4, str3}, null, null, "_id DESC", "1");
if (query.getCount() > 0) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("isPresentusername=");
stringBuilder.append(str4);
stringBuilder.append("Size=");
stringBuilder.append(String.valueOf(query.getCount()));
Log.d(str6, stringBuilder.toString());
while (query.moveToNext()) {
str4 = query.getString(query.getColumnIndex(str5));
stringBuilder = new StringBuilder();
stringBuilder.append("ispresend greater 0. chat = ");
stringBuilder.append(str4);
Log.d(str6, stringBuilder.toString());
z = str4.equals(str2);
}
} else {
Log.d(str6, "ispresent is 0");
}
query.close();
readableDatabase.close();
} catch (Exception e) {
StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.append("error: ");
stringBuilder2.append(e.toString());
Log.d(str6, stringBuilder2.toString());
}
return z;
}
public List<UserModel> getHomeList(String s) {
recentNumberDB view_deleted_messages_dbs_recentNumberDB = this;
ArrayList<UserModel> list = new ArrayList<UserModel>();
try {
List<HashMap> users = this.getUsers(s);
SQLiteDatabase readableDatabase = new recentNumberDB.datadb(view_deleted_messages_dbs_recentNumberDB.context).getReadableDatabase();
for (int i = 0; i < users.size(); ++i) {
Cursor query = readableDatabase.query("messeges", new String[] { "msg", "small_time" }, "username=? AND package=?", new String[] { users.get(i).get("string").toString(), s }, (String)null, (String)null, "_id DESC", "1");
if (query != null) {
StringBuilder sb = new StringBuilder();
sb.append("users lenght ");
sb.append(users.size());
Log.d("emptylog", sb.toString());
StringBuilder sb2 = new StringBuilder();
sb2.append("cursor lenght ");
sb2.append(String.valueOf(query.getCount()));
Log.d("emptylog", sb2.toString());
if (query.getCount() == 0) {
list.add(new UserModel(users.get(i).get("string").toString(), "no recent msg", "", 1));
}
else {
while (true) {
int moveToNext = query.moveToNext() ? 1 : 0;
if (moveToNext == 0) {
break;
}
list.add(new UserModel(users.get(i).get("string").toString(), query.getString(0), query.getString(moveToNext), Integer.parseInt(users.get(i).get("boolean").toString())));
Log.d("emptylog", query.getString(0));
}
}
query.close();
}
else {
Log.d("emptylog", "cursor null");
}
}
readableDatabase.close();
return list;
}
catch (Exception ex) {
return list;
}
}
public void addPackages(String s) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("package", s);
writableDatabase.insert("table_packages", (String)null, contentValues);
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public ArrayList<String> getAllPackages() {
String[] array = { "com.whatsapp", "com.whatsapp.w4b", "com.gbwhatsapp", "com.facebook.lite", "com.facebook.orca", "com.facebook.mlite", "org.telegram.messenger" };
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
try {
Cursor query = new recentNumberDB.datadb(this.context).getReadableDatabase().query("table_packages", new String[] { "package" }, (String)null, (String[])null, (String)null, (String)null, (String)null);
boolean moveToNext;
while (true) {
moveToNext = query.moveToNext();
if (!moveToNext) {
break;
}
list.add(query.getString(0));
}
query.close();
int n = moveToNext ? 1 : 0;
int i;
while (true) {
i = (moveToNext ? 1 : 0);
if (n >= array.length) {
break;
}
if (list.contains(array[n])) {
list2.add(array[n]);
}
++n;
}
while (i < list.size()) {
if (!list2.contains(list.get(i))) {
list2.add(list.get(i));
}
++i;
}
return list2;
}
catch (Exception ex) {
return list2;
}
}
public void removePackageAndMsg(ArrayList<String> list) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
Iterator<String> iterator = list.iterator();
while (true) {
int hasNext = iterator.hasNext() ? 1 : 0;
if (hasNext == 0) {
break;
}
String s = iterator.next();
String[] array = new String[hasNext];
array[0] = s;
writableDatabase.delete("table_packages", "package=?", array);
String[] array2 = new String[hasNext];
array2[0] = s;
writableDatabase.delete("users", "package=?", array2);
String[] array3 = new String[hasNext];
array3[0] = s;
writableDatabase.delete("messeges", "package=?", array3);
}
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void remove(ArrayList<String> list) {
try {
SQLiteDatabase writableDatabase = new recentNumberDB.datadb(this.context).getWritableDatabase();
Iterator<String> iterator = list.iterator();
while (true) {
int hasNext = iterator.hasNext() ? 1 : 0;
if (hasNext == 0) {
break;
}
String s = iterator.next();
String[] array = new String[hasNext];
array[0] = s;
/// writableDatabase.delete("table_packages", "package=?", array);
String[] array2 = new String[hasNext];
array2[0] = s;
writableDatabase.delete("users", "package=?", array2);
String[] array3 = new String[hasNext];
array3[0] = s;
writableDatabase.delete("messeges", "package=?", array3);
}
writableDatabase.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void deleteItem(UserModel position){
SQLiteDatabase db = new recentNumberDB.datadb(this.context).getWritableDatabase();
db.execSQL("DELETE FROM " + "users" + "package=?" + "username" + " = " + position + ";");
db.execSQL("DELETE FROM " + "messeges" + "package=?" + "small_time" + " = " + position + ";");
db.close();
}
}
And this is my adapter
`public class UsersAdapter extends RecyclerView.Adapter <UsersAdapter.RecyclerViewHolder> {
private Context context;
private ArrayList <UserModel> list;
private ArrayList<UserModel> selectedItems = new ArrayList<UserModel>();
private String pack;
private SparseBooleanArray mSelectedItemsIds;
LayoutInflater inflater;
private boolean multiSelect = false;
private ActionMode.Callback actionModeCallbacks = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
multiSelect = true;
menu.add("Delete");
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
for (UserModel intItem : selectedItems) {
list.remove(intItem);
notifyDataSetChanged ();
recentNumberDB recentNumberDB = new recentNumberDB(context);
recentNumberDB.deleteItem ( intItem );
}
switch (item.getItemId()) {
case R.id.action_delete:
return true;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
multiSelect = false;
selectedItems.clear();
notifyDataSetChanged();
}
};
public void itemRemoved(int position) {
recentNumberDB recentNumberDB = new recentNumberDB(context);
list.remove(position);
notifyItemRemoved(position);
recentNumberDB.deleteItem(position);
}
public UsersAdapter(Context context, ArrayList <UserModel> list, String str) {
this.context = context;
this.list = (ArrayList <UserModel>) list;
this.pack = str;
mSelectedItemsIds = new SparseBooleanArray();
this.inflater = LayoutInflater.from(context);
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder{
ConstraintLayout listt;
TextView msg;
TextView name;
TextView readunread;
TextView time;
public ImageButton btn_delete;
public CheckBox chkSelected;
public RecyclerViewHolder(#NonNull View itemView) {
super ( itemView );
name = (TextView) itemView.findViewById(R.id.name);
msg = (TextView) itemView.findViewById(R.id.msg);
time = (TextView) itemView.findViewById(R.id.time);
listt = (ConstraintLayout) itemView.findViewById(R.id.list);
readunread = (TextView) itemView.findViewById(R.id.unread);
btn_delete = (ImageButton) itemView.findViewById(R.id.btn_delete_unit);
chkSelected = (CheckBox) itemView.findViewById(R.id.chk_selected);
}
public void selectItem(UserModel list) {
if (multiSelect) {
if (selectedItems.contains(list)) {
selectedItems.remove(list);
itemView.setBackgroundColor(Color.WHITE);
} else {
selectedItems.add(list);
itemView.setBackgroundColor(Color.LTGRAY);
}
}
}
public void update(final UserModel value) {
// textView.setText(value + "");
if (selectedItems.contains(value)) {
itemView.setBackgroundColor(Color.LTGRAY);
} else {
itemView.setBackgroundColor( Color.WHITE);
}
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
((AppCompatActivity)view.getContext()).startSupportActionMode(actionModeCallbacks );
selectItem(value);
return true;
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectItem(value);
}
});
}
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.users_home, parent, false);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
UserModel userModel = (UserModel) list.get(position);
holder.name.setText(userModel.getName());
holder.msg.setText(userModel.getLastmsg());
holder.time.setText(userModel.getTime());
holder.listt.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (adCount%4==0){
/// AdmobHelper.showInterstitialAd(context, AdmobHelper.ADSHOWN);
}
adCount++;
Intent intent = new Intent(context, MessegesActivity.class);
intent.putExtra("name", userModel.getName());
intent.putExtra("pack", pack);
context.startActivity(intent);
}
});
holder.update(list.get(position));
}
#Override
public int getItemCount() {
return list.size();
}
}`
I have a textview that gets data from sqlite database but when I delete a row,or change it ,I also want to change what the textview has,the data the textview contains is basically the sum of all rows specific column,so how can I update the textview when updating sqlite data?
here is my main code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tinyDB = new TinyDB(getApplicationContext());
listView = findViewById(R.id.listt);
pharmacynme = findViewById(R.id.pharmacynme);
constraintLayout = findViewById(R.id.thelayout);
mBottomSheetDialog2 = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
inflater2 = (LayoutInflater) LoggedIn.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mBottomSheetDialog = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
content = inflater2.inflate(R.layout.activity_main2, null);
content2 = inflater2.inflate(R.layout.smalldialog, null);
total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
pharmacydescrr = findViewById(R.id.pharmacydiscribtion);
String nme = getIntent().getStringExtra("pharmacy_name");
String diskr = getIntent().getStringExtra("pharmacy_disk");
pharmacydescrr.setText(diskr);
pharmacynme.setText(nme);
//Listview Declaration
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListItems>();// Connection Class Initialization
etSearch = findViewById(R.id.etsearch);
etSearch.setSingleLine(true);
chat = findViewById(R.id.chat);
mDatabaseHelper = new DatabaseHelper(this);
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
System.out.println("IDKSDKASDJKAS"+mDatabaseHelper.ifExists());
if (mDatabaseHelper.ifExists()){
mBottomSheetDialog2.show();
total.setText(mDatabaseHelper.getPriceSum());
}else {
}
chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameid = getIntent().getStringExtra("nameid");
Intent intent = new Intent(LoggedIn.this,ChatActivity.class);
intent.putExtra("nameid",nameid);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
// myAppAdapter.filter(text);
}
});
SyncData orderData = new SyncData();
orderData.execute("");
}
public void AddData(String newEntry,String price,String amount){
boolean insertData = mDatabaseHelper.addData(newEntry,price,amount);
if (insertData){
toastMessage("Data Successfully inserted!");
}else {
toastMessage("Al anta 4abebto da ya youssef >:(");
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(LoggedIn.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String nme = getIntent().getStringExtra("pharmacy_name");
System.out.println(nme);
String query = "Select StoreArabicName,StoreEnglishName,StoreSpecialty,StoreCountry,StoreLatitude,StoreLongitude,Store_description,ProductData.ProductArabicName,ProductData.ProductImage,ProductData.ProductEnglishName,ProductData.ProductDescription,ProductData.ProductPrice FROM StoresData INNER JOIN ProductData ON StoresData.StoreID = ProductData.StoreID WHERE StoreEnglishName = '"+nme+"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("ProductEnglishName"), rs.getString("ProductDescription"), rs.getString("ProductPrice"),rs.getString("ProductImage")));
System.out.println(rs.getString("ProductImage"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg!=null){
Toast.makeText(LoggedIn.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, LoggedIn.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter//has a class viewholder which holds
{
private ArrayList<ClassListItems> mOriginalValues; // Original Values
private ArrayList<ClassListItems> mDisplayedValues;
public class ViewHolder {
TextView textName;
TextView textData;
TextView textImage;
ImageView producticon;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.sdadprice);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.setContentView(content);
total.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoggedIn.this,Listitemsbought.class);
startActivity(intent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
final Float allitemscount = Float.parseFloat(parkingList.get(position).getImage());
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
AddData(parkingList.get(position).getProname(),String.valueOf(last),String.valueOf(counter));
total.setText(mDatabaseHelper.getPriceSum());
mBottomSheetDialog2.show();
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
// if (tinyDB.getString("selecteditem").equals("English")){
// Toast.makeText(LoggedIn.this,"Sorry this ability isn't here yet",Toast.LENGTH_LONG).show();
// }else {
// Toast.makeText(LoggedIn.this,"عفوا هذه الخاصية ليست متوفرة حاليا",Toast.LENGTH_LONG).show();
// }
}
});
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
itemArrayList.clear();
if (charText.length() == 0) {
itemArrayList.addAll(arraylist);
} else {
for (ClassListItems st : arraylist) {
if (st.getProname().toLowerCase(Locale.getDefault()).contains(charText)) {
itemArrayList.add(st);
}
}
}
notifyDataSetChanged();
}
}
private Float parseFloat(String s){
if(s == null || s.isEmpty())
return 0.0f;
else
return Float.parseFloat(s);
}
And here is my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "DatabaseHelper";
private static final String NAME = "Name";
private static final String PRICE = "Price";
private static final String AMOUNT = "Amount";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null , 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ("+PRICE+" TEXT, "+ NAME + " TEXT,"+ AMOUNT +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String Price,String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PRICE,Price);
contentValues.put(NAME, item);
contentValues.put(AMOUNT, amount);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long insert = db.insert(TABLE_NAME,null,contentValues);
if (insert == -1){
return false;
}else {
return true;
}
}
public Cursor getDataOfTable(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT Name,Amount FROM " + TABLE_NAME ;
Cursor data = db.rawQuery(query, null);
return data;
}
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor price = db.rawQuery(query, null);
String result = "" + price.getString(0);
price.close();
db.close();
return result;
}
public boolean ifExists()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String checkQuery = "SELECT * FROM " + TABLE_NAME + " LIMIT 1";
cursor= db.rawQuery(checkQuery,null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public void delete(String nameofrow) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+TABLE_NAME+" where "+NAME+"='"+nameofrow+"'");
}
}
Any help?!
The method getPriceSum() should return the sum and not a Cursor:
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(query, null);
String result = "";
if (c.moveToFirst()) result = "" + c.getString(0);
c.close();
db.close();
return result;
}
I don't think that you need the if block:
if (mDatabaseHelper.ifExists()) {
.......................
}
All you need to do is:
total.setText(mDatabaseHelper.getPriceSum());
I am really stuck and have no idea what to do. I have looked into startActivityForResult and Content providers and I have no clue how to implement any of them for this app.
I am not seeing how to get the data from the database and update the displayBottomList using same listview so I don't have to redirect the user to a new layout/activity. Not sure if I can even call a new query and set that to a different cursor and switch between them. I have seen swapCursor but how does that work when using the same adapter?
I have a ListView that I want to refresh with new data from a web service call when the user clicks on a row within the list. I am using a CursorAdapter. I can get the data correctly onClick of the row.
Where I am stuck, is how do I update that listView to repopulate with the new info from the database/response without sending me to another Activity. I want the user to stay on the same screen but just update the listView with the new data.
Not sure how to get the adapter to notify the adapter to update and populate a new ListView when the onClick is in the adapter, but the ListView is being created in the MainActivity.
The Adapter for BottomListView, the one I want to update when a row is clicked.
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_layout, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
dbHandler = new EmployeeDBHandler(context);
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mCardView = (CardView) view.findViewById(R.id.home_screen_cardView);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(1);
String mEmail = cursor.getString(8);
String mFirstName = cursor.getString(2);
String mLastName = cursor.getString(3);
String mPhoneMobile = cursor.getString(4);
String mPhoneOffice = cursor.getString(5);
String mCostCenter = cursor.getString(10);
String mHasDirectReports = cursor.getString(7);
String mTitle = cursor.getString(6);
String mPic = cursor.getString(9);
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(mIntent);
}
});
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
mEmployeeNumber = cursor.getString(1);
Toast.makeText(context, mEmployeeNumber, Toast.LENGTH_SHORT).show();
callNewDirectReport();
notifyDataSetChanged();
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}
private void callNewDirectReport() {
String mDirectReportUrl = "mURL";
HttpUrl.Builder urlBuilder = HttpUrl.parse(mDirectReportUrl).newBuilder();
urlBuilder.addQueryParameter("manager_employee_number", mEmployeeNumber);
String url = urlBuilder.build().toString();
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
}
});
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
My MainActivity that is calling the adapter
public class MainActivity extends AppCompatActivity {
private ProgressBar mProgressBar;
private BottomListViewAdapter mBottomAdapter;
private View mDividerView;
EmployeeDBHandler dbHandler;
private int mStartingEmployeeID = mStartingID;
private String table = "employees";
private static final int LOADER_INTEGER = 1;
private Cursor mBottomCursor, mTopCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mDividerView = findViewById(R.id.divider);
dbHandler = new EmployeeDBHandler(getApplicationContext());
mProgressBar.setVisibility(View.VISIBLE);
mDividerView.setVisibility(View.GONE);
getXMLData();
//GUI for seeing android SQLite Database in Chrome Dev Tools
Stetho.InitializerBuilder inBuilder = Stetho.newInitializerBuilder(this);
inBuilder.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this));
Stetho.Initializer in = inBuilder.build();
Stetho.initialize(in);
}
public void getXMLData() {
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(getString(R.string.API_FULL_URL))
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setVisibility(View.GONE);
mDividerView.setVisibility(View.VISIBLE);
displayTopList();
displayBottomList();
}
});
}
});
}
public void displayTopList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
ListView mTopListView = (ListView) findViewById(R.id.mTopList);
TopListCursorAdapter topAdapter = new TopListCursorAdapter(this, mTopCursor);
mTopListView.setAdapter(topAdapter);
}
public void displayBottomList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mBottomCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
ListView mBottomListView = (ListView) findViewById(R.id.mDirectReportList);
mBottomAdapter = new BottomListViewAdapter(this, mBottomCursor);
mBottomListView.setAdapter(mBottomAdapter);
mBottomAdapter.notifyDataSetChanged();
}
}
Right now your code in callNewDirectReport() makes an API request and stores the results in the database. This will not update the adapter to show the new items, instead you need to requery the database and get a newer Cursor. Below is an example of how you may do it:
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
private Activity activityRef;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
// keep a reference to the activity
activityRef = (Activity) context;
}
//...
private void callNewDirectReport() {
//...
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
// the new items are in the database so requery the database to get a new fresher Cursor:
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor fresherCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
//change the adapter's Cursor
activityRef.runOnUiThread(new Runnable() {
public void run() {
swapCursor(freshedCursor);
}
});
}
});
}
}
You can use startActivityForResult to receive a callback from an activity, here you have a tutorial explaining how to use it: https://developer.android.com/training/basics/intents/result.html
When you receive the callback in the onActivityResult, you can update your data and call notifyDatasetChanged.
You can't call code from an activity in another because activities are handled by android. Android could have killed the activity that you are trying to call and will just recreate it when necessary.
This is structure of my json respose :
{
"data": [
{
"id": 23,
"title": "this is title",
"description": " this is desc",
"date": "21/2/16",
"authorname": "john smith",
"authorpic": "http://xtryz.com/users/1462862047com.yahoo.mobile.client.android.yahoo_128x128.png",
"filename": "1463770591.MP4",
"downloadlink": "http://xyrgz.com/download.zip",
"downloadcnt": "24"
},
...
]
And with clicking one Buton in each row of RecyclerView I save that json row In the Database . Know for some work I need to know is this json row exist in the Database or no ? for doing this work , I Want to use the id in the database and id of the json . and if id of the database same to id of the json , doing some work and else .
This is the QuestionDatabaseAdapter :
public class QuestionDatabaseAdapter {
private Context context;
private SQLiteOpenHelper sqLiteOpenHelper;
private static final int DATABASE_VERSION = 1;
//private SQLiteDatabase database = null;
public QuestionDatabaseAdapter(Context context) {
this.context = context;
sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, DATABASE_VERSION) {
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE tbl_questions ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, question_id VARCHAR( 255 ) NOT NULL , title VARCHAR( 255 ) NOT NULL, [desc] TEXT NOT NULL, Date VARCHAR( 50 ) NOT NULL, authorName VARCHAR( 255 ) NOT NULL , authorPic VARCHAR( 255 ) NOT NULL, downLink VARCHAR( 255 ) NOT NULL )";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
};
}
//================== SAVE QUESTION IN DATABASE ==========================
public long saveQuestion(ModelQuestion modelQuestion) {
String question_id = modelQuestion.getQuestionId();
String title = modelQuestion.getQuestionTitle();
String desc = modelQuestion.getQuestionDesc();
String date = modelQuestion.getQuestionDate();
String authorName = modelQuestion.getQuestionAuthorName();
String authorPic = modelQuestion.getQuestionAuthorPic();
String downloadLink = modelQuestion.getQuestionDownLink();
SQLiteDatabase database = null;
long id = -1;
try {
ContentValues values = new ContentValues();
values.put("question_id", question_id);
values.put("title", title);
values.put("desc", desc);
values.put("date", date);
values.put("authorName", authorName);
values.put("authorPic", authorPic);
values.put("downLink", downloadLink);
database = sqLiteOpenHelper.getWritableDatabase();
id = database.insert("tbl_questions", null, values);
} catch (Exception ex) {
Log.i("DATABASE SAVE EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return id;
}
//=================== READ ALL QUESTION IN DATABASE=========================
public ArrayList<ModelQuestion> readAllQuestions() {
ArrayList<ModelQuestion> questions = null;
String[] columns = new String[]{"*"};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
String favorite = null;
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getReadableDatabase();
Cursor cursor = database.query("tbl_questions", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if (cursor != null && cursor.moveToFirst()) {
questions = new ArrayList<ModelQuestion>();
int indexQuestionId = 0;
int indexTitle = 1;
int indexDesc = 2;
int indexDate = 3;
int indexAuthorName = 4;
int indexAuthorPic = 5;
int indexDownloadLink = 6;
int indexFavorite = 7;
do {
String questionId = cursor.getString(indexQuestionId);
String questionTitle = cursor.getString(indexTitle);
String questionDesc = cursor.getString(indexDesc);
String questionDate = cursor.getString(indexDate);
String questionAuthorName = cursor.getString(indexAuthorName);
String questionAuthorPic = cursor.getString(indexAuthorPic);
String questionDownloadLink = cursor.getString(indexDownloadLink);
ModelQuestion question = new ModelQuestion();
question.setQuestionId(questionId);
question.setQuestionTitle(questionTitle);
question.setQuestionDesc(questionDesc);
question.setQuestionDate(questionDate);
question.setQuestionAuthorName(questionAuthorName);
question.setQuestionAuthorPic(questionAuthorPic);
question.setQuestionDownLink(questionDownloadLink);
questions.add(question);
} while (cursor.moveToNext());
}
} catch (Exception ex) {
Log.i("DATABASE READ ALL EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return questions;
}
//=================== DELETE ONE QUESTION IN DATABASE=========================
public int deletePerson(long id) {
int noOfDeletedRecords = 0;
String whereClause = "id=?";
String[] whereArgs = new String[]{String.valueOf(id)};
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getWritableDatabase();
noOfDeletedRecords = database.delete("tbl_questions", whereClause, whereArgs);
} catch (Exception ex) {
Log.i("DATABASE DELETE EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return noOfDeletedRecords;
}
}
And this is The adapterRecyclerQuestion :
public class AdapterRecyclerQuestion extends RecyclerView.Adapter<AdapterRecyclerQuestion.ViewHolder> {
private Context context;
private ArrayList<ModelQuestion> questionha;
//constructor
public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha) {
this.context = context;
this.questionha = questionha;
}
//viewholder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView txtTitle;
private TextView txtDesc;
private TextView txtCntDown;
private ImageView imgAuthorPic;
private TextView txtAuthorName;
private TextView txtDate;
private Button btnDownload;
private ImageView imgAddFav;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_question);
txtDesc = (TextView) itemView.findViewById(R.id.txt_desc_question);
txtCntDown = (TextView) itemView.findViewById(R.id.txt_cnt_down_question_dy);
imgAuthorPic = (ImageView) itemView.findViewById(R.id.img_author_pic_question);
txtAuthorName = (TextView) itemView.findViewById(R.id.txt_author_name_question);
txtDate = (TextView) itemView.findViewById(R.id.txt_date_question);
btnDownload = (Button) itemView.findViewById(R.id.btn_down_question);
imgAddFav = (ImageView) itemView.findViewById(R.id.img_add_to_fav);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Hello" + txtTitle.getText(), Toast.LENGTH_SHORT).show();
}
}
//oncreateviewholder
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.question_row, parent, false);
return new ViewHolder(view);
}
//onbindviewholder
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
QuestionDatabaseAdapter questionDatabaseAdapter = new QuestionDatabaseAdapter(holder.itemView.getContext());
questionDatabaseAdapter.readAllQuestions();
holder.txtTitle.setText(questionha.get(position).getQuestionTitle());
holder.txtDesc.setText(questionha.get(position).getQuestionDesc());
holder.txtCntDown.setText(questionha.get(position).getQuestionDownCnt());
holder.txtAuthorName.setText(questionha.get(position).getQuestionAuthorName());
Glide.with(holder.itemView.getContext()).load(questionha.get(position).getQuestionAuthorPic()).into(holder.imgAuthorPic);
holder.txtDate.setText(questionha.get(position).getQuestionDate());
//============= IMG ADD TO FAV ON CLICK LISTENER =========================
holder.imgAddFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuestionDatabaseAdapter databaseAdapter = new QuestionDatabaseAdapter(v.getContext());
ModelQuestion question = new ModelQuestion();
question.setQuestionId(questionha.get(position).getQuestionId());
question.setQuestionTitle(questionha.get(position).getQuestionTitle());
question.setQuestionDesc(questionha.get(position).getQuestionDesc());
question.setQuestionDate(questionha.get(position).getQuestionDate());
question.setQuestionAuthorName(questionha.get(position).getQuestionAuthorName());
question.setQuestionAuthorPic(questionha.get(position).getQuestionAuthorPic());
question.setQuestionDownLink(questionha.get(position).getQuestionDownLink());
databaseAdapter.saveQuestion(question);
Toast.makeText(v.getContext(), "اضافه شد", Toast.LENGTH_SHORT).show();
}
});
//=============BTN DOWNLOAD CLICK LISTENER =========================
holder.btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(questionha.get(position).getQuestionDownLink()));
request.setTitle(questionha.get(position).getQuestionTitle());
request.setDescription("در حال دانلود");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, questionha.get(position).getQuestionDownFileName());
long enqueueId = downloadManager.enqueue(request);
}
});
}
//getitemcount
#Override
public int getItemCount() {
return questionha.size();
}
}
And this is Database Structure :
(question_id is the id of question)
Now i need to compare id of database and id of the json in adapter . but i don't know how can i do this .
private ArrayList<ModelQuestion> questionha;
private ArrayList<ModelQuestion> jsonArrList;
//pass your json arraylist too in constructor from your main activity
public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha,ArrayList<ModelQuestion> jsonArrList) {
this.context = context;
this.questionha = questionha;
this.jsonArrList = jsonArrList;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
for(int i=0;i<jsonArrList.size();i++)
{
//Check your id here
if(jsonArrList.get(i).getId().equalsIgnoreCase(questionha.get(position).getId()))
}
}
I am trying to display result from Database in a listView which is clickable On long click ,items can be deleted and on click it go to another activity. So I create an activity called editdeletedoctor
public class editdeletedoctor extends Activity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = TableData.TableInfo.TABLE_DOCTOR;
private SQLiteDatabase newDB;
private ArrayList<doctorClass> doctor_List = new ArrayList<doctorClass>();
public static String MODEL_TO_EDIT = "MODEL_TO_EDIT";
public ListView list;
public ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
init();
openAndQueryDatabase();
displayResultList();
}
private void init() {
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(editdeletedoctor.this,
registerdoctor.class);
intent.putExtra("theText", doctor_List.get(position).getUsername());
intent.putExtra(editdeletedoctor.MODEL_TO_EDIT,doctor_List.get(position));
editdeletedoctor.this.finish();
startActivity(intent);
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
Builder dialog = new AlertDialog.Builder(editdeletedoctor.this);
dialog.setTitle("Are you sure you want to delete This doctor?");
dialog.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
doctorClass doctor = doctor_List.get(position);
doctor_List.remove(position);
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
HashMap<String, String> conditionKV = new HashMap<String, String>();
conditionKV.put(TableData.TableInfo.DOCTOR_ID, doctor.getId() + "");
db.deleteDoctor(conditionKV);
results.remove(position);
adapter.notifyDataSetChanged();
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
dialog.dismiss();
}
});
dialog.setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return false;
}
});
}
private void displayResultList() {
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
doctor_List = db.getDoctor(null);
for (doctorClass inc : doctor_List) {
if(inc.getId()==TableData.TableInfo.userID)
results.add("Name: " + inc.getUsername() + " Phone:"
+ inc.getPhone() + ",Address: "
+ inc.getAddress());
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
}
}
And in the DatabaseOperations.java class :
public DatabaseOperations open() throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public ArrayList<doctorClass> getDoctor(HashMap<String, String> conditionKV) {
Cursor m_cursor = get(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
ArrayList<doctorClass> list = new ArrayList<doctorClass>();
if (m_cursor.moveToFirst()) {
do {
doctorClass model = new doctorClass();
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)) != null)
model.setId(m_cursor.getInt(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)) != null)
model.setUsername(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)) != null)
model.setPassword(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)) != null)
model.setEmail(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)) != null)
model.setPhone(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)) != null)
model.setAddress(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)) != null)
model.setGender(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)));
list.add(model);
} while (m_cursor.moveToNext());
}// end if
return list;
}
public Cursor get(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV != null)
whereClause = formatWherecondition(conditionKV);
String completeQuery = "SELECT * FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
}
return ourDatabase.rawQuery(completeQuery, null);
}
public String formatWherecondition(HashMap<String, String> conditionKV) {
try {
String result = "";
if (conditionKV.size() < 1) {
throw new Exception("Hahsmap condition Empty");
}
Iterator l_iterator = conditionKV.keySet().iterator();
boolean isOneField = false;
while (l_iterator.hasNext()) {
String l_key = (String) l_iterator.next();
String l_value = conditionKV.get(l_key);
if (isOneField)
result = result + " AND ";
result = result + l_key + "='" + l_value + "' ";
isOneField = true;
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void deleteDoctor(HashMap<String, String> conditionKV) {
delete(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
}
private void delete(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV == null)
return;
whereClause = formatWherecondition(conditionKV);
String completeQuery = "DELETE FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
ourDatabase.execSQL(completeQuery);
}
}
When running, an error occured, Here is the logcat
Please help me .
Thank you
Are you sure the "context" you are using here is not null ?
How about rewriting the open() function this way and calling it via open(getApplicationContext()); ?
public DatabaseOperations open(Context context) throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}