使用android共享首选项的致命错误

时间:2015-02-24 20:44:23

标签: android android-activity android-studio nullpointerexception fatal-error

我正在开发我的第一个android项目,我正在使用android studio。该项目在我的测试设备上正常运行,然后我选择清理项目,现在应用程序将无法运行,抛出的异常是:

Unable to instantiate activity
ComponentInfo{com.lonerganonline.league_of_ireland/com.lonerganonline.league_of_ireland.MainActivity}: 
java.lang.NullPointerException

因为我不知道错误在哪里orrignating我不知道要发布什么代码。 enter image description here

主要活动:

package com.lonerganonline.league_of_ireland;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
private Spinner spinner;
private SharedPreferences favTeam ;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    favTeam = this.getSharedPreferences("com.lonerganonline.league_of_ireland", Context.MODE_PRIVATE);
    /*if (favTeam.contains("team")){
        setContentView(R.layout.my_home);
    }
    else{*/
        setContentView(R.layout.activity_main);
   // }



    spinner = (Spinner) findViewById(R.id.selectTeam);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.teams_array, android.R.layout.simple_spinner_item);
      adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

    }


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

    public String getTeam(){
        String team ="";
        favTeam.getString("team","Not Defined");
        return team;
    }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

    public void submitMyTeam(View v){

        TextView txt = (TextView) findViewById(R.id.textView);
        String selectedTeam = spinner.getSelectedItem().toString();
        txt.setText(selectedTeam);
        editor  = favTeam.edit();
        editor.putString("team", selectedTeam);
        editor.apply();
        Intent intent = new Intent(this, MyTeamActivity.class);
        startActivity(intent);

    }

}



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Spinner
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/selectTeam"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_marginTop="163dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/submit"
    android:id="@+id/button"
    android:onClick="submitMyTeam"
    android:layout_below="@+id/selectTeam"
    android:layout_centerHorizontal="true" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView"
    android:layout_above="@+id/selectTeam"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

logcat的

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.lonerganonline.league_of_ireland/com.lonerganonline.league_of_ireland.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:212)
        at android.app.ActivityThread.main(ActivityThread.java:5137)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:718)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.lonerganonline.league_of_ireland.MainActivity.<init>(MainActivity.java:19)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1208)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
        at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)

2 个答案:

答案 0 :(得分:1)

只有在布局充气时间发生空指针异常时才能看到这样的近似误差。这种错误的最简单形式是尝试在onCreate中设置听众或菜单之类的东西。发生这种情况是因为当您说出&#34;设置片段&#34;之类的内容时,您并没有真正加载该片段。您在队列中的某处为inflater添加作业。您无法保证所有布局都是在onCreate结束时设置的。

我的赌注是稍后在应用程序启动流程中移动它(尝试onStart())

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.teams_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);move this

答案 1 :(得分:1)

private SharedPreferences.Editor editor = favTeam.edit();

更改private SharedPreferences.Editor editor = favTeam.edit();private SharedPreferences.Editor editor; 它导致NullPointerException因为它在构造Activity对象时尝试初始化编辑器,但是在执行onCreate()之前执行favTeam类成员的初始化。

然后在方法onCreate()中添加下一行 editor = favTeam.edit(); 在你之后 favTeam = this.getSharedPreferences("com.lonerganonline.league_of_ireland", Context.MODE_PRIVATE);