尝试保存数据时出错

时间:2017-08-26 17:27:47

标签: android sharedpreferences hashset

删除以前的数据后,应用程序在第一次运行时运行正常。它在第二次运行时崩溃并且必须从sharedprefs获取保存的信息(我用HashSets保存了它)。

SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.adam.vaistai", Context.MODE_PRIVATE);

HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("names", null);

HashSet<String> numberSet = (HashSet<String>) sharedPreferences.getStringSet("numbers", null);

HashSet<String> descSet = (HashSet<String>) sharedPreferences.getStringSet("desc", null);

if (set == null){
    vaistai.add("Pavyzdys 2017-08-18");
    numbers.add(String.valueOf(0));
    description.add("Nuo persalimo, vartoti 3 kartus dienoje");

} else {

    vaistai = new ArrayList<>(set);
    //error
    numbers = new ArrayList<>(numberSet);
    description = new ArrayList<>(descSet);

}

使用日志我发现应用程序在行后崩溃( vaistai = new ArrayList&lt;&gt;(set);

08-26 17:11:00.745 7730-7730/com.example.adam.vaistai E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: com.example.adam.vaistai, PID: 7730
                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.adam.vaistai/com.example.adam.vaistai.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference

logcat显示了这个

这是MainActivity.java的代码

package com.example.adam.vaistai;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

ListView listView;

static ArrayList<String> vaistai = new ArrayList<>();
static ArrayList<String> numbers = new ArrayList<>();
static ArrayList<String> description = new ArrayList<>();

static ArrayAdapter arrayAdapter;


public void nextActivity (int pos){

    Intent intent = new Intent(this, SecondActivity.class);

    intent.putExtra("index", pos);

    startActivity(intent);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater menuInflater = getMenuInflater();

    menuInflater.inflate(R.menu.main_menu, menu);

    return super.onCreateOptionsMenu(menu);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    if (item.getItemId() == R.id.newNote){

        vaistai.add("");
        numbers.add(String.valueOf(0));
        description.add("");

        arrayAdapter.notifyDataSetChanged();

        nextActivity(vaistai.size()-1);
    }
    return false;
}

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

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

    SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.adam.vaistai", Context.MODE_PRIVATE);

    HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("names", null);

    HashSet<String> numberSet = (HashSet<String>) sharedPreferences.getStringSet("numbers", null);

    HashSet<String> descSet = (HashSet<String>) sharedPreferences.getStringSet("desc", null);

    if (set == null){
        vaistai.add("Pavyzdys 2017-08-18");
        numbers.add(String.valueOf(0));
        description.add("Nuo persalimo, vartoti 3 kartus dienoje");

    } else {

        vaistai = new ArrayList<>(set);
        numbers = new ArrayList<>(numberSet);
        description = new ArrayList<>(descSet);

    }

    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, vaistai);

    listView.setAdapter(arrayAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            nextActivity(i);

        }
    });

    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

            final int item = i;

            new AlertDialog.Builder(MainActivity.this)
                    .setIcon(android.R.drawable.alert_dark_frame)
                    .setTitle("Ar norite istrinti?")
                    .setMessage("Irasas bus pasalintas")
                    .setPositiveButton("Taip", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            vaistai.remove(item);
                            numbers.remove(item);
                            description.remove(item);
                            arrayAdapter.notifyDataSetChanged();

                            SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.adam.vaistai", Context.MODE_PRIVATE);

                            HashSet<String> numberSet = new HashSet<String>(MainActivity.numbers);

                            sharedPreferences.edit().putStringSet("numbers", numberSet).apply();

                            HashSet<String> set = new HashSet<String>(MainActivity.vaistai);

                            sharedPreferences.edit().putStringSet("names", set).apply();

                            HashSet<String> descSet = new HashSet<String>(MainActivity.description);

                            sharedPreferences.edit().putStringSet("desc", descSet).apply();
                        }
                    }
                    )
                    .setNegativeButton("Ne", null)
                    .show();

            return true;
        }
    });

}

}

1 个答案:

答案 0 :(得分:0)

由于set是一个集合,请尝试使用以下行将set添加到列表中。 addall方法需要收集。

TalVideoPlayer

并确保这些行

vaistai.addAll(set);

在空字符串设置的情况下返回null,通过设置断点和调试来执行此操作。