我在列表視圖中收到空指針異常。當在activity_main.xml中創建列表視圖時,它工作正常,但是當我在獨立文件中創建listview時發生錯誤。列表視圖的空指針異常
package pk.edu.pucit.lab_02;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] username = { "hamad", "ali", "ahmed", "riaz", "hamad", "ali",
"ahmed", "riaz", "hamad", "ali", "ahmed", "riaz", "hamad",
"ali", "ahmed", "riaz", "hamad", "ali", "ahmed", "riaz",
"hamad", "ali", "ahmed", "riaz", "hamad", "ali", "ahmed",
"riaz" };
ListView listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.acticity_linear_layout,
R.id.names, username);
listView.setAdapter(adapter);
}
}
這是我activity_linear_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/names"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginTop="10dp">
</TextView>
<TextView
android:id="@+id/scores"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginTop="10dp">
</TextView>
</LinearLayout>
這是我activity_list_view.xml
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</ListView>
這是我的menifest文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pk.edu.pucit.lab_02"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
粘貼logcat在這裏,也是第二種情況下的代碼,它會給你例外。 – Nazgul 2014-12-03 07:58:42
你只發布了工作代碼,它確實看起來很好。請張貼不工作的部分(不同文件部分)以及崩潰堆棧。 – Bruce 2014-12-03 08:00:04
你的'activity_main.xml'需要包含一個ID爲listView的ListView。不要把它放在單獨的'activity_list_view.xml'中 – Wicked161089 2014-12-03 08:01:44