Sharedpreferences给了我一个空指针

时间:2013-09-30 14:56:06

标签: android eclipse sharedpreferences

嘿,我的共享偏好有点问题,它给了我一个nullpointerexception就行了     编辑器编辑= prefs.edit();

你知道为什么我会收到错误吗?

我在网上搜索了这个错误,很多人都有类似的东西,但是我没有找到与我在同一条线上有同样错误的人,并且解决方案不是我可以使用的东西

感谢您的帮助。

这是我的Main类的代码:

public class Main extends Activity{

Button bStart, bStop;
TextView tvView;
Spinner spinner1;
boolean stopValue;
int startkilometer;
String date;
SharedPreferences prefs;



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

    bStart = (Button) findViewById(R.id.bStart);
    tvView = (TextView) findViewById(R.id.tvView);
    spinner1 = (Spinner) findViewById(R.id.spinner1);

    date = getIntent().getStringExtra("datoen");
    startkilometer = getIntent().getIntExtra("startkm", 0);


SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    prefs.getBoolean("stopper", true);
    prefs.getInt("startkm", startkilometer);
    prefs.getString("datoen", date);



    stopValue = getIntent().getBooleanExtra("stopper", stopValue);


    if(stopValue){
        bStart.setText("Start");
        bStart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent start = new Intent("com.uniqueapps.runner.START");
                startActivity(start);
            }
        });
    }

    if(stopValue == false){
        bStart.setText("Stop");
        bStart.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent stop = new Intent("com.uniqueapps.runner.STOP");
                stop.putExtra("startkm", startkilometer);
                stop.putExtra("datoen", date);
                startActivity(stop);
            }
        });
    }

    KilometerSQL info = new KilometerSQL(this);
    info.open();
    String data = info.getData();
    info.close();
    tvView.setText(data);

    }




@Override
protected void onResume() {
    // TODO Auto-generated method stub

super.onResume();       


}

@Override
protected void onPause() {
    // TODO Auto-generated method stub

    Editor edit = prefs.edit();
    edit.putBoolean("stopper", stopValue);
    edit.putInt("startkm", startkilometer);
    edit.putString("datoen", date);
    edit.commit();

    super.onPause();
}

我的开始课程:

public class Start extends Main implements OnClickListener {

Button bStartTur;
EditText etDate, etKm;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start);
    bStartTur = (Button) findViewById(R.id.bStartTur);
    bStartTur.setOnClickListener(this);
    etDate = (EditText) findViewById(R.id.etdate);
    etKm = (EditText) findViewById(R.id.etKm);

    Calendar cal = Calendar.getInstance();

    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    etDate.setText(format.format(new Date()));



}



@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    String date = etDate.getText().toString();
    int startkilometer;
    switch (v.getId()) {

    case R.id.bStartTur:

        startkilometer = Integer.valueOf(etKm.getText().toString());


        Intent menu = new Intent("com.uniqueapps.runner.MENU");
        menu.putExtra("stopper", false);
        menu.putExtra("startkm", startkilometer);
        menu.putExtra("datoen", date);
        startActivity(menu);

        break;
    }

}

}

我的停课:

public class Stop extends Main implements OnClickListener {

Button bStop;
EditText sqllocations, kilometer;
int startkilometer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.stop);
    bStop = (Button) findViewById(R.id.bstopTur);
    bStop.setOnClickListener(this);
    sqllocations = (EditText) findViewById(R.id.locations);
    kilometer = (EditText) findViewById(R.id.Kilometer);

    sqllocations.setText("Unknown"); 


}

@Override
public void onClick(View v) {

    int startkilometer;
    int slutkilometer;
    startkilometer = getIntent().getIntExtra("startkm", 0);
    date = getIntent().getStringExtra("datoen");

    // TODO Auto-generated method stub

    switch(v.getId()){

    case R.id.bstopTur:


         slutkilometer = Integer.valueOf(kilometer.getText().toString());



        int kortekm = (slutkilometer - startkilometer);

        try{
        String locations = sqllocations.getText().toString();

        KilometerSQL entry = new KilometerSQL(this);
        entry.open();
        entry.createEntry(date, kortekm, locations);
        entry.close();
        }catch(Exception e){
            e.printStackTrace();
        }

         Intent menu = new Intent("com.uniqueapps.runner.MENU");
            menu.putExtra("stopper", true);
            startActivity(menu);
            break;
    }
}

}

我的SQL:

public class KilometerSQL {

public static final String KEY_ROWID = "date";
public static final String KEY_KILOMETER = "kilometer";
public static final String KEY_LOCATIONS = "locations";

private static final String DATABASE_NAME = "Kilometerdb";
private static final String DATABASE_TABLE = "kilometertable";
private static final int DATABASE_VERSION = 1;

private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class DbHelper extends SQLiteOpenHelper{

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                KEY_ROWID + " TEXT NOT NULL, " +
                KEY_KILOMETER + " INTEGER, " +
                KEY_LOCATIONS + " TEXT NOT NULL);"


                );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
    }


    }

public KilometerSQL (Context c){
    ourContext = c;
}

public KilometerSQL open(){
    ourHelper = new DbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

public void close(){
    ourHelper.close();
}

public long createEntry(String date, int kortekm, String locations) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(KEY_ROWID, date);
    cv.put(KEY_KILOMETER, kortekm);
    cv.put(KEY_LOCATIONS, locations);
    return ourDatabase.insert(DATABASE_TABLE, null, cv);
}

public String getData() {
    // TODO Auto-generated method stub
    String [] columns = new String []{ KEY_ROWID, KEY_KILOMETER, KEY_LOCATIONS};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iDate = c.getColumnIndex(KEY_ROWID);
    int iKilometer = c.getColumnIndex(KEY_KILOMETER);
    int iLocations = c.getColumnIndex(KEY_LOCATIONS);

    for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
        result = result + c.getString(iDate) + " " + c.getString(iKilometer) + " " + c.getString(iLocations) + "\n";
    }

    return result;
}

}

2 个答案:

答案 0 :(得分:2)

在onCreate中,您引用的是prefs的 local 变量,而不是作为类字段的变量。所以在onResume prefs中仍然是空的。

替换

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

答案 1 :(得分:1)

在你的onCreate中你要重新声明SharedPreferences prefs,因为它已经在Activity类中声明了你应该只用

分配它
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

您现在的方式是,prefs将是onCreate内的局部变量,活动prefs仍然为空