提问人:Basil Alosious 提问时间:6/6/2019 最后编辑:PhantômaxxBasil Alosious 更新时间:6/7/2019 访问量:74
App崩溃,空指针异常。列表视图给出 null 异常 [重复]
App is crashing , Null pointer exception . List view is giving the null exception [duplicate]
问:
我的项目中的一个活动正在崩溃。LogCat 显示 “Null EXCEPTION”。简单适配器给出 null 异常。我已经发布了feed_activity.java和feed_activity.XML文件。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FeedActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Your Feed");
setContentView(R.layout.activity_feed);
final ListView listView = findViewById(R.id.listview);
final List<Map<String,String>> wordData= new ArrayList<>();
for (int i=1;i<=5;i++){
Map<String,String> wordInfo = new HashMap<>();
wordInfo.put("content","word
content"+Integer.toString(i));
wordInfo.put("username","user"+Integer.toString(i));
wordData.add(wordInfo);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this,
wordData,android.R.layout.simple_list_item_2, new String[]
{"content","username"}, new int[]
{android.R.id.text1,android.R.id.text2});
listView.setAdapter(simpleAdapter);
}
}
[用于 feedactivity 的 LogCat][2] XML Activity_feed :- ListView 在约束布局中使用。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FeedActivity">
<ListView
android:id="@+id/listView"
android:layout_width="395dp"
android:layout_height="590dp"
android:layout_marginStart="8dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
</android.support.constraint.ConstraintLayout>
答:
-1赞
anudevSaraswat
6/6/2019
#1
您可以尝试以下操作 -
尝试从列表声明中删除 final 关键字。
尝试将
最终 ListView = findViewById(R.id.listview);
跟
final ListView = (ListView) findViewById(R.id.listview);
- 再次检查列表视图的 ID。
评论
0赞
Piyush
6/6/2019
这不会产生任何影响。
评论
activity_feed
listView