我的问题在第39行,它是空异常
btnDetail = findViewById(R.id.btn_move_activity);
btnDetail.setOnClickListener(this);
我的代码
package com.example.aplikasimoviecataloguesub1;
import android.content.Intent;
import android.content.res.TypedArray;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnDetail;
private String[] dataName;
private String[] dataDescription;
private String[] dataDate;
private TypedArray dataPhoto;
private MoviesAdapter adapter;
private ArrayList<Movie> movies;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MoviesAdapter(this);
ListView listView = findViewById(R.id.lv_list);
listView.setAdapter(adapter);
prepare();
addItem();
btnDetail = findViewById(R.id.btn_move_activity);
btnDetail.setOnClickListener(this);
}
private void prepare() {
dataName = getResources().getStringArray(R.array.data_name);
dataDescription = getResources().getStringArray(R.array.data_description);
dataDate = getResources().getStringArray(R.array.data_date);
dataPhoto = getResources().obtainTypedArray(R.array.data_photo);
}
private void addItem() {
movies = new ArrayList<>();
for (int i = 0; i < dataName.length; i++) {
Movie movie = new Movie();
movie.setPhoto(dataPhoto.getResourceId(i, -1));
movie.setName(dataName[i]);
movie.setDate(dataDate[i]);
movie.setDescription(dataDescription[i]);
movies.add(movie);
}
adapter.setMovies(movies);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_move_activity:
Intent moveIntent = new Intent(MainActivity.this, DetailActivity.class);
startActivity(moveIntent);
break;
}
}
}
这是错误
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.aplikasimoviecataloguesub1.MainActivity.onCreate(MainActivity.java:39)
答案 0 :(得分:0)
确保R.id.btn_move_activity这个ID的视图来自R.layout.activity_main这个文件。
答案 1 :(得分:0)
检查id
所传递的button
。根据崩溃,您正在初始化button
之前对其进行访问。这就像访问内存中不存在的内容。因此, NPE 。另外,请养成在致电views
后立即初始化所有setContentView()
的习惯。有了这种习惯,您就可以避免 NPE对视图的偏爱 。请参考下面的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
initListeners();
adapter = new MoviesAdapter(this);
listView.setAdapter(adapter);
prepare();
addItem();
}
private void initViews() {
listView = findViewById(R.id.lv_list);
btnDetail = findViewById(R.id.btn_move_activity);
}
private void initListeners() {
btnDetail.setOnClickListener(this);
}
如果您有任何困惑,请告诉我。快乐编码:)
答案 2 :(得分:0)
您必须将变量强制转换为相关的视图元素,如下所示
jars