我试图在其中使用“片段活动”,但我具有带有片段状态适配器的“查看”寻呼机。它运行良好,但是例如,如果发生错误,并且必须返回该片段,它将在theragmentStatePagerAdapter中给出NullPointerException。
我看到一些类似的问题,说这可能是getItem()方法或使用了错误的库。但是我检查了一下,这不是问题。
import android.os.AsyncTask;
import android.os.Looper;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.content.Context;
import android.support.v7.widget.ThemedSpinnerAdapter;
import android.content.res.Resources.Theme;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
static Context c;
static LatestChapterAdapter adapter;
static PopularAdapter adapter2;
static ArrayList<LatestChapter> list;
static ArrayList<PopularManga> list2;
static SwipeRefreshLayout swipe;
static SwipeRefreshLayout swipe2;
static TextView error;
static TextView error2;
public static int Page;
static boolean Arabic;
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
FragmentManager manager;
public HomeFragment(){}
public HomeFragment(Context context,FragmentManager fragmentManager){
c = context;
manager = fragmentManager;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Arabic = Constants.getLanguage(c).equals("arabic");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main2,container,false);
mSectionsPagerAdapter = new SectionsPagerAdapter(manager);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager)v.findViewById(R.id.container_home);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout)v.findViewById(R.id.tabs_main);
tabLayout.setupWithViewPager(mViewPager);
return v;
}
@Override
public void onResume() {
super.onResume();
}
public static class loadLatestChapters extends AsyncTask {
@Override
protected void onPreExecute() {
if (!swipe.isRefreshing()){
swipe.setRefreshing(true);
}
super.onPreExecute();
}
@Override
protected void onPostExecute(Object o) {
if (swipe.isRefreshing()){
swipe.setRefreshing(false);
}
adapter.notifyDataSetChanged();
if (list.size() == 0){
error.setText("connection error\n\b\b try again");
}else {
error.setText("");
}
super.onPostExecute(o);
}
@Override
protected Object doInBackground(Object[] params) {
try {
if (Looper.myLooper() == null) {
Looper.prepare();
}
Document doc;
if (Arabic) {
if (Page == 1) {
doc = Jsoup.connect(Constants.MANGA_LATEST_CHAPTERS).timeout(Constants.TIMEOUT).get();
} else {
doc = Jsoup.connect(Constants.MANGA_LATEST_CHAPTERS + "?page=" + String.valueOf(Page))
.timeout(Constants.TIMEOUT).get();
}
Elements elements = doc.getElementsByClass("manga-item");
for (int i = 0; i < elements.size(); i++) {
Element man = elements.get(i);
String manga_url = man.select("h3").select("a").attr("abs:href");
String manga_name = man.select("h3").select("a").text();
//Document doc2 = Jsoup.connect(manga_url).get();
//String picture = doc2.getElementsByClass("boxed").select("img").first().absUrl("src");
String picture = Constants.MANGA_COVER_1 + manga_url.
replace(Constants.MANGA_COVER_3, "")
+ Constants.MANGA_COVER_2;
Elements elements2 = man.getElementsByClass("manga-chapter");
//String ch1 = elements2.first().select("a").text();
String ch1_url = elements2.first().select("a").attr("abs:href");
double num;
try {
num = Double.parseDouble(ch1_url.replace(manga_url + "/", ""));
} catch (NumberFormatException n) {
num = 999999;
}
String ch1 = String.valueOf((int) num);
String ch2;
if (num > 1) {
ch2 = String.valueOf((int) (num - 1));
} else {
ch2 = String.valueOf(999999);
}
String ch2_url = manga_url + "/" + String.valueOf((int) (num - 1));
LatestChapter chapter = new LatestChapter(manga_name, manga_url, picture, ch1,
ch1_url, ch2, ch2_url);
list.add(chapter);
}
}else {
if (Page == 1) {
doc = Jsoup.connect(Constants.MANGA_NELO).timeout(Constants.TIMEOUT).get();
} else {
doc = Jsoup.connect(Constants.MANGA_NELO_LATES_NEXT + String.valueOf(Page))
.timeout(Constants.TIMEOUT).get();
}
Elements elements = doc.getElementsByClass("first");
for (int i = 0; i < elements.size(); i++) {
Element man = elements.get(i);
Elements man2 = man.getElementsByTag("ul").get(0).getElementsByTag("li");
String manga_url = man.select("h3").select("a").attr("abs:href");
String manga_name = man.select("h3").select("a").text();
String picture = man.select("a").select("img").first().absUrl("src");
String id_manga = manga_url.replace("https://manganelo.com/manga/","");
String ch1_url ;
String ch1;
try {
ch1_url = man2.get(1).select("span").select("a").attr("abs:href");
ch1 = ch1_url.replace("https://manganelo.com/chapter/" + id_manga + "/chapter_", "");
}catch (Exception e){
ch1 = String.valueOf(999999);
ch1_url = "dsadasdas";
}
String ch2_url;
String ch2;
if (man2.size()>2){
ch2_url = man2.get(2).select("span").select("a").attr("abs:href");
ch2 = ch2_url.replace("https://manganelo.com/chapter/"+id_manga+"/chapter_","");
}else {
ch2_url = "";
ch2 = String.valueOf(999999);
}
LatestChapter chapter = new LatestChapter(manga_name, manga_url,
picture, ch1, ch1_url, ch2, ch2_url);
list.add(chapter);
}
}
} catch (IOException e) {
Toast.makeText(c,"ioe " + e.getMessage(),Toast.LENGTH_LONG).show();
Log.e("ZZZZZZZZZZZZZZZZZZZZZZZ"," " + e.getMessage());
} catch (NumberFormatException n){
Toast.makeText(c,"run " + n.getMessage(),Toast.LENGTH_LONG).show();
Log.e("CCCCCCCCCCCCCCCCCCCCCCC"," " + n.getMessage());
} catch (RuntimeException r){
Toast.makeText(c,"run " + r.getMessage(),Toast.LENGTH_LONG).show();
Log.e("XXXXXXXXXXXXXXXXXXXXXXX"," " + r.getMessage());
}
return null;
}
}
public static class loadPopular extends AsyncTask{
@Override
protected void onPreExecute() {
if (!swipe2.isRefreshing()){
swipe2.setRefreshing(true);
}
super.onPreExecute();
}
@Override
protected void onPostExecute(Object o) {
if (swipe2.isRefreshing()){
swipe2.setRefreshing(false);
}
adapter2.notifyDataSetChanged();
if (list2.size() == 0){
error2.setText("connection error\n\btry again");
}else {
error2.setText("");
}
super.onPostExecute(o);
}
@Override
protected Object doInBackground(Object[] params) {
try {
if (Looper.myLooper() == null) {
Looper.prepare();
}
if (Arabic) {
Document doc = Jsoup.connect(Constants.MANGA).timeout(Constants.TIMEOUT).get();
Elements elements = doc.getElementsByClass("media");
for (int i = 0; i < elements.size(); i++) {
String url = elements.get(i).getElementsByClass("media-left")
.select("a").attr("abs:href");
String name = elements.get(i).getElementsByClass("media-body")
.select("h5").text();
String picture = Constants.MANGA_COVER_1 + url.
replace(Constants.MANGA_COVER_3, "")
+ Constants.MANGA_COVER_2;
list2.add(new PopularManga(url, picture, name));
}
}else {
Document doc = Jsoup.connect(Constants.MANGA_NELO_TOP_VIEWS)
.timeout(Constants.TIMEOUT).get();
Elements elements = doc.getElementsByClass("list-truyen-item-wrap");
for (int i = 0; i < elements.size(); i++) {
String url = elements.get(i).getElementsByTag("a").get(0).
attr("abs:href");
String name = elements.get(i).getElementsByTag("h3").get(0).
select("a").text();
String picture = elements.get(i).getElementsByTag("a").get(0)
.select("img").first().absUrl("src");
list2.add(new PopularManga(url, picture, name));
}
}
}catch(IOException e){
Toast.makeText(c, "ioe " + e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("ZZZZZZZZZZZZZZZZZZZZZZZ", " " + e.getMessage());
}catch(NumberFormatException n){
Toast.makeText(c, "run " + n.getMessage(), Toast.LENGTH_LONG).show();
Log.e("CCCCCCCCCCCCCCCCCCCCCCC", " " + n.getMessage());
}catch(RuntimeException r){
Toast.makeText(c, "run " + r.getMessage(), Toast.LENGTH_LONG).show();
Log.e("XXXXXXXXXXXXXXXXXXXXXXX", " " + r.getMessage());
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int index = getArguments().getInt(ARG_SECTION_NUMBER);
if (index == 1) {
View rootView = inflater.inflate(R.layout.content_main, container, false);
swipe2 = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
error2 = (TextView)rootView.findViewById(R.id.error);
swipe2.setRefreshing(true);
RecyclerView recyclerView = (RecyclerView)rootView. findViewById(R.id.recycler_manga);
recyclerView.setHasFixedSize(false);
recyclerView.setNestedScrollingEnabled(false);
list2 = new ArrayList<>();
adapter2 = new PopularAdapter(list2, c);
GridLayoutManager layoutManager = new GridLayoutManager(c,3);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter2);
swipe2.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
error2.setText("");
list2.clear();
adapter2.notifyDataSetChanged();
new loadPopular().execute();
}
});
new loadPopular().execute();
return rootView;
}else if(index == 0 ) {
View rootView = inflater.inflate(R.layout.content_main, container, false);
swipe = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
error = (TextView)rootView.findViewById(R.id.error);
Page = 1;
swipe.setRefreshing(true);
RecyclerView recyclerView = (RecyclerView)rootView. findViewById(R.id.recycler_manga);
recyclerView.setHasFixedSize(false);
recyclerView.setNestedScrollingEnabled(false);
list = new ArrayList<>();
adapter = new LatestChapterAdapter(list, c);
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
error.setText("");
list.clear();
adapter.notifyDataSetChanged();
new loadLatestChapters().execute();
}
});
new loadLatestChapters().execute();
return rootView;
}
return null;
}
/*@Override
public void onResume() {
super.onResume();
list = new ArrayList<>();
list2 = new ArrayList<>();
adapter.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
swipe.setRefreshing(true);
swipe2.setRefreshing(true);
new loadLatestChapters().execute();
new loadPopular().execute();
}*/
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
Log.e("POPOPOPOPOPOPOPOPOPOP","po:" + position);
if (position == 0 || position == 1)
return PlaceholderFragment.newInstance(position);
else
return PlaceholderFragment.newInstance(0);
}
@Override
public int getCount() {
// Show 3 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.latest);
case 1:
return getResources().getString(R.string.popular);
}
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
try {
super.restoreState(state,loader);
}catch (NullPointerException n){
}
}
}
}
最佳答案
您的viewPager
正在管理
片段内已经存在的片段。因此,您需要在childFragmentManager
中传递fragmentManager
而不是PagerAdapter
。这可能是例外的原因。getChildFragmentManager()
的定义是:
返回一个私有的FragmentManager,用于在Fragment中放置和管理Fragment。
关于java - 我的 fragment 状态寻呼机适配器中的空指针异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54564232/