Android的两个片段的AsyncTask类nullpoint

Android的两个片段的AsyncTask类nullpoint

本文介绍了Android的两个片段的AsyncTask类nullpointexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有两个片段在我tabhost(viewpager)和i解析JSON和我可以显示jsons在列表视图项目的每个片段,不同的仅仅是JSON的,现在我写setMenuVisibility方法现在,我可以当我want.for例如,如果我这就去第二个片段,第二类的AsyncTask乳宁加载的AsyncTask类,但是当我回到第一个活动(meybe又来了第二个片段)我有nullpoinexception。这是我的code,如果有人知道的解决方案,请帮助我
谢谢
这是我的Mainactivity.java类code

i have two fragment in my tabhost(viewpager)and i parsed json and i can show jsons's items in listview each fragment,the different is only json's url.first time both Asynctask class run same time but now i wrote setMenuVisibility method and now i can to load Asynctask class when i want.for example if i 'll go second fragment, second Asynctask class runing,but when i go back first activity (meybe again go second fragment) i have nullpoinexception. this is a my code if anyone knows solution please help methanksthis is a my Mainactivity.java class code

public class MainActivity extends FragmentActivity implements
    TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {

private TabHost mTabHost;
private ViewPager mViewPager;
private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, MainActivity.TabInfo>();
private PagerAdapter mPagerAdapter;
private HorizontalScrollView horizontalScrollView;
private ImageButton menubutton;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    menubutton = (ImageButton) findViewById(R.id.menubutton);
    menubutton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Toast.makeText(getApplicationContext(), "Helo",
                    Toast.LENGTH_SHORT).show();

        }
    });

    this.initialiseTabHost(savedInstanceState);
    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
    }

    this.intialiseViewPager();
}

protected void onSaveInstanceState(Bundle outState) {
    outState.putString("tab", mTabHost.getCurrentTabTag());
    super.onSaveInstanceState(outState);
}

private void intialiseViewPager() {

    List<Fragment> fragments = new Vector<Fragment>();
    fragments.add(Fragment.instantiate(this, Pirveli.class.getName()));
    fragments.add(Fragment.instantiate(this, Meore.class.getName()));


    this.mPagerAdapter = new PagerAdapter(
            super.getSupportFragmentManager(), fragments);
    //
    this.mViewPager = (ViewPager) super.findViewById(R.id.viewpager);
    this.horizontalScrollView = (HorizontalScrollView) super
            .findViewById(R.id.horizontalScrollView);
    this.mViewPager.setAdapter(this.mPagerAdapter);
    this.mViewPager.setOnPageChangeListener(this);
}

public void centerTabItem(int position) {
    mTabHost.setCurrentTab(position);
    final TabWidget tabWidget = mTabHost.getTabWidget();
    final int screenWidth = getWindowManager().getDefaultDisplay()
            .getWidth();
    final int leftX = tabWidget.getChildAt(position).getLeft();
    int newX = 0;

    newX = leftX + (tabWidget.getChildAt(position).getWidth() / 2)
            - (screenWidth / 2);
    if (newX < 0) {
        newX = 0;
    }
    horizontalScrollView.scrollTo(newX, 0);
}

private void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();
    TabInfo tabInfo = null;
    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("All Channels").setIndicator(
                    "All Channels"), (tabInfo = new TabInfo("All Channels",
                    Pirveli.class, args)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

    MainActivity.AddTab(
            this,
            this.mTabHost,
            this.mTabHost.newTabSpec("Commersant").setIndicator(
                    "Commersant"), (tabInfo = new TabInfo("Commersant",
                    Meore.class, args)));



    mTabHost.setOnTabChangedListener(this);
}

private static void AddTab(MainActivity activity, TabHost tabHost,
        TabHost.TabSpec tabSpec, TabInfo tabInfo) {

    tabSpec.setContent(activity.new TabFactory(activity));
    tabHost.addTab(tabSpec);
}

public void onTabChanged(String tag) {

    int pos = this.mTabHost.getCurrentTab();
    this.mViewPager.setCurrentItem(pos);
}

@Override
public void onPageScrolled(int position, float positionOffset,
        int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {

    centerTabItem(position);
}

@Override
public void onPageScrollStateChanged(int state) {

}

private class TabInfo {
    private String tag;
    private Class<?> clss;
    private Bundle args;
    private Fragment fragment;

    TabInfo(String tag, Class<?> clazz, Bundle args) {
        this.tag = tag;
        this.clss = clazz;
        this.args = args;
    }

}

class TabFactory implements TabContentFactory {

    private final Context mContext;

    public TabFactory(Context context) {
        mContext = context;
    }

    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }

}

}

这是我的第一个片段code

this is a my first fragment code

public class Pirveli extends Fragment {
private String URL = "***********************";

public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;

public JSONParser jsonparser;
static DealBoxAdapter adapter;
ProgressDialog pDialog, pDialog1;

ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();

private int screenSize;
private LoadDataAllChanelsToServer loader;
public static String dateTime;

public TextView journal, tittle, description, smalllink, DateTime,
        smallstatID;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.send_items, container, false);
    list = (ListView) rootView.findViewById(R.id.pirvelilistview);

    // pd = new TransparentProgressDialog(getActivity(), R.drawable.loader);
    screenSize = getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK;
    loader = new LoadDataAllChanelsToServer();
    loader.execute();

    return rootView;
}

private class LoadDataAllChanelsToServer extends
        AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {

        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Authenticating user...");
        pDialog.show();
        // pd.show();
    }

    @Override
    protected String doInBackground(String... urls) {

        jsonparser = new JSONParser();

        JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
        try {

            jsonarray = jsonobject.getJSONArray("data");

            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                HashMap<String, String> map = new HashMap<String, String>();

                map.put("journal", jsonobject.getString(KEY_journal));
                map.put("image", jsonobject.getString(KEY_image));
                map.put("title", jsonobject.getString(KEY_title));
                map.put("description",
                        jsonobject.getString(KEY_description));
                map.put("JournalID", jsonobject.getString(KEY_JournalID));
                map.put("pubDate", jsonobject.getString(KEY_pubDate));
                map.put("statID", jsonobject.getString(KEY_statID));

                itemList.add(map);
                dateTime = itemList.get(itemList.size() - 1).get(
                        KEY_pubDate);

            }

        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        return itemList.toString();

    }

    @Override
    protected void onPostExecute(String result) {
        try {
            if (pDialog != null) {
                pDialog.dismiss();

            }
        } catch (Exception e) {

        }

        try {
            adapter = new DealBoxAdapter(getActivity(), itemList,
                    screenSize);
            adapter.notifyDataSetChanged();
            list.setAdapter(adapter);

        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

}

@Override
public void onDestroy() {
    super.onDestroy();
    try {
        if (loader != null) {
            loader.cancel(true);
            loader = null;
        }
    } catch (Exception e) {

    }

}

}
和第二个片段的code

}and second fragment's code

public class Meore extends Fragment {
private String URL = "*************************";

public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;
public TransparentProgressDialog pd;
public JSONParser jsonparser;
static DealBoxAdapter adapter;
ProgressDialog pDialog, pDialog1;

ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();


private int screenSize;

LoadDataAllChanelsToServer1 load;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.recived_items, container,
            false);
    list = (ListView) rootView.findViewById(R.id.listView2);
    pd = new TransparentProgressDialog(getActivity(), R.drawable.loader);
    screenSize = getResources().getConfiguration().screenLayout
            & Configuration.SCREENLAYOUT_SIZE_MASK;
    load = new LoadDataAllChanelsToServer1();
    return rootView;
}

private class LoadDataAllChanelsToServer1 extends
        AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {

        pd.show();
    }

    @Override
    protected String doInBackground(String... urls) {

        jsonparser = new JSONParser();

        JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
        try {

            jsonarray = jsonobject.getJSONArray("data");

            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                HashMap<String, String> map = new HashMap<String, String>();

                map.put("journal", jsonobject.getString(KEY_journal));
                map.put("image", jsonobject.getString(KEY_image));
                map.put("title", jsonobject.getString(KEY_title));
                map.put("description",
                        jsonobject.getString(KEY_description));
                map.put("JournalID", jsonobject.getString(KEY_JournalID));
                map.put("pubDate", jsonobject.getString(KEY_pubDate));
                map.put("statID", jsonobject.getString(KEY_statID));

                itemList.add(map);

            }

        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }

        return itemList.toString();

    }

    @Override
    protected void onPostExecute(String result) {
        try {
            if (pd != null) {
                pd.dismiss();

            }
        } catch (Exception e) {

        }

        try {
            adapter = new DealBoxAdapter(getActivity(), itemList,
                    screenSize);
            list.setAdapter(adapter);

        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }

}

@Override
public void setMenuVisibility(final boolean visible) {
    super.setMenuVisibility(visible);
    if (visible) {
        load.execute();
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    try {
        if (load != null) {
            load.cancel(true);
            load = null;
        }
    } catch (Exception e) {

    }

}

}
我logcat的错误是:java.lang.illegalStateException:无法执行任务:任务已经执行(在第二片段的setMenuVisibility法)

}my logcat error is : java.lang.illegalStateException: Cannot execute task:the task has already been executed (in second fragments's setMenuVisibility method)

推荐答案

试试这个code:

if (visible) {
    new LoadDataAllChanelsToServer1().execute();
    //load.execute();
}

而不是:

if (visible) {
    load.execute();
}

这篇关于Android的两个片段的AsyncTask类nullpointexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:16