Focusable EditText in ListView and Swipe to Dismiss - android

I have a MainActivity, CustomListAdapter, customlistItem.xml, mainlayout.xml, SwipeDismissListViewTouchListener.java, SwipeDismissTouchListener.java.
I'm using a this code(Swipe to Dismiss).
I want to make a focusable(editable) EditText in ListView & onItemClickListener ListView & Swipe to Dismiss ListView.
My Code works well focusable(editable) EditText in ListView & onItemClickListener ListView.But didn't work the Swipe to Dismiss ListView.
If I make a new Item, then Swipe to Dismiss ListView works well, but Didn't work focusable(editable) EditText in ListView & onItemClickListener ListView.
I think there is a problem with TouchListener code.(dupplicated)
What am I Supposed to do?
MainActivity.java
...
footer.setOnClickListener(new View.onclickListener()
{
#Override
public void onClick(View v)
{
int id=0;
String list = "new";
String contents = "";
myHelper = new myDBHelper(myListActivity.this);
myadapter = new subMyListAdapter(myListActivity.this, R.layout.custom_edit_item, arrItem,myHelper);
mainList.setItemsCanFocus(false);
mainList.setAdapter(myadapter);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(mainList,
new SwipeDismissListViewTouchListener.DismissCallbacks()
{
#Override
public boolean canDismiss(int position)
{
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions)
{
for (int position : reverseSortedPositions)
{
myadapter.remove(position);
}
myadapter.notifyDataSetChanged();
}
});
mainList.setOnTouchListener(touchListener);
mainList.setOnScrollListener(touchListener.makeScrollListener());
sqlDB = myHelper.getReadableDatabase();
Cursor cursor;
cursor = sqlDB.rawQuery("SELECT * FROM clearTBL;", null);
sqlDB.execSQL("INSERT INTO clearTBL(list, contents) VALUES ('"
+ list + "' , '" + "');");
arrItem.clear();
while (cursor.moveToNext())
{
id = cursor.getInt(0);
list = cursor.getString(1);
contents = cursor.getString(2);
subMyItem item = new subMyItem(id, list, contents);
arrItem.add(item);
}
myadapter.notifyDataSetChanged();
}
});
mainList.addFooterView(footerViewLayout, null, true);
mainList.setAdapter(myadapter);
mainList.setDivider(null);
SwipeDismissListViewTouchListener touchListener =
new SwipeDismissListViewTouchListener(mainList,
new SwipeDismissListViewTouchListener.DismissCallbacks()
{
#Override
public boolean canDismiss(int position)
{
return true;
}
#Override
public void onDismiss(ListView listView, int[] reverseSortedPositions)
{
for (int position : reverseSortedPositions)
{
myadapter.remove(position);
}
myadapter.notifyDataSetChanged();
}
});
subMyListAdapter.java
...
holder.tvItem.setOnTouchListener(test);
conv.setOnTouchListener(test);
...
View.OnTouchListener test= new View.OnTouchListener()
{
#Override
public boolean onTouch(View view, MotionEvent event)
{
if (view instanceof EditText)
{
tvItem = (EditText) view;
tvItem.setFocusable(true);
tvItem.setFocusableInTouchMode(true);
try
{
openPositon = Integer.parseInt(tvItem.getTag().toString());
}
catch(Exception e)
{}
if(sPosition!=null)
{
int pos = Integer.parseInt(sPosition);
myHelper = new myDBHelper(context);
SQLiteDatabase sqlDB = myHelper.getWritableDatabase();
subMyItem user = arraySrc.get(pos);
int a = user.id;
String update = "UPDATE clearTBL SET list='" + tvItem.getText().toString()+ "' WHERE id=" + a + ";";
try
{
sqlDB.execSQL(update);
}
catch (Exception e)
{
e.printStackTrace();
}
sqlDB.close();
myListActivity.arrItem.get(pos).list = tvItem.toString();
}
} else
{
hideSoftKeyboard();
view.requestFocus();
UserHolder holder = (UserHolder) view.getTag();
holder.tvItem.clearFocus();
holder.tvItem.setMovementMethod(null);
holder.tvItem.setFocusable(false);
holder.tvItem.setFocusableInTouchMode(false);
try
{
sPosition = tvItem.getTag().toString();
}
catch
(Exception e)
{}
if(sPosition!=null)
{
int pos = Integer.parseInt(sPosition);
myHelper = new myDBHelper(context);
SQLiteDatabase sqlDB = myHelper.getWritableDatabase();
subMyItem user = arraySrc.get(pos);
int a = user.id;
String update = "UPDATE clearTBL SET list='" + tvItem.getText().toString()+ "' WHERE id=" + a + ";";
try
{
sqlDB.execSQL(update);
}
catch (Exception e)
{
e.printStackTrace();
}
sqlDB.close();
myListActivity.arrItem.get(pos).list = tvItem.toString();
}
}
return false;
}
};
Manifest
...
android:windowSoftInputMode="adjustPan"
/*android:windowSoftInputMode="adjustResize" didn't works for Focusable EditText*/
...

Related

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

transfer checked items in list-view to another list-view on button click in android

I have a listview with data using customAdapter.class now what i want is that to transfer checked items in listview to secondActivity on button click...
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<Model> mylist = new ArrayList<Model>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
// listView = new ArrayList<Model>();
mylist.add(String.valueOf(adapter.getItem(position)));
}
String[] output = new String[mylist.size()];
for (int i = 0; i < mylist.size(); i++) {
output[i] = (mylist.get(i));
}
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", output);
// b.putStringArrayList("SelectedItems: ",list);
// b.putString("selectedItems", String.valueOf(output));
intent.putExtras(b);
startActivity(intent);*/
}
});
and this is the second activity where i am getting that data in another listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Bundle b = getIntent().getExtras();
String[] result = b.getStringArray("selectedItems");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
lv.setAdapter(adapter);
}
The method you followed to send custom list to another activity will not work. In order to transfer your custom list between activities you need to create Parcelable List and send it through intent.
Android Intents does not support custom list.
Custom list can be passed in two ways, Serialization and Parcelable.
But Parcelable is more Efficient and Simple to implement.
Refer this link to send custom list between activities through Parcelable
This link will give you much better idea to implement Parcelable.
Updated Code: Change your Model Code like below.
public class Model implements Parcelable{
private String name;
private int selected;
public Model(String name){
this.name = name;
selected = 0;
}
public String getName(){
return name;
}
public int isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
/**
* Storing the Student data to Parcel object
**/
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(selected);
}
private Model (Parcel in){
this.name = in.readString();
this.selected = in.readInt();
}
public static final Parcelable.Creator<Model> CREATOR = new Parcelable.Creator<Model>() {
#Override
public Student createFromParcel(Parcel source) {
return new Student(source);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
}
Then in the MainActivity do this..
Intent next = new Intent(MainActivity , ResultActivity.class);
next.putParcelableArrayListExtra("model_data", (ArrayList<? extends Parcelable>) selectedItems);
startActivity(next);
In the ResultActivity do this.
ArrayList<Model> his = getIntent().getParcelableArrayListExtra("model_data");
Try the above code..
Good Luck..!!
i solve by saving checked items from listview to sqlite on button click. another button to open new activity and call selected items sqlite this way...
oncheckchange add and remove items in an arraylist and call this in onbutton click like this way...
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view = null;
Support support = (Support) this.getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.view_items, null);
view = new ViewHolder();
view.tvInfo = (TextView) convertView.findViewById(R.id.tvInfo);
view.cb = (CheckBox) convertView.findViewById(R.id.cb);
convertView.setTag(view);
view.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cb = (CheckBox) buttonView;
Support support = (Support) cb.getTag();
support.setSelected(cb.isChecked());
if (isChecked){
selList.add(support.status);
selID.add(support.id);
selType.add(support.type);
// Toast.makeText(CustomAdapter.this, "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}else {
selList.remove(support.status);
selID.remove(support.id);
selType.remove(support.type);
}
}
});
}else{
view = (ViewHolder) convertView.getTag();
view.cb = view.getCb();
view.tvInfo = view.getTvInfo();
}
view.cb.setTag(support);
support = list.get(position);
String id = support.getId();
String status = support.getStatus();
String type = support.getType();
view.cb.setChecked(support.isSelected());
// view.tvInfo.setText(id + "," + status + "," + type);
view.tvInfo.setText(status);
return convertView;
}
this is button coding to add to db
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.addSelected(adapter.selList, adapter.selID, adapter.selType);
and this is how to insert to sqlite..
public void addSelected(ArrayList<String> selList, ArrayList<String> selID, ArrayList<String> selType) {
int size = selID.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
// cv.put(KEY_ID, selID.get(i).toString());
cv.put(KEY_ID, selID.get(i));
cv.put(KEY_STATUS, selList.get(i));
cv.put(KEY_TYPE, selType.get(i));
Log.d("Added ",""+ cv);
db.insertOrThrow(TABLE_SELECTED, null, cv);
}
db.close();
}catch (Exception e){
Log.e("Problem", e + " ");
}
}
and get back from db like this
public ArrayList<String> getSelected() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> result = null;
try{
result = new ArrayList<String>();
// String query = "SELECT * FROM " + TABLE_SELECTED;
String query = "SELECT " + KEY_ID + " FROM " + TABLE_SELECTED;
Cursor c = db.rawQuery(query, null);
if (!c.isLast()){
if (c.moveToFirst()){
do{
String sel_name = c.getString(c.getColumnIndex("_id"));
result.add(sel_name);
Log.d("Added ", sel_name);
}while (c.moveToNext());
}
}
c.close();
db.close();
}catch (Exception e){
Log.e("Nothing is to show", e + " ");
}
return result;
}

Display Results in ListView from Database

I am trying to display result from Database in a listView which is clickable On long click ,items can be deleted and on click it go to another activity. So I create an activity called editdeletedoctor
public class editdeletedoctor extends Activity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = TableData.TableInfo.TABLE_DOCTOR;
private SQLiteDatabase newDB;
private ArrayList<doctorClass> doctor_List = new ArrayList<doctorClass>();
public static String MODEL_TO_EDIT = "MODEL_TO_EDIT";
public ListView list;
public ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
init();
openAndQueryDatabase();
displayResultList();
}
private void init() {
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(editdeletedoctor.this,
registerdoctor.class);
intent.putExtra("theText", doctor_List.get(position).getUsername());
intent.putExtra(editdeletedoctor.MODEL_TO_EDIT,doctor_List.get(position));
editdeletedoctor.this.finish();
startActivity(intent);
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
Builder dialog = new AlertDialog.Builder(editdeletedoctor.this);
dialog.setTitle("Are you sure you want to delete This doctor?");
dialog.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
doctorClass doctor = doctor_List.get(position);
doctor_List.remove(position);
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
HashMap<String, String> conditionKV = new HashMap<String, String>();
conditionKV.put(TableData.TableInfo.DOCTOR_ID, doctor.getId() + "");
db.deleteDoctor(conditionKV);
results.remove(position);
adapter.notifyDataSetChanged();
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
dialog.dismiss();
}
});
dialog.setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
return false;
}
});
}
private void displayResultList() {
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
DatabaseOperations db = new DatabaseOperations(getApplicationContext());
try {
db.open();
doctor_List = db.getDoctor(null);
for (doctorClass inc : doctor_List) {
if(inc.getId()==TableData.TableInfo.userID)
results.add("Name: " + inc.getUsername() + " Phone:"
+ inc.getPhone() + ",Address: "
+ inc.getAddress());
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
}
}
And in the DatabaseOperations.java class :
public DatabaseOperations open() throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public ArrayList<doctorClass> getDoctor(HashMap<String, String> conditionKV) {
Cursor m_cursor = get(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
ArrayList<doctorClass> list = new ArrayList<doctorClass>();
if (m_cursor.moveToFirst()) {
do {
doctorClass model = new doctorClass();
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)) != null)
model.setId(m_cursor.getInt(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)) != null)
model.setUsername(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)) != null)
model.setPassword(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)) != null)
model.setEmail(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)) != null)
model.setPhone(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)) != null)
model.setAddress(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)));
if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)) != null)
model.setGender(m_cursor.getString(m_cursor
.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)));
list.add(model);
} while (m_cursor.moveToNext());
}// end if
return list;
}
public Cursor get(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV != null)
whereClause = formatWherecondition(conditionKV);
String completeQuery = "SELECT * FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
}
return ourDatabase.rawQuery(completeQuery, null);
}
public String formatWherecondition(HashMap<String, String> conditionKV) {
try {
String result = "";
if (conditionKV.size() < 1) {
throw new Exception("Hahsmap condition Empty");
}
Iterator l_iterator = conditionKV.keySet().iterator();
boolean isOneField = false;
while (l_iterator.hasNext()) {
String l_key = (String) l_iterator.next();
String l_value = conditionKV.get(l_key);
if (isOneField)
result = result + " AND ";
result = result + l_key + "='" + l_value + "' ";
isOneField = true;
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void deleteDoctor(HashMap<String, String> conditionKV) {
delete(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
}
private void delete(String tableName, HashMap<String, String> conditionKV) {
String whereClause = null;
if (conditionKV == null)
return;
whereClause = formatWherecondition(conditionKV);
String completeQuery = "DELETE FROM " + tableName + " ";
if (whereClause != null) {
completeQuery += " WHERE " + whereClause;
ourDatabase.execSQL(completeQuery);
}
}
When running, an error occured, Here is the logcat
Please help me .
Thank you
Are you sure the "context" you are using here is not null ?
How about rewriting the open() function this way and calling it via open(getApplicationContext()); ?
public DatabaseOperations open(Context context) throws SQLException {
ourHelper = new DatabaseOperations(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}

How to prevent duplicate phone contacts to be added in database?

In my Android application, I have a List of Phone Contacts. I want to add these contacts in private list by selection through CheckBoxe and onButtonClick. What I want here is that if contacts are already present there in database then they should not be added. How can i do so ? Please help.
Here is the code :
private MyListAdapter adapter;
ArrayList<String> item_id = new ArrayList<String>();
ArrayList<String> item_contact_name = new ArrayList<String>();
ArrayList<String> filteredList = new ArrayList<String>();
ArrayList<String> item_contact_number = new ArrayList<String>();
Uri queryUri;
boolean flag = false;
boolean[] selection;
static ArrayList<String> selection_val;
private Button btn_select, btn_remove;
DbManager manager;
String[] contactArray;
Cursor Cursor, cursor1;
public static String[] selectedData;
String phoneNumber;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contacts);
manager = new DbManager(this);
try{
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
showEvents(Cursor);
cursor1 = manager.Return_All_Contacts();
contactArray = showEvents2(cursor1);
//final ViewHolder holder = new ViewHolder();
selection = new boolean[item_id.size()];
selection_val = new ArrayList<String>();
selectedData=new String[selection.length];
adapter = new MyListAdapter(this);
setListAdapter(adapter);
btn_select = (Button) findViewById(R.id.button1);
btn_select.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
// selectedData[i]=item_msg_body.get(i);
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
try{
addContacts(selectedData);
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(
getApplicationContext(),
"Your have Selected " + cnt + " ids. " + " "+ selectIds, Toast.LENGTH_LONG).show();
}
}
});
}
catch(Exception ex)
{
Log.e("Error in retrieving phone", ex.toString());
}
btn_remove = (Button)findViewById(R.id.remove);
btn_remove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
deleteMultiple(selectedData);
if (cnt == 0) {
Toast.makeText(getApplicationContext(), "NO Selection",Toast.LENGTH_LONG).show();
} else {
}
}
});
}
public class MyListAdapter extends BaseAdapter{
Context con;
private LayoutInflater layoutinf;
ArrayList<Boolean> itemChecked = new ArrayList<Boolean>();
ArrayList<String> items_ = new ArrayList<String>();
public MyListAdapter(
privateContacts sample_MultipleSelectionActivity) {
con = sample_MultipleSelectionActivity;
}
public int getCount() {
return item_id.size();
}
public Object getItem(int position) {
return item_id.size();
}
public long getItemId(int position) {
return item_id.get(position).hashCode();
}
public View getView(final int position, View convertView, ViewGroup arg2) {
View v = convertView;
ViewHolder holder = null;
if (v == null) {
layoutinf = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutinf.inflate(R.layout.row_add_contacts, null);
holder = new ViewHolder();
holder.chk = (CheckBox) v.findViewById(R.id.checkBox);
holder.tv_contact_name = (TextView) v.findViewById(R.id.tvname);
holder.tv_number = (TextView) v.findViewById(R.id.tvphone);
holder.iv_contact = (ImageView) v.findViewById(R.id.iv_contacts);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.chk.setId(position);
holder.tv_contact_name.setId(position);
holder.chk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
String val = cb.getText().toString();
if (selection[id]) {
cb.setChecked(false);
selection[id] = false;
selection_val.remove("" + item_contact_name.get(id));
} else {
cb.setChecked(true);
selection[id] = true;
selection_val.add("" + item_contact_name.get(id));
}
adapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("error", "" + e.toString());
}
}
});
holder.chk.setChecked(selection[position]);
if(selection[position] == true)
{
//holder.tv_contact_name.setBackgroundColor(Color.GRAY);
}
else
{
holder.tv_contact_name.setBackgroundColor(Color.TRANSPARENT);
}
// for(int i=0;i<contactArray.length;i++){
//
// holder.tv_contact_name.setBackgroundColor(Color.GREEN);
// }
//holder.chk.setText(item_id.get(position));
holder.tv_contact_name.setText("" + item_contact_name.get(position));
holder.tv_number.setText("" + item_contact_number.get(position));
return v;
}
}
public class ViewHolder {
private CheckBox chk;
private TextView tv_contact_name;
private TextView tv_number;
private ImageView iv_contact;
}
private void addContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
moveToLogActivity();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
private void showEvents(Cursor cursor) {
item_id = new ArrayList<String>(cursor.getCount());
item_contact_name = new ArrayList<String>(cursor.getCount());
item_contact_number = new ArrayList<String>(cursor.getCount());
//String ContactNames[] = new String[cursor.getCount()];
String id[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
item_contact_name.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
item_contact_number.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
i++;
}
}
private String[] showEvents2(Cursor cursor) {
String addedContacts[]=new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
addedContacts[i] = cursor.getString(1);
i++;
}
return addedContacts;
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void deleteMultiple(String[]selectedItems) {
manager.deleteContactsMultiselected(selectedItems);
moveToLogActivity();
}
The database code where i am saving data is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
ContactTable code in database is as :
// define table name
public static final String TABLE_CONTACTS = "CONTACTS_TABLE";
//define column of TABLE_CONTACTS
public static final String KEY_CONTACTID = "_id";
public static final String CONTACT_NAME = "Contact_name";

SetOnItemLongClickListener in custom cursorAdapter

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"

Categories

Resources