为ListView索引设置存储的背景色时出现问题

时间:2019-01-16 22:26:19

标签: java android

我使用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);
        }
    });

EditNote.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)

1 个答案:

答案 0 :(得分:0)

尝试以下方法,希望它能正常工作,因为我在我的应用程序中做了类似的事情,并且效果很好:

保存颜色:

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

检索颜色:

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