Java 在片段中使用异步任务时如何避免应用程序崩溃?

Java 在片段中使用异步任务时如何避免应用程序崩溃?,java,android,Java,Android,我正在尝试使用选项卡滑动在网格视图中显示图像。但当包含异步任务从json URL获取图像时,应用程序甚至不会启动。它只是崩溃和关闭。这是我的密码 import android.support.v4.app.Fragment; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.La

我正在尝试使用选项卡滑动在网格视图中显示图像。但当包含异步任务从json URL获取图像时,应用程序甚至不会启动。它只是崩溃和关闭。这是我的密码

import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class GamesFragment extends Fragment {
public GamesFragment(){}

// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> items;
private Button button;
static String CATEGORY = "category";
int setlimit = 6;
int tolimit = 5;

static String IMAGE = "image";




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

    View rootView = inflater.inflate(R.layout.gridview_main, container, false);

   new DownloadJSON().execute();
    return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(getActivity());
        // Set progressdialog title
        mProgressDialog.setTitle("Student Government App");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions
                .getJSONfromURL
                        ("http://jsonurl.com");

        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("wallpaper");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects

                map.put("category", jsonobject.getString("category"));

                map.put("image", jsonobject.getString("image"));
                // Set the JSON Objects into the array
                arraylist.add(map);

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

    @Override
    protected void onPostExecute(Void args) {

        gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
        // Pass the results into ListViewAdapter.java
        adapter = new GridViewAdapter(getActivity(), arraylist);

        gridview.setAdapter(adapter);

        mProgressDialog.dismiss();
    }
}

}
导入android.support.v4.app.Fragment;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.Button;
导入android.widget.GridView;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.util.ArrayList;
导入java.util.HashMap;
公共类游戏片段扩展片段{
公共游戏片段(){}
//声明变量
JSONObject JSONObject;
JSONArray JSONArray;
GridView;
GridViewAdapter;
进程对话框;
ArrayList ArrayList;
数组列表项;
私人按钮;
静态字符串CATEGORY=“CATEGORY”;
int setlimit=6;
int-tolimit=5;
静态字符串IMAGE=“IMAGE”;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.gridview\u main,container,false);
新建下载JSON().execute();
返回rootView;
}
//下载JSON异步任务
私有类下载JSON扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//创建一个progressdialog
mProgressDialog=newprogressdialog(getActivity());
//设置进程对话框标题
mProgressDialog.setTitle(“学生政府应用程序”);
//设置进程对话框消息
设置消息(“加载…”);
mProgressDialog.setUndeterminate(false);
//显示进度对话框
mProgressDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
//创建一个数组
arraylist=新的arraylist();
//从给定的URL地址检索JSON对象
jsonobject=JSONfunctions
.getJSONfromURL
("http://jsonurl.com");
试一试{
//在JSON中找到数组名称
jsonarray=jsonobject.getJSONArray(“壁纸”);
for(int i=0;i
如何防止应用程序崩溃?任何帮助都会很好

Logcat:

    07-03 15:22:36.692      838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-    AM_ON_PAUSE_CALLED ActivityRecord{41353570 token=android.os.BinderProxy@41352cb0  {info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity}}
07-03 15:22:36.707      838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-PAUSE_ACTIVITY_FINISHING handled : 0 / android.os.BinderProxy@41352cb0
07-03 15:22:36.904      838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.944      838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:36.989      838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.003      838-838/info.androidhive.tabsswipe E/WindowManager﹕ Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4136f300 that was originally added here
    android.view.WindowLeaked: Activity info.androidhive.tabsswipe.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4136f300 that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:418)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:294)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:226)
            at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:151)
            at android.view.Window$LocalWindowManager.addView(Window.java:547)
            at android.app.Dialog.show(Dialog.java:277)
            at info.androidhive.tabsswipe.GamesFragment$DownloadJSON.onPreExecute(GamesFragment.java:65)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
            at android.os.AsyncTask.execute(AsyncTask.java:534)
            at info.androidhive.tabsswipe.GamesFragment.onCreateView(GamesFragment.java:48)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
            at android.view.View.measure(View.java:15264)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:15264)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
            at android.view.View.measure(View.java:15264)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4918)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at  com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2161)
            at android.view.View.measure(View.java:15264)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2131)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1242)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1435)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1127)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4609)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
            at android.view.Choreographer.doCallbacks(Choreographer.java:567)
            at android.view.Choreographer.doFrame(Choreographer.java:536)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:4987)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)
07-03 15:22:37.004      838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 0)
07-03 15:22:37.004      838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-DESTROY_ACTIVITY handled : 1 / android.os.BinderProxy@41352cb0
07-03 15:22:37.004      838-838/info.androidhive.tabsswipe D/OpenGLRenderer﹕ Flushing caches (mode 1)
Logcat:
07-03 15:22:36.692 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-AM_ON_PAUSE_称为ActivityRecord{41353570 token=android.os。BinderProxy@41352cb0{info.androidhive.tabsswipe/info.androidhive.tabsswipe.MainActivity}
07-03 15:22:36.707 838-838/info.androidhive.tabsswipe D/ActivityThread﹕ ACT-PAUSE\u活动\u完成处理:0/android.os。BinderProxy@41352cb0
07-03 15:22:36.904 838-838/info.androidhive.tabsswipe D/opengl﹕ 正在刷新缓存(模式0)
07-03 15:22:36.944 838-838/info.androidhive.tabsswipe D/opengl﹕ 正在刷新缓存(模式0)
07-03 15:22:36.989 838-838/info.androidhive.tabsswipe D/opengl﹕ 正在刷新缓存(模式0)
07-03 15:22:37.003 838-838/info.androidhive.tabsswipe E/WindowManager﹕ Activity info.androidhive.tabsswipe.main活动已泄漏窗口com.android.internal.policy.impl.PhoneWindow$DecorView@4136f300原来是加在这里的
android.view.WindowLeaked:Activity info.androidhive.tabsswipe.main活动泄漏了window com.android.internal.policy.impl.PhoneWindow$DecorView@4136f300原来是加在这里的
在android.view.ViewRootImpl。(ViewRootImpl.java:418)
在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:294)
在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:226)
在android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:151)中
在android.view.Window$LocalWindowManager.addView(Window.java:547)
在android.app.Dialog.show上(Dialog.java:277)
位于info.androidhive.tabsswipe.GamesFragment$DownloadJSON.onPreExecute(GamesFragment.java:65)
位于android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
在android.os.AsyncTask.execute(AsyncTask.java:534)
位于info.androidhive.tabsswipe.GamesFragment.onCreateView(GamesFragment.java:48)
位于android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
位于android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
位于android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
位于android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
位于android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
位于android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
在android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)上
在
 gridview = (GridView) rootview.findViewById(R.id.gridViewCustom);
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.gridview_main, container, false);
           gridview = (GridView) rootView.findViewById(R.id.gridViewCustom);
       new DownloadJSON().execute();
        return rootView;
    }

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
                   ProgressDialog progressDialog = null;

                    @Override
                    protected void onPreExecute() {
                        progressDialog = new ProgressDialog(getActivity());
                        progressDialog.setMessage("Loading , Please wait...");
                        progressDialog.setIndeterminate(true);
                        progressDialog.setCancelable(false);
                        progressDialog.setCanceledOnTouchOutside(false);
                        progressDialog.show();

                        super.onPreExecute();
                    }
 @Override
    protected void onPostExecute(Void args) {
         mProgressDialog.dismiss();
        gridview = (GridView) getView().findViewById(R.id.gridViewCustom);
        // Pass the results into ListViewAdapter.java
        adapter = new GridViewAdapter(getActivity(), arraylist);

        gridview.setAdapter(adapter);

       super.onPostExecute(arg);
    }