保存SharedPreferences并阅读它们会遇到麻烦

时间:2014-03-21 04:16:09

标签: android nullpointerexception sharedpreferences

我正在登录屏幕和主菜单屏幕。现在我一直工作,直到我尝试实现一个方法,如果用户登录或不。根据logcat的主要问题是nullpointerexception,我不能为我的生活如何解决这个问题。如果有人能给我一些很棒的意见。在这一点上任何帮助都会很棒。

以下是我的主菜单活动:

package com.chonbonstudios.LOLTOOLs;



import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class TitleMenu extends Activity {

TextView SummonerId;
TextView SummonerName;
TextView SummonerLevel;


long SummonerIdA = 0;
String SummonerNameA = "";
long SummonerLevelA = 0;
int profileIconIdA = 0;

SharedPreferences data;
SharedPreferences data1;
SharedPreferences data2;
SharedPreferences data3;
SharedPreferences data4;

boolean loggedIn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 

    data4 = getSharedPreferences("LoggedInStatus", 0);
    loggedIn = data4.getBoolean("LoggedInStatus", false);


    if (loggedIn == true){

    } else {
        startActivity(new Intent(TitleMenu.this, LoginActivity.class));
        this.finish();
    }


    SummonerIdA = getIntent().getLongExtra("SummonerIdTag", 0);
    SummonerNameA = getIntent().getStringExtra("SummonerNameTag");
    SummonerLevelA = getIntent().getLongExtra("SummonerLevelTag", 0);
    profileIconIdA = getIntent().getIntExtra("SummonerProfileIconIdTag", 0);

    SharedPreferences.Editor editor = data.edit();
    editor.putLong("SummonerIdTag", SummonerIdA);
    editor.commit();
    finish();

    SharedPreferences.Editor editor1 = data1.edit();
    editor1.putString("SummonerNameTag", SummonerNameA);
    editor1.commit();
    finish();


    SharedPreferences.Editor editor2 = data2.edit();
    editor2.putLong("SummonerLevelTag", SummonerLevelA);
    editor2.commit();
    finish();

    SharedPreferences.Editor editor3 = data3.edit();
    editor3.putInt("SummonerProfileIconIdTag", profileIconIdA);
    editor3.commit();
    finish();

    data = getSharedPreferences("SummonerIdTag", 0);
    SummonerIdA = data.getLong("SummonerIdTag", 0);

    data1 = getSharedPreferences("SummonerNameTag", 0);
    SummonerNameA = data1.getString("SummonerNameTag", "");

    data2 = getSharedPreferences("SummonerLevelTag", 0);
    SummonerLevelA = data2.getLong("SummonerLevelTag", 0);

    data3 = getSharedPreferences("SummonerProfileIconIdTag", 0);
    profileIconIdA = data3.getInt("SummonerProfileIconIdTag", 0);

    setContentView(R.layout.activity_title_menu);

    SummonerId = (TextView) findViewById(R.id.txtSummonerId);
    SummonerLevel = (TextView) findViewById(R.id.txtSummonerLevel);
    SummonerName = (TextView) findViewById(R.id.txtSummonerName);


    SummonerId.setText(String.valueOf("My Id: " + SummonerIdA));
    SummonerLevel.setText(String.valueOf(SummonerLevelA));
    SummonerName.setText(String.valueOf(SummonerNameA));






    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.title_menu, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.action_LofOff:
        startActivity(new Intent(TitleMenu.this, LoginActivity.class));
        this.finish();

    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}


    }

和我的登录活动:

package com.chonbonstudios.LOLTOOLs;



import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnItemSelectedListener {
public String array_spinner[];

Button Login;
EditText Name;
String loginName = "";
String url ="";
TextView one;
TextView two;
Spinner Area;
String AreaCode;

// JSON Node names
private static final String TAG_SUMMONERID = "id";
private static final String TAG_SUMMONERNAME = "name";
private static final String TAG_SUMMONERLEVEL = "summonerLevel";
private static final String TAG_PROFILEICON = "profileIconId";


long SummonerIdA = 0;
String SummonerNameA = "";
long SummonerLevelA = 0;
int profileIconIdA = 0;

SharedPreferences data4;

public boolean loggedIn = false;


private ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    Typeface typeFace =  Typeface.createFromAsset(getAssets(),"fonts/fq.ttf");

    Login = (Button) findViewById(R.id.btnLogin);
    Name = (EditText) findViewById(R.id.inputSummonerNameLogin);
    one = (TextView) findViewById(R.id.textView1);
    two = (TextView) findViewById(R.id.textView2);


    Area = (Spinner) findViewById(R.id.spinArea);

    Login.setTypeface(typeFace);
    one.setTypeface(typeFace);
    two.setTypeface(typeFace);
    Name.setTypeface(typeFace);

    array_spinner= new String[7];
    array_spinner[0]="NA";
    array_spinner[1]="BR";
    array_spinner[2]="EUW";
    array_spinner[3]="EUNE";
    array_spinner[4]="LAN";
    array_spinner[5]="LAS";
    array_spinner[6]="OCE";


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, array_spinner);
    Area.setAdapter(adapter);
    Area.setOnItemSelectedListener(this);

    Login.setOnClickListener(new OnClickListener(){


        public void onClick(View V) {

            if(Name.getText().length() != 0){
                loginName = Name.getText().toString();

                url = "https://prod.api.pvp.net/api/lol/" + AreaCode  + "/v1.3/summoner/by-name/" + loginName + "?api_key=NOAPIKEYFORYOU";




                new GetUserData().execute();




            } else{
                toastNoNameMethod();

            }       

        }

    });



}



private void toastNoNameMethod() {
    Toast toastNoName = Toast.makeText(this, "Please Enter a Summoner Name",     Toast.LENGTH_SHORT);
    toastNoName.show();

}

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {

    int i = Area.getSelectedItemPosition();
    switch(i){
    case 0: AreaCode = "na"; break;
    case 1: AreaCode = "br" ; break;
    case 2: AreaCode = "euw"; break;
    case 3: AreaCode = "eune"; break;
    case 4: AreaCode = "lan"; break;
    case 5: AreaCode = "las"; break;
    case 6: AreaCode = "oce"; break;

    }

}

public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

private class GetUserData extends AsyncTask<Void, Void, Void> {



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String userDataSummoner = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + userDataSummoner);

        if (userDataSummoner != null) {
            try {
                JSONObject jsonObj = new JSONObject(userDataSummoner);
                JSONObject userData = jsonObj.getJSONObject(loginName);

                SummonerIdA = userData.getLong(TAG_SUMMONERID);
                SummonerNameA = userData.getString(TAG_SUMMONERNAME);
                SummonerLevelA = userData.getLong(TAG_SUMMONERLEVEL);
                profileIconIdA = userData.getInt(TAG_PROFILEICON);



            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");

        }


        return null;


    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();

        Intent myIntent = new Intent(LoginActivity.this, TitleMenu.class);
        myIntent.putExtra("SummonerNameTag", SummonerNameA);
        myIntent.putExtra("SummonerIdTag", SummonerIdA);
        myIntent.putExtra("SummonerLevelTag", SummonerLevelA);
        myIntent.putExtra("SummonerProfileIconIdTag", profileIconIdA);
        startActivity(myIntent);


        loggedIn = true;

        SharedPreferences.Editor editor4 = data4.edit();
        editor4.putBoolean("LoggedInStatus", loggedIn);
        editor4.commit();
        finish();




    }


}

@Override
public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}


}

我的日志猫:

03-21 00:12:16.350: D/AndroidRuntime(31329): Shutting down VM
03-21 00:12:16.350: W/dalvikvm(31329): threadid=1: thread exiting with uncaught exception (group=0x41df9700)
03-21 00:12:16.355: E/AndroidRuntime(31329): FATAL EXCEPTION: main
03-21 00:12:16.355: E/AndroidRuntime(31329): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.chonbonstudios.LOLTOOLs/com.chonbonstudios.LOLTOOLs.TitleMenu}: java.lang.NullPointerException
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.ActivityThread.access$700(ActivityThread.java:168)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.os.Looper.loop(Looper.java:137)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.ActivityThread.main(ActivityThread.java:5493)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at java.lang.reflect.Method.invokeNative(Native Method)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at java.lang.reflect.Method.invoke(Method.java:525)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at dalvik.system.NativeStart.main(Native Method)
03-21 00:12:16.355: E/AndroidRuntime(31329): Caused by: java.lang.NullPointerException
03-21 00:12:16.355: E/AndroidRuntime(31329):    at com.chonbonstudios.LOLTOOLs.TitleMenu.onCreate(TitleMenu.java:55)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.Activity.performCreate(Activity.java:5372)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
03-21 00:12:16.355: E/AndroidRuntime(31329):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
03-21 00:12:16.355: E/AndroidRuntime(31329):    ... 11 more
03-21 00:12:16.740: D/libEGL(31368): loaded /system/lib/egl/libEGL_mali.so
03-21 00:12:16.740: D/libEGL(31368): loaded /system/lib/egl/libGLESv1_CM_mali.so
03-21 00:12:16.745: D/libEGL(31368): loaded /system/lib/egl/libGLESv2_mali.so
03-21 00:12:16.750: E/(31368): Device driver API match
03-21 00:12:16.750: E/(31368): Device driver API version: 23
03-21 00:12:16.750: E/(31368): User space API version: 23 
03-21 00:12:16.750: E/(31368): mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Wed Oct  9 21:05:57 KST 2013 
03-21 00:12:16.785: D/OpenGLRenderer(31368): Enabling debug mode 0

1 个答案:

答案 0 :(得分:0)

在调用data方法之前,您还需要初始化data1data2data3SharedPreferences edit()个实例:

data = getSharedPreferences("pref_key", 0);
SharedPreferences.Editor editor = data.edit();
.....
data1 = getSharedPreferences("pref_key_data1", 0);
SharedPreferences.Editor editor = data1.edit();
.....