2017-03-29 32 views
0

我想从连接到sharedPreferences的taskList中删除一个项目。 我设法删除所有项目,但问题是我无法找到一种方法来连接计数器从具有开关的列表中删除单个项目,并且当此开关为真时我需要通过索引编号从列表中删除项目。不能找到一种方法来删除sharedPreferences项目

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"))); 
     } 

} 

}

而且我utlShared类是

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

} 

}

这种方法是从我的欢迎类,这是

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

} 

}

称为

很抱歉的长码,但我已经花了这个问题如此多的时间,并没有找到一个正常的方式来解决它......

在此先感谢你们,非常感谢!

+0

为什么不使用类似SugarORM的东西呢?有了它,你可以在一行中删除/添加和选择用户。 – DEADMC

+0

看到这个链接http://stackoverflow.com/questions/18806147/deleting-listview-item-from-list-and-sharedpreferences。我认为它可以帮助你解决你的问题。 – Sushrita

+0

我正在看这个家伙的代码,它有点乱,但我会尽快尝试,谢谢,我会回复一个答案,希望它会有所帮助。 – z3r0

回答

0
taskEditor.remove('item tag'); 
taskEditor.commit(); 
+0

While这段代码可能会解决这个问题,[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高您的帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – yennsarah

0

猜猜我的问题还不够清楚,但我找到了一种方法来做到这一点。

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它不是完美的,因为我可以刷新视图后,我更新的编辑器和后,才重新启动应用程序我最后删除的任务消失。

干杯和谢谢很多家伙!

相关问题