【问题标题】:NullPointer thrown not sure whyNullPointer 抛出不知道为什么
【发布时间】:2014-02-20 06:05:48
【问题描述】:

我不知道为什么我会收到这个错误,它以前工作过,感谢任何帮助。尝试在选择微调器时生成一个新活动(我有一个内部带有列表视图的工作版本,我决定分支尝试微调器,走得很远,然后在试图找出这个错误时迷路了)。它也工作得很好,所以我知道我必须像 1-5 行代码或其他东西。再次感谢任何帮助。

Logcat

02-19 23:57:15.980: E/AndroidRuntime(350): FATAL EXCEPTION: main
02-19 23:57:15.980: E/AndroidRuntime(350): java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.jordanmaxportfolio/com.example.jordanmaxportfolio.MainActivity}: java.lang.NullPointerException
02-19 23:57:15.980: E/AndroidRuntime(350):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
02-19 23:57:15.980: E/AndroidRuntime(350):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-19 23:57:15.980: E/AndroidRuntime(350):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-19 23:57:15.980: E/AndroidRuntime(350):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-19 23:57:15.980: E/AndroidRuntime(350):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 23:57:15.980: E/AndroidRuntime(350):  at android.os.Looper.loop(Looper.java:123)
02-19 23:57:15.980: E/AndroidRuntime(350):  at android.app.ActivityThread.main(ActivityThread.java:3683)

主要活动

package com.example.jordanmaxportfolio;


import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity
implements AdapterView.OnItemSelectedListener {

TextView selection;
ListView list;
Spinner spin = (Spinner) findViewById(R.id.spinner2);
public final static String exID="com.example.portfolio.MainActivity";

static final String[] items = new String[] {
    "36-2510 Game Engine Scripting I",  
    "36-2551 C++ I",    
    "36-3210 Game AI Programming",
    "36-3405 Authoring Interactive Media I & II" 
     };


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

    list = (ListView)findViewById(R.id.listView1);
    String[] items = getResources().getStringArray(R.array.Classes);

    list.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,items));

    list.setOnItemClickListener(new OnItemClickListener(){
        public void onItemClick(AdapterView<?> parent, View view,
                int postion, long id){

            Intent i =new Intent(MainActivity.this,ClassPage.class);
            i.putExtra(exID, String.valueOf(id));
            startActivity(i);
        }
        });

    selection = (TextView) findViewById(R.id.textView1);

    Spinner spin = (Spinner) findViewById(R.id.spinner2);
    spin.setOnItemSelectedListener(this);

    ArrayAdapter<String> aa = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_spinner_item, 
            items);

    aa.setDropDownViewResource(
       android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(aa);
}

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

public void onItemSelected(AdapterView<?> parent, View v, int position,
        long id) {
    // TODO Auto-generated method stub
    selection.setText(items[position]);
    Intent i =new Intent(MainActivity.this,ClassPage.class);
    i.putExtra(exID, String.valueOf(position));
    startActivity(i); 

}

/*spin.setOnItemSelectedListener(new OnItemSelectedListener()
{
    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position,
            long id) {
        Intent i =new Intent(MainActivity.this,ClassPage.class);
        i.putExtra(exID, String.valueOf(id));
        startActivity(i);  

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // TODO Auto-generated method stub
    }
    }
});*/


  /* example I saw online, however not quite right */



public void onNothingSelected(AdapterView<?> parent) {
    // TODO Auto-generated method stub
    selection.setText("");

}

}

类页面

package com.example.jordanmaxportfolio;


import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;

public class ClassPage extends Activity {


private TextView passedView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_class);

    String passedVar = getIntent().getStringExtra(MainActivity.exID);
    passedView = (TextView)findViewById(R.id.tv1);

    //passedView.setText("You have clicked item id: "+passedVar);
    if(passedVar.equals("0"))
    {
        passedView.setText("YAYY");

    }
    if(passedVar.equals("1"))
    {
        passedView.setText("Game Engine Scripting I");
        ImageView iv = (ImageView)findViewById(R.id.imageView1);
        iv.setImageResource(R.drawable.asteroids);
        TextView tv2 = (TextView)findViewById(R.id.tv2);
        tv2.setText("Using C# and Unity, I created a remake of the classic 'Asteroids!'. Dynamic difficulty level is the next addition.");
    }
    else if(passedVar.equals("2"))
    {
        passedView.setText("C++ I");
        ImageView iv = (ImageView)findViewById(R.id.imageView1);
        iv.setImageResource(R.drawable.poker);
        TextView tv2 = (TextView)findViewById(R.id.tv2);
        tv2.setText("Console GUI C++ Texas Hole 'Em Poker created by Neil Inglese and Jordan Max. Basic concept of game was to eliminate cursors. The game was completed, however we are re-doing it for our C++ II class to make it into the Xbox Live and Windows Store.");
    }
    else if(passedVar.equals("3"))
    {
        passedView.setText("Game AI Programming");
        ImageView iv = (ImageView)findViewById(R.id.imageView1);
        iv.setImageResource(R.drawable.game);
        TextView tv2 = (TextView)findViewById(R.id.tv2);
        tv2.setText("Currently enrolled in this class, we are learning about FSM's and C++ data structures such as stacks, vectors and queues. ");
    }
    else
    {
        passedView.setText("Authoring Interactive Media I & II");
        ImageView iv = (ImageView)findViewById(R.id.imageView1);
        iv.setImageResource(R.drawable.p);
        TextView tv2 = (TextView)findViewById(R.id.tv2);
        tv2.setText("Learned basic skills for HTML and CSS. Also divulged into HTML5, PHP, jQuery, and Javascript for web programming. Created my portfolio website based off knowledge learned.");
    }

    Button btn1 = (Button)findViewById(R.id.button1);

    // Show the Up button in the action bar.
    setupActionBar();
}
public void btnClicked(View view){
    Intent i = new Intent(this,MainActivity.class);
    startActivity(i);


}

/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // This ID represents the Home or Up button. In the case of this
        // activity, the Up button is shown. Use NavUtils to allow users
        // to navigate up one level in the application structure. For
        // more details, see the Navigation pattern on Android Design:
        //
        // http://developer.android.com/design/patterns/navigation.html#up-vs-back
        //
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

acitvity_class.xml

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ClassPage" >

<TextView
    android:id="@+id/tv1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:text="@string/hello_world" />

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="200dp"
    android:layout_alignLeft="@+id/tv1"
    android:layout_alignRight="@+id/tv1"
    android:layout_below="@+id/tv1"
    android:layout_marginTop="46dp"
    android:maxHeight="500dp"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/tv2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView1"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/imageView1"
    android:layout_marginLeft="21dp"
    android:layout_marginTop="60dp"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/tv2"
    android:layout_below="@+id/tv2"
    android:layout_marginTop="20dp"
    android:onClick="btnClicked"
    android:text="Go Back" />

</RelativeLayout>

activity_main.xml

<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/spinner1" >
</ListView>

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="67dp"
    android:layout_toLeftOf="@+id/listView1" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:text="@string/hello" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView2"
    android:layout_below="@+id/textView2"
    android:layout_marginLeft="57dp" />

</RelativeLayout>

【问题讨论】:

  • 你还没有定义spinner的id。

标签: java android eclipse listview


【解决方案1】:

放这个

Spinner spin = (Spinner) findViewById(R.id.spinner2);

setContentView(R.layout.activity_main); 之后的onCreate()

【讨论】:

    【解决方案2】:

    添加这个

    Spinner spin=(Spinner)findViewById(R.id.spinner2);

    在你的主要活动中。

    【讨论】:

      【解决方案3】:

      试试这个..

      OnCreatesetContentView(R.layout.activity_main); 之后在MainActivity 中执行此操作

      Spinner spin = (Spinner) findViewById(R.id.spinner2);
      

      从全局变量中删除Spinner spin = (Spinner) findViewById(R.id.spinner2);

      【讨论】:

        【解决方案4】:

        您正在尝试通过调用findViewById() 来初始化类成员spin。但是,在构造 Activity 类时,布局还不会膨胀。这意味着您必须等到onCreate() 进行此初始化。正如其他人已经回答的那样,您需要在调用setContentView() 之后将spin = (Spinnder) findViewById(R.id.spinner2) 放入onCreate() 方法中。

        要更详细地了解这一点,我强烈建议您阅读有关 Activity 生命周期的内容。

        【讨论】:

        • 大声笑不,我只是个白痴,这是有道理的。谢谢。
        猜你喜欢
        • 2019-04-12
        • 2013-11-07
        • 1970-01-01
        • 2020-01-15
        • 2015-11-09
        • 1970-01-01
        • 2017-07-08
        • 2013-05-16
        • 1970-01-01
        相关资源
        最近更新 更多