0

I am trying to delete an item from taskList which is connected to sharedPreferences. I managed to remove all items but the problem is I cant find a way to connect a counter to delete an individual item from a list that has a switch and when this switch is on true I need to remove the item from list by index number.

public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
PendingIntent pendingIntent;
int pos;

//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
    this.context = context;
    this.userName = userName;
    //go to user shared preferences and fill the list
    getData();
    notifyDataSetChanged();

}
//how many item to display
@Override
public int getCount() {
    //return the myTasks size....
    return myTasks.size();
}

//return a specific item by index
@Override
public Object getItem(int i) {
    return myTasks.get(i);
}

//return index number
@Override
public long getItemId(int i) {
    return i;
}

//create our view
@Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
    //inflate the view inside view object -> viewInflated
    final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
    //set our inflated view behavior

    //set pointer for our inflated view

    //set pointer for task name....
    final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
    //set pointer for taskInfo
    final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
    //set pointer for task status....
    final Switch swTask = (Switch) viewInflated.findViewById(taskDone);

    //set task name, by the index of my myTasks collection
    txtTaskName.setText(myTasks.get(index).taskName);
    //set task info, by index of myTasks collection
    txtTaskInfo.setText(myTasks.get(index).taskInfo);
    //set task status , switch is getting true/false
    swTask.setChecked(myTasks.get(index).taskStatus);

    //show date and time dialog
    final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
    dtPicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final AlertDialog.Builder ad = new AlertDialog.Builder(context);
            final AlertDialog aDialog = ad.create();
            final LinearLayout adLayout = new LinearLayout(context);
            adLayout.setOrientation(LinearLayout.VERTICAL);
            TextView txtTime = new TextView(context);
            txtTime.setText("Choose time");
            adLayout.addView(txtTime);

            final TimePicker tp = new TimePicker(context);
            adLayout.addView(tp);
            final DatePicker dp = new DatePicker(context);
            tp.setVisibility(View.GONE);
            adLayout.addView(dp);


            final Button btnNext = new Button(context);
            btnNext.setText("Next>");
            adLayout.addView(btnNext);
            btnNext.setGravity(1);

            Button btnCancel = new Button(context);
            btnCancel.setText("Cancel");
            adLayout.addView(btnCancel);
            btnCancel.setGravity(1);


            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    aDialog.cancel();
                }
            });
            btnNext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final int hour = tp.getHour();
                    final int min = tp.getMinute();

                    final String myHour = String.valueOf(hour);
                    final String myMin = String.valueOf(min);


                    calendar.set(Calendar.MONTH, dp.getMonth());
                    calendar.set(Calendar.YEAR, dp.getYear());
                    calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
                    dp.setVisibility(View.GONE);
                    tp.setVisibility(View.VISIBLE);
                    btnNext.setText("Finish");
                    btnNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                            calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
                            calendar.set(Calendar.MINUTE, tp.getMinute());
                            Intent my_intent = new Intent(context, RingtonePlayingService.class);
                            pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
                            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
                            if(hour > 12){
                                String myHour = String.valueOf(hour - 12);
                            }

                            if(min < 10)
                            {
                                String myMin = "0"+String.valueOf(min);
                            }

                            Toast.makeText(context, "Set for- "+tp.getHour()+":"+tp.getMinute() , Toast.LENGTH_LONG).show();
                            aDialog.cancel();
                        }
                    });
                }
            });
            aDialog.setView(adLayout);
            aDialog.show();
        }
    });

    //create listener event, when switch is pressed
    swTask.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //we using utlShared to update task status
            //create instance of utlShared
            utlShared myShared = new utlShared(context);
            //calling method of task, and giving userName(shared preferences, taskName, taskStatus)
            myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
            //we sending a message to the user, and inform him/her about the change
            Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();

        }
    });

    //return the view with the behavior.....
    return viewInflated;
}

private void getData() {
    //go to specific shared preferences by user name.....
    SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
    //create instance of our myTasks list
    myTasks = new ArrayList<>();


        Map<String, ?> tasks = taskPref.getAll();
        for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
            //insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
            for(int pos=0 ; pos<myTasks.size() ; pos++){
                myTasks.get(pos);
            }
            String[] str = oneTask.getValue().toString().split(",");
            myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
        }

}

}

And my utlShared class is

public class utlShared {

//context to use later

Context context;
//declatrtion of shared preferences object
private SharedPreferences userPref;
//declaration of shared preferences editor
private SharedPreferences.Editor editor;



public utlShared() {}

public utlShared(Context context)
{
    //get context to use it
    this.context=context;
    //declaretion of shared preferences with file name and file mode (private,public)
   userPref=context.getSharedPreferences("users",Context.MODE_PRIVATE);
    //declaration of editor
   editor=userPref.edit();


}

//get user and password
public void addUser(String userName, String password)
{

    //stores in the phone device under data\data\package name
    //put in shared preferences user name and password
    editor.putString(userName,password);
    //commit (save/apply) the changes.
    editor.commit();
}


public boolean checkUser(String userName)
{
    //get name by key->userName
    String checkString = userPref.getString(userName,"na");
    //print to logcat a custom message.....
    Log.e("checkUser", "checkUser: "+checkString );
    //check if userName equals to responded data, if it's na, we don't have the user...
    return !checkString.equals("na");


}

public boolean checkUserPassword(String userName, String userPassword)
{
    String checkString = userPref.getString(userName,"na");
    return checkString.equals(userPassword);
}

public void task(String userName,String taskName,String taskInfo, boolean taskDone)
{
    //pointer to user task shared preferences
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    //create editor to change the specific shared preferences
    SharedPreferences.Editor taskEditor=taskPref.edit();

    //add new task -> if true write 1 else write 0
    if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }


}
public void clearTasks(String userName, String taskName, String taskInfo, boolean taskDone)
{
    SharedPreferences taskPref=context.getSharedPreferences(userName, Context.MODE_PRIVATE);
    SharedPreferences.Editor tskEditor=taskPref.edit();
        tskEditor.clear();
        tskEditor.commit();

}

}

This method is called from my Welcome class which is

public class Welcome extends AppCompatActivity {

String userName;
Context context;
utlShared myUtl;
ListView taskList;
String taskName;
String taskInfo;
boolean taskDone;
AlarmManager alarmManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    setPointer();


}

private void setPointer()
{

    this.context=this;
    userName=getIntent().getStringExtra("userName");
    myUtl = new utlShared(context);
    taskList=(ListView)findViewById(R.id.taskList);
    setListData();
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    Toast.makeText(Welcome.this, "welcome user:"+userName, Toast.LENGTH_SHORT).show();
    Button btnBack = (Button)findViewById(R.id.btnBack);
    FloatingActionButton btnDelete=(FloatingActionButton)findViewById(R.id.btnDelete);

    btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myUtl.clearTasks(userName, taskName, taskInfo, taskDone);
            setListData();
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context, MainActivity.class);
            startActivity(intent);
            finish();
        }
    });



}

private void setListData() {
    final TaskAdapter adapter = new TaskAdapter(context, userName);
    taskList.setAdapter(adapter);
}

public void addCustomTask(View view)
{
    //create builder
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    //set title
    builder.setTitle("Add new task!");


    //inflate view from layout ->custom layout,null,false as defualt values
    View viewInflated= LayoutInflater.from(context).inflate(R.layout.dlg_new_task,null,false);

    final EditText txtCustomLine = (EditText)viewInflated.findViewById(R.id.txtHLine);
    final EditText txtCustomTask = (EditText)viewInflated.findViewById(R.id.txtTask);

    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    });

    builder.setPositiveButton("Add task", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();

            String myTaskCustom = txtCustomTask.getText().toString();
            String myTaskLine = txtCustomLine.getText().toString();
                myUtl.task(userName, myTaskCustom, myTaskLine, false);
                setListData();
        }
    });


    //display our inflated view in screen
    builder.setView(viewInflated);
    //show the dialog
    builder.show();

}

}

Sorry for the long code but I have spent so much time on that problem and didnt find a normal way to fix it...

Thanks in advance guys, much appreciated!

z3r0
  • 39
  • 1
  • 7
  • Why not use something like SugarORM?With it you could do removing/adding and selecting users in a single line. – Andrey Danilov Mar 29 '17 at 08:05
  • see this link http://stackoverflow.com/questions/18806147/deleting-listview-item-from-list-and-sharedpreferences .I assume it can help you with your problem. – Sushrita Mar 29 '17 at 08:08
  • Im looking at this guys code, its a bit of a mess but I will try it soon, thanks, I will get back with an answer, hopefully it would help. – z3r0 Mar 29 '17 at 09:10
  • 3
    Possible duplicate of [How to remove some key/value pair from SharedPreferences?](http://stackoverflow.com/questions/8034127/how-to-remove-some-key-value-pair-from-sharedpreferences) – Manoj Perumarath Mar 29 '17 at 09:13

2 Answers2

0
taskEditor.remove('item tag');
taskEditor.commit();
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – yennsarah Mar 29 '17 at 13:14
0

Guess my question wasnt clear enough but I have found a way to do that.

if(!taskDone){
        String myData = taskName+","+taskInfo+","+(taskDone?"1":"0");
        taskEditor.putString(taskName,myData);
        //apply the changes
        taskEditor.commit();
    }
    else
    {
        taskEditor.remove(taskName);
        taskEditor.commit();
        adapter.notifyDataSetChanged();
    }

Eventhough its not perfect because I can refresh the view after I update the Editor and only after I restart the app my last deleted tasks disappear.

Cheers and thanks a lot guys!

z3r0
  • 39
  • 1
  • 7