如何在TextView中显示传递的intent数据 - NullPointerException错误

时间:2016-04-05 19:53:29

标签: java android android-intent

我正在创建一个应用程序,将数据库中的数据显示到列表视图中。单击列表视图上的项目时,它会将用户带到新活动,以便他们可以查看有关该项目的更多详细信息。我想使详细信息页面动态显示详细信息,并设法在toast中显示列表视图项的标题。

现在,我试图通过使用setText()在字符串中显示标题但是收到错误来显示这个:

AndroidRuntime: FATAL EXCEPTION: main
         Process: com.example.kathe.parenttripapp, PID: 22849
                                                                             java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.kathe.parenttripapp/com.example.kathe.parenttripapp.Details}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
                                                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
                                                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                 at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                 at android.os.Looper.loop(Looper.java:135)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                              Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
                                                                                 at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)
                                                                                 at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                 at java.lang.Class.newInstance(Class.java:1606)
                                                                                 at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
                                                                                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
                                                                                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                                 at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                 at android.os.Looper.loop(Looper.java:135) 
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                                 at java.lang.reflect.Method.invoke(Native Method) 
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

这是错误发生在的类:

TextView titletext;
final List<Activitytable> activityTable = Activitytable.listAll(Activitytable.class);

String data = getIntent().getSerializableExtra("listPosition").toString();

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

    TextView titletext = (TextView) findViewById(R.id.titletext);

    String data = getIntent().getSerializableExtra("listPosition").toString();

    Toast.makeText(getBaseContext(),String.valueOf(data),Toast.LENGTH_LONG).show();

    setData();
}

private void setData() {
    Intent i = getIntent();
    Bundle b = i.getExtras();
    if (data != null) {
        String j = (String) b.get("listPosition");
        titletext.setText(j);
    }
    else{
        titletext.setText("Hello");
    }
}

这是它来自的活动:

final ListView listView = (ListView) findViewById(R.id.viewAll_listview);
    long count = Activitytable.count(Activitytable.class);

    if(count>0) {
        final List<Activitytable> activitytable = Activitytable.listAll(Activitytable.class);
        final ViewAllListView madapter = new ViewAllListView(getApplicationContext(), activitytable);
        listView.setAdapter(madapter);
        listView.setClickable(true);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?>parent, View v, int position, long id) {
                String title = activitytable.get(position).Title.toString();
                Activitytable AT = Activitytable.findById(Activitytable.class,activitytable.get(position).getId());
                Intent i = new Intent(getApplicationContext(),Details.class);
                i.putExtra("listPosition",title);
                startActivity(i);

            }
            public Object getItem(int position) {return position;}
        });

    }
        else

            {
                Toast.makeText(getApplicationContext(), "No Data Available in Table", Toast.LENGTH_LONG);
            }
        }

我想做的是将意图数据放入TextView'titletext'然后执行if语句,说明传递的意图数据是否等于活动标题然后显示以下数据但是无法解决出了什么问题。我尝试过使用getStringExtra()而不是getSerializableExtra但没有运气。适用于吐司但不适用于TextView。

3 个答案:

答案 0 :(得分:1)

如果你没有很好地理解你为什么这样做,那么在你进入onCreate之前不要初始化你的变量,同时为了防止NullPointerException,这是一个好习惯。 if (variable != null)

您正在存储int,因此请使用getIntExtra

TextView titletext;
List<Activitytable> activityTable;

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

    activityTable = Activitytable.listAll(Activitytable.class);
    titletext = (TextView) findViewById(R.id.titletext);

    Intent i = getIntent();
    if (i != null) {
        String data = i.getStingExtra("listPosition");
        titletext.setText(String.valueOf(data));
    }
}

答案 1 :(得分:0)

Bundle intentBundle = getIntent().getExtras(); if (intentBundle != null) { lastPosition = getInt( "lastPostion" ); } 中,不要将其作为成员变量。

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

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- GCM requires a Google account. -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <permission android:name="com.assorttech.assorttech.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.assorttech.assorttech.permission.C2D_MESSAGE" />
    <!-- This app has permission to register and receive dataf message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="com.assorttech.assorttech.MESSAGE" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.thefinestartist.finestwebview.FinestWebViewActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:screenOrientation="sensor"
            android:theme="@style/FinestWebViewTheme.Light"
            >

        </activity>
        <receiver
            android:name="com.pushbots.google.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <!-- Receives the actual messages. -->
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <!-- Receives the registration id. -->
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.assorttech.assorttech" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.pushbots.push.DefaultPushHandler" />
        <!--<receiver android:name="com.assorttech.assorttech.customHandler" />-->
        <service android:name="com.pushbots.push.GCMIntentService" />
    </application>

</manifest>

答案 2 :(得分:-1)

您收到的空指针位于第23行的Details类中

 at com.example.kathe.parenttripapp.Details.<init>(Details.java:23)