首页 > 解决方案 > 为 ListView 索引设置存储的背景颜色时出现问题

问题描述

我使用 ListView 布局制作了一个笔记应用程序。用户可以单击注释并设置其颜色。该颜色应用于 EditText 背景及其对应的 ListView 项。但是,当我退出应用程序时颜色会重置。每当打开应用程序时,如何为每个 ListView 索引设置保存的颜色配置?

我尝试使用 SharedPreferences 来保存和加载颜色,但我不断收到错误,应用程序甚至无法打开。我还尝试标记另一个 StackOverflow 帖子建议的颜色,但我得到了同样的错误。

MainActivity.java

 static int pos = 0;
 static String c = "";
 static ListView listBackground;

 protected void onCreate(Bundle savedInstanceState) {

 listBackground = findViewById(R.id.listView);

 // LOAD DATA FROM EditNote.java
 sharedPreferences = getApplicationContext().getSharedPreferences("com.example.syeds.notesapp", MODE_PRIVATE);

 //ATTEMPT TO SET COLOR OF CHILD  
 for(int count = 0; count < notes.size(); count++){
            String color = sharedPreferences.getString("color", null);
            listBackground.getChildAt(count).setBackgroundColor(Color.parseColor(color));

        }


 final ListView listView = findViewById(R.id.listView);

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    //THIS IS WHERE USER IS TAKEN TO EditNote.java   ` 
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     Intent intent = new Intent(getApplicationContext(),EditNote.class);       
            intent.putExtra("notePosition",position);     
            startActivity(intent);
        }
    });

编辑笔记.java

String color;
int position;

 @Override
  protected void onCreate(Bundle savedInstanceState) {

    final EditText editText = findViewById(R.id.editText);
    Intent intent = getIntent();

    //Get the position of array index
    position = intent.getIntExtra("notePosition", -1);

} 
    //EXAMPLE METHOD FOR ONE COLOR(OTHERS NOT INCLUDED IN SAMPLE)
    public void changeGreen(View view) {   

    //Set color
    color = "#D4EFDF";
    MainActivity.listBackground.getChildAt(position).setBackgroundColor(Color.parseColor(color));

    //ATTEMPT TO SAVE COLOR
    sharedPreferences.edit().putString("color",color).apply();


    //Sets background of EditText
    background = findViewById(R.id.editText);
    background.setBackgroundColor(Color.parseColor("#D4EFDF"));
}

对于上面提到的所有我尝试过的事情,我收到了这个错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char java.lang.String.charAt(int)' on a null object reference
    at android.graphics.Color.parseColor(Color.java:1384)
    at com.example.syeds.notesapp.MainActivity.onCreate(MainActivity.java:61)

标签: javaandroid

解决方案


尝试以下方式,希望它会起作用,因为我在我的应用程序中做类似的事情并且它工作正常:

保存颜色:

SharedPreferences mPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString("color", color);
editor.commit();

检索颜色:

color = mPreferences.getString("color", "#FFF");

推荐阅读