我一直在尝试为我的活动实现recyclelerview,但是我的onBindViewHolder一直在获取NullPointerException。我知道这意味着我将一个带有null值的变量传递给onBindViewHolder,但我似乎无法找到它!这是我第一次实施Recyclerview,所以如果我做错了什么我会很感激简洁的解释。
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at cn.easyar.samples.helloarmultitargetmt.RVAdapter.onBindViewHolder(RVAdapter.java:72)
at cn.easyar.samples.helloarmultitargetmt.RVAdapter.onBindViewHolder(RVAdapter.java:20)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6279)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6312)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5258)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5521)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3254)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1669)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1527)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131)
at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1375)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:870)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1193)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1669)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1527)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1669)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1527)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14618)
at android.view.ViewGroup.layout(ViewGroup.java:4491)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2191)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2005)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1218)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4975)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at
- >
我的适配器:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.ArticleViewHolder>{
Context context;
List<Article_Data> articles = Collections.emptyList();
public RVAdapter(List<Article_Data> articles, Context context){
this.articles = articles;
this.context = context;
}
public class ArticleViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView personName;
TextView article_data;
ImageView articlePhoto;
ArticleViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
personName = (TextView)itemView.findViewById(R.id.person_name);
article_data = (TextView)itemView.findViewById(R.id.person_age);
articlePhoto = (ImageView)itemView.findViewById(R.id.person_photo);}}
@Override
public ArticleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
ArticleViewHolder avh = new ArticleViewHolder(v);
return avh;
}
@Override
public void onBindViewHolder(ArticleViewHolder articleViewHolder, int i) {
articleViewHolder.personName.setText(articles.get(i).name);
articleViewHolder.article_data.setText(articles.get(i).article);
articleViewHolder.articlePhoto.setImageResource(articles.get(i).photoId);
}
@Override
public int getItemCount() {
return articles.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public void insert(int position, Article_Data data) {
articles.add(position, data);
notifyItemInserted(position);
}
public void remove(Article_Data data) {
int position = articles.indexOf(data);
articles.remove(position);
notifyItemRemoved(position);}} -->
我的布局文件(row_layout.xml):
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/activity_vertical_margin"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="@dimen/activity_vertical_margin"
app:cardElevation="@dimen/activity_vertical_margin">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/imageView"
android:text="Title"
android:textSize="30sp" />
<TextView
android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/title"
android:layout_toRightOf="@+id/imageView"
android:text="Description" />
</RelativeLayout>
</android.support.v7.widget.CardView> -->
我的WelcomeActivity:
<!-- public class WelcomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private FusedLocationProviderApi mFusedLocationClient;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private List<Article_Data> articles;
RecyclerView rv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initializeData();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.create();
builder.setIcon(R.drawable.ayade_gov);
builder.setTitle("Welcome to Cross River State!");
builder.setMessage("Hello You!, A hearty welcome to Cross River State!, we the people will like to show you our culture...");
builder.setNeutralButton("Enter", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
builder.setCancelable(true);
}
});
builder.show();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
@Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
private void initializeData() {
articles = new ArrayList<>();
//Uncomment data below to add info to cardview
// persons.add(new Person("Lavery Maiss", "25 years old", R.drawable.lavery));
// persons.add(new Person("Lillie Watts", "35 years old", R.drawable.lillie));
RecyclerView rv = (RecyclerView)findViewById(R.id.rv);
//rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
articles.add(new Article_Data("Emma Wilson", "23 years old", R.drawable.crs));
RVAdapter adapter = new RVAdapter(articles, getApplication());
rv.setAdapter(adapter);
}
@Override
protected void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.welcome, menu);
return true;
}
private void handleNewLocation(Location location) {
Log.d("MainActuvuty", location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
//LatLng latLng = new LatLng(currentLatitude, currentLongitude);
//mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
//MarkerOptions options = new MarkerOptions()
// .position(latLng)
// .title("I am here!");
// mMap.addMarker(options);
// mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
@Override
public void onConnected(Bundle bundle) {
try {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
} catch (SecurityException e) {
e.printStackTrace();
Log.d("MainActivity", e.getMessage());
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i("MainActivity", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if(id==R.id.nav_carnival){
// Handle the camera action
//add articles
//articles.add(new Article_Data("","",R.drawable.ayade_gov));
Sp.setDefaults("drawable", "R.drawable.ayade_gov" , getApplicationContext());
Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
startActivity(intent);
}else if(id==R.id.nav_gallery){
//add Gallery photos
Intent intent = new Intent(WelcomeActivity.this, FourInOneActivity.class);
startActivity(intent);
}else if(id==R.id.nav_calabar){
//articles relating to history
}else if(id==R.id.nav_places){
//articles relating to places to be in calabar
}else if(id==R.id.nav_share){
}else if(id==R.id.nav_send){
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
} -->
我的欢迎布局:
<!-- <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/content_welcome"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="cn.easyar.samples.helloarmultitargetmt.WelcomeActivity"
tools:showIn="@layout/app_bar_welcome">
<android.support.v7.widget.RecyclerView
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rv"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
/></LinearLayout> -->
答案 0 :(得分:0)
personName = (TextView)itemView.findViewById(R.id.person_name);
article_data = (TextView)itemView.findViewById(R.id.person_age);
articlePhoto = (ImageView)itemView.findViewById(R.id.person_photo);
所有这些变量都为null,因为在raw_layout中找不到任何带有关联id的视图。请指定带有ID的视图
person_name
person_age
person_photo
在raw_layout
中答案 1 :(得分:0)
Holder中的ID与XML中的id不同:
R.id.person_name AND title;
R.id.person_age AND description;
R.id.person_photo AND imageView
我想知道它是否是相同的xml!或者你从某处做过复制粘贴!