Display Multiple data from database to textview android - android

my problem is cant display all the data i call from my database to my textview when i click the button , but i can only display 1 data at the time , and i read the other question like this but still i dont get it.
This is my Code to call the data from database
public WordObject getPOSbyWords(String wordd){
WordObject wordObject2 = null;
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
if (cursor.moveToFirst()){
do {
//=
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
//String pos2 = cursor.getString(cursor.getColumnIndexOrThrow("words"));
wordObject2 = new WordObject(pos1,null);
}while (cursor.moveToNext());
}
cursor.close();
return wordObject2;
}
This my Code in main activity
public class GrammarActivity extends AppCompatActivity {
TextView postv, wordtv;
Button btngo;
MultiAutoCompleteTextView multiple;
Listview listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grammar);
wordtv = (TextView) findViewById(R.id.grammar);
multiple = (MultiAutoCompleteTextView) findViewById(R.id.MultipleAuto);
btngo = (Button) findViewById(R.id.check);
postv = (TextView) findViewById(R.id.Partofspeech);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
//Welcome user
builder.setMessage("Welcome to the Grammar Checker")
.setIcon(R.mipmap.ic_launcher)
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
//Space Tokenizer splitting the words
final String[] words = getResources().getStringArray(R.array.autocomplete);
multiple.setTokenizer(new SpaceTokenizer());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, words);
multiple.setAdapter(adapter);
btngo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String space = "";
String foo = " ";
String foo1 = ",";
String sentences = null;
String red = multiple.getText().toString();
if (red.isEmpty()) {
Toast.makeText(getApplicationContext(), " Input text please ", Toast.LENGTH_SHORT).show();
multiple.setBackgroundColor(Color.RED);
}else
Toast.makeText(getApplicationContext(), "THanks ", Toast.LENGTH_SHORT).show();
//Splitting the sentence into words
sentences = multiple.getText().toString().toLowerCase();
String[] splitwords = sentences.trim().split("\\s+");
for (String biyak : splitwords) {
foo = (foo + "'" + biyak + "'" + foo1);
String fot = foo.replaceAll(",$", " ");
wordtv.setText(fot);
Db1Backend db1Backend = new Db1Backend(GrammarActivity.this);
WordObject DisplayPOS = db1Backend.getPOSbyWords(fot);
postv.setText(DisplayPOS.getWord());
}
World Class
public class WordObject {
private String word;
private String pos;
public WordObject(String word, String definition) {
this.word = word;
this.pos = definition;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getPOS() {
return pos;
}
public void setPOS(String definition) {
this.pos = definition;
}
}

Try this one.
public String getPOSbyWords(String wordd)
{
String myPos = "";
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
try
{
if (cursor != null && cursor.getCount() > 0)
{
while (cursor.moveToNext())
{
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
myPos = pos1;
}
}
}
catch (Exception e)
{
// Handle Exception here
}
finally
{
// release cursor
if (cursor != null && !cursor.isClosed())
cursor.close();
}
return myPos;
}
Now in your GrammarActivity inside for loop do this.
// Taking String Builder to append all the String in one.
StringBuilder sb = new StringBuilder();
for (String biyak : splitwords)
{
foo = (foo + "'" + biyak + "'" + foo1);
String fot = foo.replaceAll(",$", " ");
wordtv.setText(fot);
Db1Backend db1Backend = new Db1Backend(GrammarActivity.this);
// Append all your position into StringBuilder
sb.append(db1Backend.getPOSbyWords(fot));
}
postv.setText(sb.toString());

Replace your method with this.
public ArrayList<WordObject> getPOSbyWords(String wordd){
WordObject wordObject2 = null;
String query2 = "SELECT pos FROM wordbank WHERE words in ("+wordd+")";
Cursor cursor = this.getDbConnection1().rawQuery(query2,null);
ArrayList<WordObject> words = new ArrayList<>();
if (cursor.moveToFirst()){
do {
//=
String pos1=cursor.getString(cursor.getColumnIndexOrThrow("pos"));
//String pos2 = cursor.getString(cursor.getColumnIndexOrThrow("words"));
wordObject2 = new WordObject(pos1,null);
words.add(wordObject2);
}while (cursor.moveToNext());
}
cursor.close();
return words;
}

Related

database.sqlite.SQLiteException: near "=": syntax error (code 1 SQLITE_ERROR): , while compiling: DELETE FROM users = UserModel#dff4685;

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();
}
}`

Update textview data sqlite Android

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

Null pointer exception while uploading contacts to server

Here i am fetching the name,email,phone number from the mobile and trying to upload to server..Here if the contacts contains name,email and phone number the values will be inserted successfully..but if any of the field is empty it is throwing NULL pointer exception.How to avoid this one..i mean if the contact does not contain email it should atleast send name and phone number.
here is my code.
public class DisplayContact1 extends Activity {
private static String TAG = WorkDetails1.class.getSimpleName();
Button select;
private String vault;
List<AddressBookContact> list;
public static final String kvault = "vault_no";
public static final String kname = "name";
public static final String kphone = "phone";
public static final String kemail = "email";
public static final String kcontacts = "contacts";
public static final String SHARED_PREF_NAME = "myloginapp";
public static final String UPLOAD_URL = "http://oursite.com/contacts_1.php";
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
Cursor cursor;
LongSparseArray<AddressBookContact> array;
long start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.display);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
getAllContacts(this.getContentResolver());
}
public void getAllContacts(ContentResolver cr) {
int result = ContextCompat.checkSelfPermission(DisplayContact1.this, Manifest.permission.READ_CONTACTS);
if (result == PackageManager.PERMISSION_GRANTED){
//fetches contacts from the phone contact list and displays in ascending order
list = new LinkedList<AddressBookContact>();
array = new LongSparseArray<AddressBookContact>();
start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.Data.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
contactsdisplay();
} else {
requestForLocationPermission();
}
}
private void requestForLocationPermission()
{
if (ActivityCompat.shouldShowRequestPermissionRationale(DisplayContact1.this, Manifest.permission.READ_CONTACTS))
{
}
else {
ActivityCompat.requestPermissions(DisplayContact1.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getAllContacts(DisplayContact1.this.getContentResolver());
contactsdisplay();
}
break;
}
}
public void contactsdisplay() {
//Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
ListView lv= (ListView) findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
uploadImage();
}
});
}
public void uploadImage(){
SharedPreferences sharedPreferences = getSharedPreferences(DisplayContact.SHARED_PREF_NAME, MODE_PRIVATE);
final String vault_no = vault;
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DisplayContact1.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("Successfully Saved")){
//Intent intent = new Intent(CollegeDetails.this,Work.class);
Toast.makeText(DisplayContact1.this, s, Toast.LENGTH_SHORT).show();
// startActivity(intent);
}else{
Toast.makeText(DisplayContact1.this,s,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
//RegisterUserClass rh = new RegisterUserClass();
HashMap<String,String> param = new HashMap<String,String>();
JSONArray contacts = new JSONArray();
int i = 1;
for (AddressBookContact addressBookContact : list) {
try {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
JSONObject contact = new JSONObject();
contact.put(kname, addressBookContact.name.toString());
contact.put(kvault, vault_no);
contact.put(kphone, addressBookContact.phone.toString());
if(addressBookContact.email.toString()!=null)
contact.put(kemail, addressBookContact.email.toString());
contacts.put(contact);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
param.put(kcontacts, contacts.toString());
System.out.println("param value.." + i++ +":"+ contacts.toString());
}
return rh.sendPostRequest(UPLOAD_URL, param);
}
}
UploadImage u = new UploadImage();
u.execute();
}
}
here is the AddressBookContact.class
public class AddressBookContact {
private long id;
private Resources res;
String name;
LongSparseArray<String> email;
LongSparseArray<String> phone;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append(name);
} else {
builder.append("name: ").append(name);
}
if (phone != null) {
builder.append("\nphone: ");
for (int i = 0; i < phone.size(); i++) {
int type = (int) phone.keyAt(i);
builder.append(phone.valueAt(i));
if (i + 1 < phone.size()) {
builder.append(", ");
}
}
}
if (email != null) {
builder.append("\nemail: ");
for (int i = 0; i < email.size(); i++) {
int type = (int) email.keyAt(i);
builder.append(email.valueAt(i));
if (i + 1 < email.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (email == null) {
email = new LongSparseArray<String>();
}
email.put(type, address);
}
public void addPhone(int type, String number) {
if (phone == null) {
phone = new LongSparseArray<String>();
}
phone.put(type, number);
}
}
if email field is empty, i am getting null pointer exception at this line..
contact.put(kemail, addressBookContact.email.toString());..so i have added if loop to check the null condition..but then also i am getting exception.
Here
if (addressBookContact.email.toString() != null)
you try to get String from 'email' variable that is null.
Correct comparing is:
if (addressBookContact.email != null)
Add two conditions as below your string might not be null but can be
empty ""
if(addressBookContact.email.toString() != null && !addressBookContact.email.toString().equalsIgnoreCase(""))
contact.put(kemail, addressBookContact.email.toString());
Use TextUtils.
if(!TextUtils.isEmpty(addressBookContact.email.toString())){
contact.put(kemail, addressBookContact.email.toString());
}
And if kemail is compulsory field then in else condition just pass "" empty value.

Nullpointer exception while using SQLite

I am using sqlitedatabase,and i am able to insert data properly,but issue is when i am trying to display inserted data,my app got crash and giving nullpointer exception,can any one tell the what is the issue with my code,following is my snippet code,
Error in this line
if (c1 != null & c1.getCount() != 0) {
MAinActivity.java
public class MainActivity extends Activity {
private ListView upcominglist;
private ListView todays;
private ListView eventhistory;
private ImageView addnewevent;
public ArrayList<ContactListItems> contactList;
public ContactListItems contactListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upcominglist=(ListView)findViewById(R.id.listview_upcoming);
todays=(ListView)findViewById(R.id.listview_todays);
eventhistory=(ListView)findViewById(R.id.listview_eventhistory);
addnewevent=(ImageView)findViewById(R.id.addneweventbutton);
addnewevent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddNewEvent.class);
startActivity(intent);
}
});
contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
else
{
c1.close();
}
c1.close();
String first=contactListItems.getSlno();
System.out.println("First" + first);
String second=contactListItems.getNameofevent();
System.out.println("SEcond"+second);
String third=contactListItems.getDtofevent();
System.out.println("Third"+third);
String fourth=contactListItems.getTimeofevent();
System.out.println("Fourth"+fourth);
String fifth=contactListItems.getDuration();
System.out.println("Fifth"+fifth);
}
Addnewevent.java
public class AddNewEvent extends Activity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
static final int TIME_PICKER_ID = 11111;
int flag = 0;
private ImageView addnewdata;
private LinearLayout lnr;
private Button submit;
private EditText edtnmofevent;
private EditText edtdtofevent;
private EditText edttmofevent;
private EditText edtdurationofevent;
SqlHandler sqlHandler;
private ImageView datepicks;
private ImageView timepicks;
private Calendar cal;
private int hour;
private int min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_event);
sqlHandler = new SqlHandler(getApplicationContext());
addnewdata = (ImageView) findViewById(R.id.addnewdata);
submit = (Button) findViewById(R.id.btnsubmit);
edtnmofevent = (EditText) findViewById(R.id.edtnameofevent);
edtdtofevent = (EditText) findViewById(R.id.edtdateofevent);
edttmofevent = (EditText) findViewById(R.id.edttimeofevent);
edtdurationofevent = (EditText) findViewById(R.id.edtdurationofevent);
datepicks = (ImageView) findViewById(R.id.calndrdat);
timepicks = (ImageView) findViewById(R.id.timepickrs);
cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
timepicks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(TIME_PICKER_ID);
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
StringBuilder dateValue1 = new StringBuilder().append(day).append("-").append(month + 1).append("-")
.append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
try {
testDate1 = sdf123.parse(abs1);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
edtdtofevent.setText(DateFormat);
edtdtofevent.setFocusable(false);
edtdtofevent.setInputType(InputType.TYPE_NULL);
datepicks.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
addnewdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(AddNewEvent.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AddNewEvent.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
lnr = (LinearLayout) findViewById(R.id.addnewlinear);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(25, 0, 0, 0);
TextView valueTV = new TextView(AddNewEvent.this);
// valueTV.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
valueTV.setText(userInput.getText());
valueTV.setLayoutParams(lp);
valueTV.setTextSize(18);
valueTV.setTextColor(Color.parseColor("#2d6cae"));
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(25, 0, 25, 0);
lp1.height = 50;
EditText edtvalues = new EditText(AddNewEvent.this);
edtvalues.setBackgroundResource(R.drawable.rect_edt);
edtvalues.setLayoutParams(lp1);
lnr.addView(valueTV);
lnr.addView(edtvalues);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddNewEvent.this, EventDetails.class);
startActivity(intent);
String nameofevent = edtnmofevent.getText().toString();
String dtofevent = edtdtofevent.getText().toString();
String timeofevent = edttmofevent.getText().toString();
String duration = edtdurationofevent.getText().toString();
String query = "INSERT INTO PHONE_CONTACTS(nameofevent,dtofevent,timeofevent,duration) values ('"
+ nameofevent + "','" + dtofevent + "','" + timeofevent + "','" + duration + "')";
sqlHandler.executeQuery(query);
System.out.println("Querys" + query);
}
});
}
SQL
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "slno";
public static final String COLUMN2 = "nameofevent";
public static final String COLUMN3 = "dtofevent";
public static final String COLUMN4 = "timeofevent";
public static final String COLUMN5 = "duration";
/* public static final String COLUMN6 = "dlabl";
public static final String COLUMN7 = "dedt";*/
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ DATABASE_TABLE + " (" + COLUMN1
+ " integer primary key autoincrement, " + COLUMN2
+ " text not null, " + COLUMN3 + " text not null, " + COLUMN4 + " text not null, " + COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
The problem is in your SqlHandler.selectQuery() that returns a null, and another problem here checking the result:
if (c1 != null & c1.getCount() != 0)
You're using bitwise and & and not the short-circuiting logical and &&. Without short circuiting the complete expression including c1.getCount() on a null reference is evaluated.
There is too much here to explain it all, so I will give you the flaws causing a null pointer exception.
I can see your method of programming is coming from worrying too much about closing things and clearing up
resources to a point, it's causing problems.
contactList = new ArrayList<ContactListItems>();
// You are clearing your list, it should be empty, you have just created it.
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
// As mentioned by the other answer. You need && not &
// if (c1 != null & c1.getCount() != 0) {
if (c1 != null && c1.getCount() != 0) {
// Move to the first entry.
c1.moveToFirst();
//if (c1.moveToNext()) {
// do {
// Continue while it has not passed the last entry.
while (!cursor.isAfterLast())
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
// Move the cursor along to the next entry.
cursor.moveToNext();
}
}
// Close cursor after while and within if (so you know it is not null).
c1.close();
}
else
{
// You can't close c1 if it is Null. This will throw and error. Lose the else.
c1.close();
}
// Move this to within your if statment.
c1.close();
From your code you provided in the chat.
Don't open and close your database continuously, just close each cursor you use when you're done. Just open it at the beginning and end of your program run.
public static Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (sqlDatabase.isOpen()) {
// You are closing the database.
sqlDatabase.close();
}
sqlDatabase = dbHelper.getWritableDatabase();
c1 = sqlDatabase.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
There are many other flaws in your project. Like the structure and how and when you are calling things. You need to modularise it out, create methods for particular tasks and call those methods, rather than have a great lump of code in oncreate.
I am sure you will have many questions about this. But currently this question is addressing your null pointer exception and that is all I will discuss here. For questions about this not relating to this exception, please ask a new question. Hope this helps.

How to get Distinct list of Call log with descending order of date in android using Treeset

In my application, i just want call log with distinct and sorted with descending of date. I tried below code and not getting exact result
my code as follows
public class MainActivity extends Activity {
// List<CLogItem> clogitems = new ArrayList<CLogItem>();
Set clogitems = new TreeSet();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
getCallDetails(this);
TextView tv1 = (TextView)findViewById(R.id.tv1);
String str = "";
Iterator sitr=clogitems.iterator();
while(sitr.hasNext())
{
CLogItem clitem=(CLogItem) sitr.next();
str = str + "P: " + clitem.No + "\n";
str = str + "N: " + clitem.Name + "\n";
str = str + "--------------------------------------------\n";
}
tv1.setText(str);
}
private void getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int iname = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
while (cursor.moveToNext()) {
CLogItem clitem = new CLogItem();
clitem.No = cursor.getString(number);
clitem.Name = cursor.getString(iname);
clitem.lDate = Long.valueOf(cursor.getString(date));
clogitems.add(clitem);
}
cursor.close();
}
public static class CLogItem implements Comparable {
String No;
String Name;
long lDate;
public CLogItem(){
this.No = "";
this.Name = "";
this.lDate = 0;
}
#Override
public int compareTo(Object arg0) {
CLogItem l = (CLogItem)arg0;
int fnResult = this.No.compareTo(l.No);
if( fnResult == 0 ){
if (lDate > l.lDate) {
return -1;
}
else if (lDate < l.lDate) {
return 1;
}
else {
return 0;
}
}
return fnResult;
}
}
}
please help me to sort out this issue
thanks in advance
Finally i got a correct solution.
private void getCallDetails(Context context) {
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.NUMBER + "," + CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int iname = cursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
String curNo = "";
while (cursor.moveToNext()) {
String No = cursor.getString(number);
if( !No.equalsIgnoreCase(curNo) ){
CLogItem clitem = new CLogItem();
clitem.No = cursor.getString(number);
clitem.Name = cursor.getString(iname);
clitem.lDate = Long.valueOf(cursor.getString(date));
clogitems.add(clitem);
curNo = No;
}
}
cursor.close();
Collections.sort(clogitems);
}
Can't we achive this using GROUP BY while querying itself. Because in this case we should get all the values and then checking the possibilities. If I want to get the top 2 distinct items,still i need to get all the values.So,I think GROUP BY will help..

Categories

Resources