NullPointer抛出不确定原因

时间:2014-02-20 06:05:48

标签: java android eclipse listview

我不确定为什么我会收到此错误,之前有效,任何帮助都表示赞赏。试图在微调器选择时产生一个新的活动(我有一个带有列表视图的工作版本,我决定分支尝试一个微调器,相当远,然后迷失了试图弄清楚这个错误)。它也很完美,所以我知道我必须像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("");

}

}

ClassPage

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>

4 个答案:

答案 0 :(得分:2)

把这个

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

onCreate()之后setContentView(R.layout.activity_main);内的<{1}}

答案 1 :(得分:2)

添加此

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

在你的主动活动中。

答案 2 :(得分:1)

试试这个..

OnCreate

setContentView(R.layout.activity_main);后的MainActivity内执行此操作
Spinner spin = (Spinner) findViewById(R.id.spinner2);

OR

从全局变量

中删除Spinner spin = (Spinner) findViewById(R.id.spinner2);

答案 3 :(得分:1)

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

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