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 displayed the contacts in list view but when displaying it shows repeated phone numbers and names. so I tried to remove the duplicate names and numbers. It shows the single names but it displays the incorrect phone numbers of the user. How to solve that issue. This is my code :
public class Split extends AppCompatActivity implements AdapterView.OnItemClickListener {
public static String TAG = "amount";
ListView mainListView;
ProgressDialog pd;
public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
final static List<String> name1 = new ArrayList<>();
List<String> phno1 = new ArrayList<>();
List<Long> bal = new ArrayList<>();
List<Bitmap> img = new ArrayList<>();
private Splitadapter mCustomAdapter;
List<String> names = new ArrayList<String>();
List<String> phonenumbers = new ArrayList<String>();
private ArrayList<ContactModel> _Contacts = new ArrayList<ContactModel>();
Button select;
int amount=100;
float result;
String ph;
String phoneNumber;
EditText search;
private FirebaseAuth mAuth;
FirebaseUser firebaseUser;
FirebaseFirestore db = FirebaseFirestore.getInstance();
#SuppressLint("StaticFieldLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Split");
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.split);
mAuth = FirebaseAuth.getInstance();
search = findViewById(R.id.search_bar);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final List<String> phonenumber = new ArrayList<>();
System.out.print(phonenumber);
mainListView = findViewById(R.id.listview);
showContacts();
select = findViewById(R.id.button1);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user chan ged the Text
mCustomAdapter.getFilter().filter(cs.toString());
//
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
//ma.filter(text);
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
ArrayList checkedcontacts1 = new ArrayList();
ArrayList names = new ArrayList();
System.out.println(".............." + (mCustomAdapter.mCheckStates.size()));
System.out.println("name size is" + name1.size());
int a = mCustomAdapter.mCheckStates.size();
result = ((float) amount / a);
System.out.println("final1 amount is " + result);
long result1 = (long) result;
System.out.println("final amount is " + result1);
for (int k = 0; k <= a; k++) {
bal.add(result1);
}
System.out.println("balance" + bal);
System.out.println("selected contacts split amount" + result);
for (int i = 0; i < name1.size(); i++) // it displays selected contacts with amount
{
if (mCustomAdapter.mCheckStates.get(i)) {
checkedcontacts.append(phno1.get(i)).append("\t").append("\t").append("\t").append(result1);
checkedcontacts1.add((phno1.get(i)));
names.add((name1.get(i)));
checkedcontacts.append("\n");
System.out.println("checked contacts:" + "\t" + phno1.get(i) + "\t" + "amount" + "\t" + result1);
}
}
System.out.println("checked names" + names);
System.out.println(
"checkec contcts foggfgfgfgfgf" + checkedcontacts1
);
List<Object> list = new ArrayList<>();
for (Object i : checkedcontacts1) {
list.add(i);
}
System.out.println("checked contacts size is" + checkedcontacts1.size());
HashMap<String, HashMap<String, Object>> Invites = new HashMap<>();
for (int i = 0; i < checkedcontacts1.size(); i++) {
HashMap<String, Object> entry = new HashMap<>();
entry.put("PhoneNumber", list.get(i));
entry.put("Name", names.get(i));
System.out.println("entry is" + entry);
for (int j = i; j <= i; j++) {
System.out.println("phonenumber" + i + ":" + list.get(i));
System.out.println("amount" + j + ":" + bal.get(j));
//dataToSave.put("phonenumber" +i, list.get(i));
entry.put("Amount", bal.get(j));
}
Invites.put("Invite" + i, entry);
}
}
private void showContacts() // it is for to check the build versions of android . if build version is >23 or above it is set the permissions at the run time . if the build version is less than 23 the we give the permissions at manifest file .
{if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
}
else {
mCustomAdapter = new Splitadapter(Split.this,_Contacts);
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
mainListView.setAdapter(mCustomAdapter);
mainListView.setOnItemClickListener(this);
mainListView.setItemsCanFocus(false);
mainListView.setTextFilterEnabled(true);
getAllContacts(this.getContentResolver());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, // it is display the request access permission dilogue box to access the contacts of user.
#NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
}
}
}
private void getAllContacts(ContentResolver getcontentResolver) {
// it displays the contact phonenumber and name rom the phone book. and add to the list.
Cursor phones = getcontentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME ));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER ));
long contactId = Long.parseLong(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
if(!phonenumbers.contains(phoneNumber)) {
phonenumbers.add(phoneNumber);
}
if(!names.contains(name)) {
names.add(name);
}
}
Collections.sort(names);
for (int i = 0; i < names.size(); i++) {
ContactModel contacts = new ContactModel();
contacts.setName(names.get(i));
contacts.setPhonenum(phonenumbers.get(i));
_Contacts.add(contacts);
}
System.out.println("phonenumber size is" + phonenumbers.size());
System.out.println("name size is" + names.size());
phones.close();
}
}
And this is my adapter class :
public class Splitadapter extends BaseAdapter implements Filterable,CompoundButton.OnCheckedChangeListener
{
public SparseBooleanArray mCheckStates;
private ArrayList<ContactModel> _Contacts;
private Context mContext;
private LayoutInflater inflater;
private ValueFilter valueFilter;
private ArrayList<ContactModel> mStringFilterList;
List<Bitmap> img = new ArrayList<>();
public Splitadapter(Context context, ArrayList<ContactModel> _Contacts) {
super();
mContext = context;
this._Contacts = _Contacts;
mStringFilterList = _Contacts;
mCheckStates = new SparseBooleanArray(_Contacts.size());
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getFilter();
}//End of CustomAdapter constructor
#Override
public int getCount() {
return _Contacts.size();
}
#Override
public Object getItem(int position) {
return _Contacts.get(position).getName();
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
TextView textviewName;
TextView textviewNumber;
CheckBox checkbox;
ImageView image;
int id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
//
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.row, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.name);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.mobile);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
holder.image = convertView.findViewById(R.id.image);
convertView.setTag(holder);
}//End of if condition
else {
holder = (ViewHolder) convertView.getTag();
}//End of else
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
holder.textviewName.setText(_Contacts.get(position).getName());
holder.textviewNumber.setText(_Contacts.get(position).getPhonenum());
holder.checkbox.setTag(position);
holder.checkbox.setChecked(mCheckStates.get(position, false));
holder.checkbox.setOnCheckedChangeListener(this);
holder.image.setImageBitmap(_Contacts.get(position).getImage());
//holder.id = position;
return convertView;
// }//End of getView method
}
boolean isChecked(int position) {// it returns the checked contacts
return mCheckStates.get(position, false);
}
void setChecked(int position, boolean isChecked) { //set checkbox postions if it sis checked
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), true);
} else {
mCheckStates.delete((Integer) buttonView.getTag());
}
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<ContactModel> filterList = new ArrayList<ContactModel>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ContactModel contacts = new ContactModel();
contacts.setName(mStringFilterList.get(i).getName());
contacts.setPhonenum(mStringFilterList.get(i).getPhonenum());
filterList.add(contacts);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
_Contacts = (ArrayList<ContactModel>) results.values;
notifyDataSetChanged();
}
}
} //End of CustomAdapter instance inne
And this my class :
public class ContactModel {
String phonenum;
String cname;
Bitmap b;
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
System.out.println("se ph num"+phonenum);
}
public String getName() {
return cname;
}
public void setName(String name) {
this.cname = name;
}
public void setImage(Bitmap image) {
this.b = image;
}
public Bitmap getImage() {
return b;
}
}
How to solve that issue?
Use below link.I hope this will solve your problem.
Android get phone contacts and remove duplicates
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
String lastnumber = "0";
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String number = null;
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]
{ id }, null);
while (pCur.moveToNext())
{
number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("lastnumber ", lastnumber);
Log.e("number", number);
if (number.equals(lastnumber))
{
}
else
{
lastnumber = number;
Log.e("lastnumber ", lastnumber);
int type = pCur.getInt(pCur.getColumnIndex(Phone.TYPE));
switch (type)
{
case Phone.TYPE_HOME:
Log.e("Not Inserted", "Not inserted");
break;
case Phone.TYPE_MOBILE:
databaseHandler.insertContact(id, name, lastnumber, 0);
break;
case Phone.TYPE_WORK:
Log.e("Not Inserted", "Not inserted");
break;
}
}
}
pCur.close();
}
}
}
Several wrong things here:
You have independent conditions for uniqueness of names vs phone numbers. It should be one to keep it all consistent.
Even if, somehow, the matching is preserved from the first point, you will mess everything up by sorting only the names list. The names will be ordered alphabetically but the phones will remain as they were.
You can use HashSet instead of arrayList and you must override equal and hashset method of your ContactModel class like this :
#Override
public boolean equals(Object o) {
if(o == null)
return false;
if (o == this) {
return true;
}
if(o instanceof ContactModel) {
return this.phoneNum.equals(o.phoneNum); //Or check other Parameters
}
}
#Override
public int hashCode() {
return this.phoneNum!= null ? this.phoneNum.hashCode() : 0;
}
if you do this , it will not add duplicate automatically contact in your list.
I can not do function "setOnItemLongClickListener" in my application. Help me please. How I can do it?
I have a pager and pageradapter
pager = (ViewPager) findViewById(R.id.pager);
Log.d(Tag,"pager 2");
pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
Log.d(Tag,"pager 3");
pager.setOffscreenPageLimit(0);
pager.setAdapter(pagerAdapter);
Log.d(Tag,"pager 4");
setListTitle(0);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
Log.d(Tag,"ПЕРЕЛИСТНУЛИ СТРАНИЦУ");
//pager.invalidate();
setNameList(position);
//****
}
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
This is MyFragmentPagerAdapter
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d(Tag, "getItem");
return PageFragment.newInstance(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
MySqlCursorAdapter.prevDate = null;
Log.d(Tag, "getCount.. получаем количество страниц"+PAGE_COUNT);
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
Log.d(Tag, "getPageTitle");
return "Title " + position;
}
// Код из FragmentPagerAdapter.java
private String makeFragmentName(int viewId, long id) {
Log.d(Tag, "makeFragmentName");
return "android:switcher:" + viewId + ":" + id;
}
}
PageFragment.java
public class PageFragment extends Fragment {
static PageFragment newInstance(int page) {
Log.d(Tag1, "page="+page);
test=page;
PageFragment pageFragment = new PageFragment();
Bundle arguments = new Bundle();
arguments.putInt(ARGUMENT_PAGE_NUMBER, page);
pageFragment.setArguments(arguments);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Tag1, "FRAGMENT onCreate0");
pageNumber = getArguments().getInt(ARGUMENT_PAGE_NUMBER);
Log.d(Tag1, "FRAGMENT onCreate!!!!!!!!");
// dlg1 = new dialog_edit();
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case M_EDIT1:
dlg1.show(getFragmentManager(), "dlg1");
break;
case M_EDIT2:
Toast.makeText(getActivity(), "Изменение во втором списке", Toast.LENGTH_SHORT).show();
break;
case M_DELETE:
//dlg2.show(getFragmentManager(), "dlg2");
break;
case M_ADD:
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Tag, "onCreateView1");
View view = inflater.inflate(R.layout.activity_page_fragment, null);
lvMain_today = (ListView) view.findViewById(R.id.list);
//tv = (TextView) view.findViewById(R.id.tv);
Log.d(Tag, "onCreateView2");
Log.d(Tag, "onCreateView4 id_for_listtsk="+ListTsk.id_for_listtsk);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(getActivity());
// final SQLiteDatabase db = dbHelper.getWritableDatabase();
OnCreateContextMenuListener occm1 = new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
AdapterContextMenuInfo aMenuInfo = (AdapterContextMenuInfo) menuInfo;
itemselected = aMenuInfo.position;
id_itemselected = (int) aMenuInfo.id;
menu.add(Menu.NONE, M_EDIT1, Menu.NONE, "Изменить1");
menu.add(Menu.NONE, M_DELETE, Menu.NONE, "Удалить1");
menu.add(Menu.NONE, M_ADD, Menu.NONE, Integer.toString(id_itemselected));
}
};
Log.d(Tag, "onCreateView3");
OnCreateContextMenuListener occm2 = new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
AdapterContextMenuInfo aMenuInfo = (AdapterContextMenuInfo) menuInfo;
itemselected = aMenuInfo.position;
id_itemselected = (int) aMenuInfo.id;
menu.add(Menu.NONE, M_EDIT2, Menu.NONE, "Изменить2");
menu.add(Menu.NONE, M_DELETE, Menu.NONE, "Удалить2");
menu.add(Menu.NONE, M_ADD, Menu.NONE, Integer.toString(id_itemselected));
}
};
//*****************получаем аккаунт**
SharedPreferences mSettings;
mSettings = getActivity().getSharedPreferences(MainActivity.APP_PREFERENCES, Context.MODE_PRIVATE);
if(mSettings.contains(MainActivity.ACCAUNT_NAME)) {
accauntName=mSettings.getString(MainActivity.ACCAUNT_NAME, "");
Log.d(Tag, "!!!accauntName = _"+accauntName);
}
//пробуем*****
// Log.d(Tag, "ПРОВЕРЯЕМ ЛИСТЫ, ЛИСТ = _"+taskList.getId());
//проверяем если данные в базе
DBHelper dbHelper_AL = new DBHelper(getActivity());
final SQLiteDatabase db1 = dbHelper_AL.getWritableDatabase();
columns = new String[] { COLUMNLIST_GOOGLEID, COLUMNLIST_ID, COLUMNLIST_TITLE ,COLUMNLIST_ACCAUNT };
selection = "tasklistAccaunt = ?";
selectionArgs = new String[] {accauntName};
// orderBy = "time_up";
try {
c_TL = db1.query("listTable", columns, selection, selectionArgs, null, null, null);
Log.d(Tag, "смотрим курсор с параметром"+String.valueOf(pageNumber)+" test= "+test+" pagerPos="+MainActivity.pagerPos +" pagecount = "+MainActivity.PAGE_COUNT);
//тут делаем вилку для листа "все" и остальных
if (pageNumber ==(MainActivity.PAGE_COUNT - 1)) {
if (allTasks()) {
return view;
}
}
String[] arr_date1 = Pager.logCursor(c_TL);
//идем по курсору
if (c_TL.moveToFirst()) {
c_TL.moveToPosition(pageNumber);
Log.d(Tag, "получаем значение из курсора1");
nameGoogleId = c_TL.getColumnIndex(COLUMNLIST_GOOGLEID);
// titleGoogleId = c_TL.getColumnIndex(COLUMNLIST_TITLE);
Log.d(Tag, "получаем значение из курсора2 "+nameGoogleId);
Log.d(Tag, "получаем значение из курсора3");
listGoogleId = c_TL.getString(nameGoogleId);
// listTitle1 = (TextView)getActivity().findViewById(R.id.listTitle1); //это тут не работает...
// listTitle1.setText(c_TL.getString(titleGoogleId));
// Log.d(Tag, "listGoogleId="+listGoogleId);
// do {
// Log.d(Tag, "получаем значение из курсора3");
// listGoogleId = c_TL.getString(nameGoogleId);
// Log.d(Tag, "listGoogleId="+listGoogleId);
// }while (c_TL.moveToNext());
}
} catch (Exception e) {
// TODO: handle exception
}
columns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_ID, DBHelper.COLUMN_ACCAUNT, DBHelper.COLUMN_TASK, DBHelper.COLUMNTASKLIST_ID, DBHelper.COLUMN_TIME, DBHelper.COLUMN_DATA, DBHelper.COLUMN_STATUS};
if (listGoogleId != null) {
selection = "tasklist = ? and data_id = ? and accaunt= ?";
if (ListTsk.id_for_listtsk==null) {
selectionArgs = new String[] {listGoogleId, id_for_listtsk_today, accauntName};
} else {
selectionArgs = new String[] {listGoogleId, ListTsk.id_for_listtsk, accauntName};
}
} else {
selection = "data_id = ? and accaunt= ?";
if (ListTsk.id_for_listtsk==null) {
selectionArgs = new String[] {id_for_listtsk_today, accauntName};
} else {
selectionArgs = new String[] {ListTsk.id_for_listtsk, accauntName};
}
}
orderBy = "time_up";
try {
c = db1.query("mytable", columns, selection, selectionArgs, null, null, orderBy);
// String[] arr_date = MainActivity.logCursor(c);
Log.d(Tag, "получаем курсор напрямую..listGoogleTitle = "+listGoogleId+"data_id="+id_for_listtsk_today+"accaunt="+accauntName);
// String[] arr_date = logCursor(c);
//**************************
Log.d(Tag, "onCreateView6");
getActivity().startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.textData1 };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
// Log.d(Tag, "трассировка" );
adapter = new MySqlCursorAdapter(
getActivity(), R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
Log.d(Tag, "onCreateView7");
lvMain_today.setAdapter(adapter);
Log.d(Tag, "onCreateView8");
registerForContextMenu(lvMain_today);
Log.d(Tag, "onCreateView9");
lvMain_today.setOnCreateContextMenuListener(occm1);
lvMain_today.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
Log.d(Tag, "YYYYYYY");
return false;
}
});
if (c.getCount()==0) {
Log.d(Tag, "c.getCount()==0");
c.close();
db1.close();
// db.close();
}
} catch (Exception e) {
// TODO: handle exception
}
Log.d(Tag, "onCreateView10");
return view;
}
public static String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
// Log.d(Tag,"мы в курсоре");
if (c!=null) {
Log.d(Tag,"logcursor курсор не нулевой");
if (c.moveToFirst()) {
Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
else {
Log.d(Tag,"logcursor курсор нулевой");
}
return arr_date;
}
private Boolean allTasks() {
DBHelper dbHelper = new DBHelper(getActivity());
final SQLiteDatabase db1 = dbHelper.getWritableDatabase();
columns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_ID,DBHelper.COLUMN_DATA_INTEGER, DBHelper.COLUMN_ACCAUNT, DBHelper.COLUMN_TASK, DBHelper.COLUMNTASKLIST_ID, DBHelper.COLUMN_TIME, DBHelper.COLUMN_DATA, DBHelper.COLUMN_STATUS};
selection = "accaunt= ?";
selectionArgs = new String[] {accauntName};
orderBy = "data_id_integer DESC, time_up";
try {
c = db1.query("mytable", columns, selection, selectionArgs, null, null, orderBy);
//**************************
Log.d(Tag, "onCreateView6");
getActivity().startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.textData1 };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
// Log.d(Tag, "трассировка" );
adapter = new MySqlCursorAdapter(
getActivity(), R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
Log.d(Tag, "onCreateView7");
lvMain_today.setAdapter(adapter);
Log.d(Tag, "onCreateView8");
registerForContextMenu(lvMain_today);
Log.d(Tag, "onCreateView9");
// lvMain_today.setOnCreateContextMenuListener(occm1);
if (c.getCount()==0) {
Log.d(Tag, "c.getCount()==0");
c.close();
db1.close();
// db.close();
}
Boolean end = true;
return end;
} catch (Exception e) {
Boolean end = false;
return end;
}
}
And MySQLCursorAdapter
public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener, OnLongClickListener {
public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {
super(context, layout, c, from, to);
Log.d(Tag, "создаем mysqlcursoradapter" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
mSelectedItemsIds = new SparseBooleanArray();
}
public View getView(int pos, View inView, ViewGroup parent) {
//-------------------------------------------
final int viewType = getItemViewType(pos);
prevDate = null;
if (currentCursor.getPosition() > 0 && currentCursor.moveToPrevious()) {
prevDate = currentCursor.getString(currentCursor.getColumnIndex(DBHelper.COLUMN_DATA));
currentCursor.moveToNext();
}
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}
this.currentCursor.moveToPosition(pos);
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_ID))));
//Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS)) != null
&& String.valueOf(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS))).equals(needsAction)) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);
DateTitle = (TextView) v.findViewById(R.id.DateTitle);
DateTitle.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_DATA)));
//----------------------
if (prevDate == null || !prevDate.equals(thisDate)) {
DateTitle.setVisibility(View.VISIBLE);
} else {
DateTitle.setVisibility(View.GONE);
}
//------------------------
txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle1 = (TextView) v.findViewById(R.id.textData1);
txtTitle.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_TIME))+" , "+this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_NAME)));
txtTitle1.setText(this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_TASK)));
llText = (LinearLayout) v.findViewById(R.id.llText);
llText.setTag(Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_ID))));
llText.setOnLongClickListener(this);
llText.setOnClickListener(this);
if (cBox.isChecked())
{
Log.d(Tag, " pos444=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else
{
Log.d(Tag, "!pos5555=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle1.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
// txtTitle1.setSelected(true);
}
return (v);
}
private int getItemViewType(Cursor cursor) {
thisDate = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DATA));
String thistitle = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME));
Log.d(Tag, "type===="+thisDate+thistitle);
if (thisDate.equals("1")) {
return 0;
} else {
return 1;
}
}
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
this.dbHelper.clearSelections();
this.currentCursor.requery();
}
#Override
public void onClick(View v) {
Log.d(Tag, "onClick(View v) в адаптере"+ v.getId());
switch (v.getId()) {
case R.id.llText:
Log.d(Tag, "переход в ListTsk activity");
LinearLayout llText = (LinearLayout) v;
Integer _idTask = (Integer) llText.getTag();
Intent intent_add = new Intent(context, AddLineBD.class);
Log.d(Tag, "_idTask="+_idTask);
intent_add.putExtra("idTask", _idTask.toString());
// intent_add.putExtra("idTitleList", super);
context.startActivity(intent_add);
break;
case R.id.bcheck:
if(dbHelper.dbSqlite==null) {
Log.d(Tag, "00000000000");
SQLiteDatabase db = dbHelper.getWritableDatabase();
//Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
//Integer _id = 4;
//Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
ContentValues valuesListTable = new ContentValues();
values.put("status", cBox.isChecked() ? "completed" : "needsAction");
Calendar calNow = Calendar.getInstance();
calNow.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
Long time_for_date1 = calNow.getTimeInMillis();//-(Integer.valueOf(ValueTZ)*3600000);
Log.d(CopyOfAsyncLoadTasks.Tag3, "ValueTZ = "+ValueTZ);
values.put("data_id_update",time_for_date1);
valuesListTable.put("tasklistUpdate",time_for_date1);
try {
db.update("mytable", values, "_id = ?", new String[] { Integer.toString(_id) });
db.update("listtable", valuesListTable, "tasklistTitle = ?", new String[] { MainActivity.titleList});
// String pp = MainActivity.titleList;
Log.d(Tag, "checkbox все получилось");
} catch (SQLException sqle) {
Log.d(Tag, "checkbox неудача");
throw sqle;
}
}
//получаем etag общий листа
try {
SharedPreferences mSettingsList;
mSettingsList = context.getSharedPreferences(MainActivity.LIST_ETAG, Context.MODE_PRIVATE);
Editor editor = mSettingsList.edit();
editor.putString(MainActivity.ETAG, "1");
editor.commit();
} catch (Exception e) {
// TODO: handle exception
// preferences= intent.getStringExtra("preferences");
Log.d(Tag, "ни фига не нашли etag общий");//"preferences in intenrservice = "+preferences);
}
try {
MainActivity.update();
} catch (Exception e) {
// TODO: handle exception
}
try {
ListTsk.update();
} catch (Exception e) {
// TODO: handle exception
}
break;
}
}
#Override
public boolean onLongClick(View v) {
LinearLayout llText = (LinearLayout) v;
Integer ask = (Integer) llText.getTag();
Log.d(Tag, "длинное!"+ask+"__");
toggleSelection(ask);
return true;
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public void toggleSelection(int tag) {
selectView(tag, !mSelectedItemsIds.get(tag));
}
OnLongClick operates in the function of MySqlCursorAdapter. But I need setOnItemLongClickListener. I try do this function in MainActivity
ListView lvTareas = (ListView) findViewById (R.id.list);
lvTareas.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
Log.d(Tag,"pos"+" "+pos);
return true;
}
});
But it not work. Help me please? what I do not correctly?
It happens due to focusability of CheckBox in my_list_item layout.
Add below line to root layout of your ListView's Item layout(my_list_item).
android:descendantFocusability="blocksDescendants"
In my application I use SimpleCursorAdapter. If CheckBox.isChecked() then text should be strikethrough. But why then the first line is always crossed out, even if the CheckBox is not checked
public class MainActivity extends Activity {
// Button btnCalendar;
//*******************************************8
String[] names = {"Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
"Костя", "Игорь", "Анна", "Денис", "Андрей"};
//Button buttonAddTask;
final String Tag="States";
final String Ten = "Ten";
TextView txtDataTaskToday;
String id_for_listtsk_today;
ListView lvMain_today;
String[] arr_date;
SharedPreferences sPref;
static Cursor c;
private ListView listView = null;
SQLiteDatabase db;
//public static String id_for_listtsk_today;
// static SQLiteDatabase db;
MySqlCursorAdapter adapter = null;
//***********************************************8
#Override
protected void onCreate(Bundle savedInstanceState) {
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btnCalendar = (Button) findViewById(R.id.btnActTwo);
// btnCalendar.setOnClickListener(this);
//*********************************************
// переменные для query
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
//*********работа с БД****************
// создаем объект для данных
txtDataTaskToday = (TextView) findViewById(R.id.txtDataTaskToday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
//final String b = id_for_listtsk_today;
txtDataTaskToday.setText("Today: "+id_for_listtsk_today.toString());
// txtDataTaskToday.setPaintFlags(txtDataTaskToday.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Log.d(Tag, "id_for_listtsk_today ="+id_for_listtsk_today );
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(this);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
columns = new String[] {"name"};
selection = "data_id = ?";
selectionArgs = new String[] {id_for_listtsk_today};
//c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
try {
c=dbHelper.getCursor(id_for_listtsk_today);
} catch (SQLException sqle) {
Log.d(Tag, "неудача");
throw sqle;
}
String[] arr_date = logCursor(c);
//*********работа с БД****************
lvMain_today = (ListView) findViewById(R.id.list);
// lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//this.listView=getl
//listView = MainActivity.this.getlgetListView();
lvMain_today.setItemsCanFocus(false);
lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_multiple_choice, arr_date);// R.layout.item, my_list_item
startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.txtDataTaskToday };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
Log.d(Tag, "трассировка" );
MainActivity.this.adapter = new MySqlCursorAdapter(
this, R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
//
lvMain_today.setAdapter(MainActivity.this.adapter);
// setListAdapter(MainActivity.this.adapter);
names = arr_date;
//c.close();
//db.close();
//dbHelper.close();
lvMain_today.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView txtView = (TextView) findViewById(R.id.txtTitle);
txtView.setText("blah blah blah");
Log.d(Tag, "position="+position);
// ((TextView) txtDataTaskToday).setTextColor(android.R.color.white);
SparseBooleanArray chosen = ((ListView) parent).getCheckedItemPositions();
for (int i = 0; i < chosen.size(); i++) {
int key = chosen.keyAt(i);
if (chosen.get(key))
Log.d(Tag, "выделены ====="+names[key]);
Log.d(Tag, "itemClick: position = " + position + ", id = "
+ id);}
//****************nen пробная фигня**************
// String[] columns = null;
// String selection = null;
// String[] selectionArgs = null;
// String groupBy = null;
// String having = null;
// String orderBy = null;
// columns = new String[] {"name"};
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};//id_for_listtsk_today
// Cursor c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
// String[] arr = logCursor(c);
//**************************************************
// String s=test();
}
});
// lvMain_today.setOnItemSelectedListener(new OnItemSelectedListener() {
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// Log.d(Tag, "Было выделение позиции меню!!!!position = " + position + ", id = "
// + id);
// }
//
// public void onNothingSelected(AdapterView<?> parent) {
// Log.d(Tag, "itemSelect: nothing");
// }
// });
}
private String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
Log.d(Tag,"мы в курсоре");
if (c!=null) {
if (c.moveToFirst()) {
// Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
// Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
return arr_date;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "календарь");
menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Уйти");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
// Выведем в TextView информацию о нажатом пункте меню
// txtDataTaskToday.setText("Item Menu");
// txtDataTaskToday.setText(item.getGroupId());
txtDataTaskToday.setText("\r\n itemId: " + String.valueOf(item.getItemId()));
// txtDataTaskToday.setText("\r\n order: " + String.valueOf(item.getOrder()));
// txtDataTaskToday.setText("\r\n title: " + item.getTitle());
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, ToDoCalendarActivity.class);
startActivity(intent);
onDestroy();
break;
case 2:
SparseBooleanArray sbArray = lvMain_today.getCheckedItemPositions();
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key))
Log.d(Tag, "выделены "+names[key]);
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(Ten, "1");
ed.commit();
Log.d(Tag, "ставим константу для скрытия");
}
break;
case 3:
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(Ten, "");
Log.d(Tag, "ten= "+ savedText);
onDestroy();
//finish();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
try {
MainActivity.this.onRestart();
} catch (Exception e) {
Log.d(Tag, "не получилось рестартануть");
}
Log.d(Tag, "MainActivity: onStart()");
}
#Override
protected void onResume() {
super.onResume();
Log.d(Tag, "MainActivity: onResume()");
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
// ToDoCalendarActivity.this.finish();
Log.d(Tag, "MainActivity: onDestroy()");
finish();
// db.close();
}
#Override
protected void onPause() {
super.onPause();
//this.dbHelper.close();
Log.d(Tag, "MainActivity: onPause()");
}
#Override
protected void onStop() {
super.onStop();
Log.d(Tag, "MainActivity: onStop()");
}
#Override
protected void onRestart() {
super.onRestart();
// new SelectDataTask().execute();
Log.d(Tag, "MainActivity: onRestart()");
}
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// switch (v.getId()) {
// case R.id.btnActTwo:
//
// Intent intent = new Intent(this, ToDoCalendarActivity.class);
// startActivity(intent);
// break;
// }
// }
}
MySqlCursorAdapter
public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener {
final String Tag="States";
private Context context;
private DBHelper dbHelper;
private Cursor currentCursor;
TextView txtTitle;
TextView txtTitle1;
public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {
super(context, layout, c, from, to);
Log.d(Tag, "трассировка1" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
}
public View getView(int pos, View inView, ViewGroup parent) {
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}
this.currentCursor.moveToPosition(pos);
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(Integer.parseInt(this.currentCursor.getString(this.currentCursor.getColumnIndex(DBHelper.COLUMN_ID))));
Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS)) != null
&& Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS))) != 0) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);
txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle1 = (TextView) v.findViewById(R.id.txtDataTaskToday);
txtTitle.setText(this.currentCursor.getString(this.currentCursor.getColumnIndex(DBHelper.COLUMN_NAME)));
txtTitle1.setText(this.currentCursor.getString(this.currentCursor.getColumnIndex(DBHelper.COLUMN_TASK)));
if (cBox.isChecked()) {
Log.d(Tag, " pos=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
return (v);
}
public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
this.dbHelper.clearSelections();
this.currentCursor.requery();
}
#Override
public void onClick(View v) {
if(dbHelper.dbSqlite==null) {
//Log.d(Tag, "00000000000");
SQLiteDatabase db = dbHelper.getWritableDatabase();
//Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
//Integer _id = 4;
//Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
values.put(" status", cBox.isChecked() ? 1 : 0);
try {
db.update("mytable", values, "_id = ?", new String[] { Integer.toString(_id) });
} catch (SQLException sqle) {
// Log.d(Tag, "неудача");
throw sqle;
}
}
txtTitle.setTextColor(Color.BLUE);
}
}
}
I put a flag in textView in functoin getView()
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Why is the first line is always crossed out?
setPaintFlags changes are persistent, so I suspect that your function gets called twice, the first time cBox.setChecked(true) is executed, but the second time cBox.setChecked(false) is executed, so the flags are not reset. Thus:
if (cBox.isChecked())
{
Log.d(Tag, " pos=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else
{
Log.d(Tag, "!pos=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}