Android Studio:无法启动活动java.lang.NullPointerException

时间:2017-11-29 15:13:10

标签: android android-activity nullpointerexception onclicklistener

我正在开发一个项目,当我点击一个按钮打开另一个活动时,这是它崩溃时给我的消息。我知道这可能很简单,但我似乎无法找到我做错的事。

这是崩溃时给我的消息。

"java.lang.RuntimeException: Unable to start activity ComponentInfo{ualr.capstone.arkansasfloater/ualr.capstone.arkansasfloater.RiverTweet}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference"

这是清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="ualr.capstone.arkansasfloater">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name=".RList"
        android:parentActivityName=".MainActivity">
    </activity>
    <activity
        android:name=".InfoActivity"
        android:parentActivityName=".RList">
    </activity>

    <activity android:name=".RiverTweet">
    </activity>
</application>

</manifest>

这是xml代码

<?xml version="1.0" encoding="utf-8"?>
<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="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="ualr.capstone.arkansasfloater.MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Welcome! This app provides water height data for Arkansas 
  Rivers, press a button to continue"
    android:textAlignment="center"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"/>

<Button
    android:id="@+id/continuebutton"
    android:layout_width="150dp"
    android:layout_height="75dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:onClick="click"
    android:text="River Info" />

<Button
    android:id="@+id/Rtweets"
    android:layout_width="150dp"
    android:layout_height="75dp"
    android:layout_below="@+id/continuebutton"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="55dp"
    android:text="River Tweets"/>

</RelativeLayout>

这是主要活动

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


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


    Button welcome = (Button) findViewById(R.id.continuebutton);
    Button tweets = (Button) findViewById(R.id.Rtweets);

    welcome.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){

            Intent i = new Intent(v.getContext(), RList.class);
            startActivity(i);
        }



    });

    tweets.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v){

            Intent intent = new Intent(MainActivity.this, RiverTweet.class);
            startActivity(intent);
        }



    });




}
}

这是应该开放的活动。

import java.util.ArrayList;
import java.util.List;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.OAuth2Token;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class RiverTweet extends Activity {
Button bigpiney;
Button buffalo;
Button ouachita;
Button white;
Button spring;
private final String TWIT_CONS_KEY = "my cons";
private final String TWIT_CONS_SEC_KEY = 
"my secret";
ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    spring = (Button)findViewById(R.id.spring);
    white = (Button) findViewById(R.id.white);
    ouachita = (Button) findViewById(R.id.ouachita);
    bigpiney = (Button) findViewById(R.id.bigpiney);
    buffalo = (Button) findViewById(R.id.buffalo);
    list = (ListView) findViewById(R.id.list);

    spring.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new SearchOnTwitter().execute(spring.getText().toString());
        }
    });

    white.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new SearchOnTwitter().execute(white.getText().toString());
        }
    });

    ouachita.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new SearchOnTwitter().execute(ouachita.getText().toString());
        }
    });

    bigpiney.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new SearchOnTwitter().execute(bigpiney.getText().toString());
        }
    });

    buffalo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            new SearchOnTwitter().execute(buffalo.getText().toString());
        }
    });
}

class SearchOnTwitter extends AsyncTask<String, Void, Integer> {
    ArrayList<Tweet> tweets;
    final int SUCCESS = 0;
    final int FAILURE = SUCCESS + 1;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(String... params) {
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setApplicationOnlyAuthEnabled(true);
            builder.setOAuthConsumerKey(TWIT_CONS_KEY);
            builder.setOAuthConsumerSecret(TWIT_CONS_SEC_KEY);

            OAuth2Token token = new 
TwitterFactory(builder.build()).getInstance().getOAuth2Token();

            builder = new ConfigurationBuilder();
            builder.setApplicationOnlyAuthEnabled(true);
            builder.setOAuthConsumerKey(TWIT_CONS_KEY);
            builder.setOAuthConsumerSecret(TWIT_CONS_SEC_KEY);
            builder.setOAuth2TokenType(token.getTokenType());
            builder.setOAuth2AccessToken(token.getAccessToken());

            Twitter twitter = new 
TwitterFactory(builder.build()).getInstance();

            Query query = new Query(params[0]);
            // YOu can set the count of maximum records here
            query.setCount(50);
            QueryResult result;
            result = twitter.search(query);
            List<twitter4j.Status> tweets = result.getTweets();
            StringBuilder str = new StringBuilder();
            if (tweets != null) {
                this.tweets = new ArrayList<Tweet>();
                for (twitter4j.Status tweet : tweets) {
                    str.append("@" + tweet.getUser().getScreenName() + " - " 
+ tweet.getText() + "\n");
                    System.out.println(str);
                    this.tweets.add(new Tweet("@" + 
tweet.getUser().getScreenName(), tweet.getText()));
                }
                return SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return FAILURE;
    }

    @Override
    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);
        if (result == SUCCESS) {
            list.setAdapter(new TweetAdapter(RiverTweet.this, tweets));
        } else {
            Toast.makeText(RiverTweet.this, getString(R.string.error), 
Toast.LENGTH_LONG).show();
        }
    }
}
}

第一个按钮工作正常,第二个按钮不是在我输入twitter的代码之后(从我建立的另一个应用程序复制粘贴。)再次感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

您正在使用第二个ActivityRiverTweet)上第一个活动的布局:

setContentView(R.layout.activity_main);

当您尝试按ID查找时,这就是您的按钮为空的原因:)