我在项目中使用RecyclerView,CardView和ViewPager,但由于NullPointerException错误导致应用程序崩溃。我在这个平台上尝试过相关问题的解决方案,但我仍然无法解决这个问题。有人可以帮我查看我的代码并告诉我我错过了什么吗?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PhoneAppsDataFragment(), "PHONE APPS DATA");
adapter.addFragment(new SocialNetworkDataFragment(), "SOCIAL NETWORK DATA");
adapter.addFragment(new PersonaManagerFragment(), "PERSONA MANAGER");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<> ();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@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);
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:elevation="5dp"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="5dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
android:elevation="5dp"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:elevation="5dp"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="5dp"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<android.support.v7.widget.RecyclerView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/rv"
>
</android.support.v7.widget.RecyclerView>
</android.support.design.widget.CoordinatorLayout>
PhoneAppsDataFragment.java(实现RecyclerView和CardView)
public class PhoneAppsDataFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
public PhoneAppsDataFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.custom_row, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.rv);
adapter = new RecyclerViewAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
return layout;
}
public static List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] logos = {R.drawable.ic_number1, R.drawable.ic_number2, R.drawable.ic_number3};
String[] thirdpartySites = {"Udacity", "JavaRanch", "Coursera"};
String[] sourceSites = {"Facebook", "Twitter", "LinkedIn"};
for (int i = 0; i < logos.length && i < thirdpartySites.length && i < sourceSites.length; i++) {
Information current = new Information();
current.logoId = logos[i];
current.thirdParty = thirdpartySites[i];
current.source = sourceSites[i];
data.add(current);
}
return data;
}
}
PhoneAppsDataFragment Layout
<?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:padding="16dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cv"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/logo_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/thirdparty_name"
android:layout_toRightOf="@+id/logo_photo"
android:layout_alignParentTop="true"
android:textSize="30sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/source_name"
android:layout_toRightOf="@+id/logo_photo"
android:layout_below="@+id/thirdparty_name"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private LayoutInflater inflater;
List<Information> data = Collections.emptyList();
public RecyclerViewAdapter(Context context, List<Information> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.logo.setImageResource(current.logoId);
holder.thirdPartyName.setText(current.thirdParty);
holder.sourceName.setText(current.source);
}
@Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
TextView thirdPartyName;
TextView sourceName;
ImageView logo;
public MyViewHolder(View itemView) {
super(itemView);
logo = (ImageView) itemView.findViewById(R.id.logo_photo);
thirdPartyName = (TextView) itemView.findViewById(R.id.thirdparty_name);
sourceName = (TextView) itemView.findViewById(R.id.source_name);
}
}
}
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/logo_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:src="@drawable/ic_number1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/thirdparty_name"
android:layout_toRightOf="@+id/logo_photo"
android:layout_alignParentTop="true"
android:textSize="30sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/source_name"
android:layout_toRightOf="@+id/logo_photo"
android:layout_below="@+id/thirdparty_name"
/>
</LinearLayout>
Information.java
class Information {
int logoId;
String thirdParty;
String source;
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.personamanager.org.personamanager" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/MyMaterialTheme">
<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>
错误日志
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.personamanager.org.personamanager, PID: 2317
E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widge t.RecyclerView$Adapter)' on a null object reference
E/AndroidRuntime: at com.personamanager.org.personamanager.PhoneAppsDataFragment.onCreateView(P honeAppsDataFragment.java:35)
E/AndroidRuntime: at android.support.v4.app.Fragment.performCreateView(Fragment.java:1965)
E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.jav a:1078)
E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
E/AndroidRuntime: at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
E/AndroidRuntime: at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
E/AndroidRuntime: at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
E/AndroidRuntime: at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
E/AndroidRuntime: at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
E/AndroidRuntime: at android.view.View.measure(View.java:17430)
E/AndroidRuntime: at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
E/AndroidRuntime: at android.support.design.widget.CoordinatorLayout.onMeasureChild(Coordinator Layout.java:610)
E/AndroidRuntime: at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayou t.java:677)