无法找到从sharedPreferences

时间:2017-03-29 07:56:28

标签: java android android-studio sharedpreferences baseadapter

我正在尝试从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();

}

}

对于长代码很抱歉,但是我花了很多时间来解决这个问题,并没有找到解决问题的正常方法......

先谢谢你们,非常感谢!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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();
    }

尽管它并不完美,因为我可以在更新编辑器后刷新视图,并且只有在我重新启动应用程序后,我上次删除的任务才会消失。

干杯谢谢你!