Android项目崩溃中具有多个AsyncTask类的多个片段

时间:2018-07-25 01:02:33

标签: android android-fragments android-asynctask

我正在开发一个Tabbed Android项目,其中有2个包含2个AsyncTask类的片段。在片段1中,它要求其中的一个AsyncTask类从URL中获取JSON;在片段2中,它调用驻留在该片段中的另一个AsyncTask类,以从URL中获取另一个JSON,这现在导致应用程序运行时崩溃。因此,如何能够同时运行来自两个不同Fragment的两个AsyncTask类?请帮忙!这是这两个片段的代码片段...

Tab2Fragment.java

public class Tab2Fragment extends Fragment {

SharedPreferences sharedPreferences;
private static boolean jsonExists = false;

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

private static final String TAG_LIST = "Shelter List";
private static final String TAG_TYPE = "Image";
private static final String TAG_NAME = "Name";
private static final String TAG_COORDINATE = "Coordinate";
private static final String TAG_IMG = "Img";

View view;
ListView list;
JSONArray mapArray = null;

boolean connected = false;

String[] from = new String[]{ TAG_NAME, TAG_TYPE, TAG_COORDINATE, TAG_IMG };
int[] to = new int[]{R.id.name, R.id.type, R.id.coordinate, R.id.lvimage };

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


    view = inflater.inflate(R.layout.tab2_fragment, container, false);

    if (isOnline()) {

        connected = true;

        //new JSONParse().execute();
        new JSONParse().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } else {
        connected = false;

        if (jsonExists) {
            Toast.makeText(getContext(), "No Internet Connection! " +
                    "Please, turn on internet connection to get updated data!!", Toast.LENGTH_SHORT).show();

            //new JSONParse().execute();
            new JSONParse().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        } else {

            view = inflater.inflate(R.layout.tab2_fragment, container, false);

            Toast.makeText(getContext(), "No Internet Connection! " +
                    "Please, turn on internet connection to get going!!", Toast.LENGTH_SHORT).show();

        }
    }

    return view;
}

private class JSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(getContext());
        pDialog.setMessage("Getting Updated Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        JsonParser jParser = new JsonParser();
        JSONObject json;

        if (connected) {

            // Getting JSON from URL
            //JSONObject json = jParser.getJSONFromUrl(url);

            String url;

            // Getting Current District Name from Globals class
            String myCurrentLocation = ((Globals) getActivity().getApplication()).getCurrentLocation();

            if (myCurrentLocation == null) {

                url = "http://192.168.1.126/json_files/parser_ex.json";

                Log.i("Current URL Name: ", url);

            } else {

                String[] parts = myCurrentLocation.split("\\ ");
                String url_name = parts[0];

                url = "http://192.168.1.126/json_files/"+url_name+".json";

            }

            Log.i("Current URL Name: ", url);
            json = jParser.getJSONFromUrl(url);

        } else {

            if (jsonExists) {

                // Getting JSON from SharedPreferences                 
                String jsnString = getStringProperty("json");
                json = jParser.getJSONFromCache(jsnString);

                Log.i("JSON File", "String Array: "+jsnString);

            } else {

                Toast.makeText(getContext(), "No Internet Connection Available! "+
                        "Please, turn on the internet to get data!!", Toast.LENGTH_LONG);
                json = null;

            }

        }

        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {

        pDialog.dismiss();

        try {

            // Getting JSON Array from URL
            mapArray = json.getJSONArray(TAG_LIST);
            for (int i = 0; i < mapArray.length(); i++) {
                JSONObject c = mapArray.getJSONObject(i);

                // Storing JSON item in a Variable
                String name = c.getString(TAG_NAME);
                String type = c.getString(TAG_TYPE);
                String cod = c.getString(TAG_COORDINATE);

                // Adding value HashMap key => value
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_TYPE, type);
                map.put(TAG_NAME, name);
                map.put(TAG_COORDINATE, cod);

                if(type.startsWith("school")) {

                    Integer pic = R.drawable.school;
                    map.put(TAG_IMG, pic.toString());

                } else if(type.startsWith("hospital")) {

                    Integer pic = R.drawable.hospital;
                    map.put(TAG_IMG, pic.toString());

                } else if(type.startsWith("fscd")) {

                    Integer pic = R.drawable.fscd;
                    map.put(TAG_IMG, pic.toString());

                } else if(type.startsWith("ps")) {

                    Integer pic = R.drawable.ps;
                    map.put(TAG_IMG, pic.toString());

                } else if(type.startsWith("cs")) {

                    Integer pic = R.drawable.cs;
                    map.put(TAG_IMG, pic.toString());

                } else {

                    Integer pic = R.drawable.school;
                    map.put(TAG_IMG, pic.toString());

                }

                itemList.add(map);
                setStringProperty("json", String.valueOf(map));
                jsonExists = true;


                ListAdapter adapter = new SimpleAdapter(getContext(), itemList,
                        R.layout.map_data_list, from, to);

                list = (ListView) view.findViewById(R.id.mapData);
                list.setAdapter(adapter);

                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {

                        // Launching new Activity on selecting single List Item
                        Intent i = new Intent(getContext(), Tab2Activity.class);
                        // sending data to new activity
                        i.putExtra("coordinate", itemList.get(+position).get("Coordinate"));
                        startActivity(i);

                    }
                });

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

public String getStringProperty(String key) {

    sharedPreferences = this.getActivity().getSharedPreferences("preferences", Context.MODE_PRIVATE);
    String res = null;
    if (sharedPreferences != null) {
        res = sharedPreferences.getString(key, null);
    }


}

public void setStringProperty(String key, String value) {

    sharedPreferences = this.getActivity().getSharedPreferences("preferences", Context.MODE_PRIVATE);
    if (sharedPreferences != null) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();

    }
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}
}

Tab3Fragment.java

public class Tab3Fragment extends Fragment {

SharedPreferences sharedPreferences;
private static boolean jsonExists = false;

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

private static final String TAG_LIST = "Agro List";
private static final String TAG_TYPE = "Type";
private static final String TAG_TITLE = "Title";
private static final String TAG_SHORT_DESCRIPTION = "ShortDesc";
private static final String TAG_DESCRIPTION = "Description";
private static final String TAG_IMG = "Img";

View view;
ListView list;

JSONArray agroArray = null;

boolean connected = false;

String[] from = new String[]{ TAG_TITLE, TAG_TYPE, TAG_SHORT_DESCRIPTION, TAG_IMG };
int[] to = new int[]{R.id.agroTitle, R.id.agroType, R.id.agroShortTitle, R.id.agroImage };

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

    view = inflater.inflate(R.layout.tab3_fragment, container, false);

    if (isOnline()) {

        connected = true;

        //new AGROJSONParse().execute();
        new AGROJSONParse().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        //new AGROJSONParse().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } else {
        connected = false;

        if (jsonExists) {
            Toast.makeText(getContext(), "No Internet Connection! " +
                    "Please, turn on internet connection to get updated data!!", Toast.LENGTH_SHORT).show();

            //new AGROJSONParse().execute();
            new AGROJSONParse().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

        } else {

            view = inflater.inflate(R.layout.tab3_fragment, container, false);

            Toast.makeText(getContext(), "No Internet Connection! " +
                    "Please, turn on internet connection to get going!!", Toast.LENGTH_SHORT).show();

        }
    }



    return view;
}

private class AGROJSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        pDialog = new ProgressDialog(getContext());
        pDialog.setMessage("Getting Updated Agricultural Tips Data ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... args) {

        JsonParser jParser = new JsonParser();
        JSONObject json;

        if (connected) {

            // Getting JSON from URL

            String url;

            // Getting Current District Name from Globals class
            String myCurrentLocation = ((Globals) getActivity().getApplication()).getCurrentLocation();

            if (myCurrentLocation == null) {

                url = "http://192.168.1.126/json_files/parser_ex1.json";

                Log.i("Current URL Name: ", url);

            } else {

                String[] parts = myCurrentLocation.split("\\ ");
                String url_name = parts[0];
                url = "http://192.168.1.126/json_files/"+url_name+"_Agro.json";

            }

            Log.i("Current URL Name: ", url);
            json = jParser.getJSONFromUrl(url);

        } else {

            if (jsonExists) {

                // Getting JSON from SharedPreferences

                String jsnString = getStringProperty("json");
                json = jParser.getJSONFromCache(jsnString);

                Log.i("JSON File", "String Array: "+jsnString);

            } else {

                Toast.makeText(getContext(), "No Internet Connection Available! "+
                        "Please, turn on the internet to get data!!", Toast.LENGTH_LONG);
                json = null;                   
            }

        }

        return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {

        pDialog.dismiss();

        try {

            // Getting JSON Array from URL
            agroArray = json.getJSONArray(TAG_LIST);
            for (int i = 0; i < agroArray.length(); i++) {
                JSONObject c = agroArray.getJSONObject(i);

                // Storing JSON item in a Variable
                String name = c.getString(TAG_TITLE);
                String type = c.getString(TAG_TYPE);
                String shortDesc = c.getString(TAG_SHORT_DESCRIPTION);

                // Adding value HashMap key => value
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_TYPE, type);
                map.put(TAG_TITLE, name);
                map.put(TAG_SHORT_DESCRIPTION, shortDesc);

                if(type.startsWith("crops")) {

                    Integer pic = R.drawable.crops;
                    map.put(TAG_IMG, pic.toString());

                } else if(type.startsWith("cattle")) {

                    Integer pic = R.drawable.cattle;
                    map.put(TAG_IMG, pic.toString());

                } else if(type.startsWith("poultry")) {

                    Integer pic = R.drawable.poultry;
                    map.put(TAG_IMG, pic.toString());

                } else if(type.startsWith("fisheries")) {

                    Integer pic = R.drawable.fisheries;
                    map.put(TAG_IMG, pic.toString());

                } else {

                    Integer pic = R.drawable.crops;
                    map.put(TAG_IMG, pic.toString());

                }

                agroList.add(map);
                setStringProperty("json", String.valueOf(map));
                jsonExists = true;                    


                ListAdapter adapter = new SimpleAdapter(getContext(), agroList,
                        R.layout.agro_list_view, from, to);

                list = (ListView) view.findViewById(R.id.agroData);
                list.setAdapter(adapter);

                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {


                        // Launching new Activity on selecting single List Item
                        Intent i = new Intent(getContext(), Tab2Activity.class);
                        // sending data to new activity
                        i.putExtra("descriptionText", agroList.get(+position).get("Description"));
                        i.putExtra("shortDescriptionText", agroList.get(+position).get("ShortDesc"));
                        i.putExtra("titleText", agroList.get(+position).get("Title"));
                        startActivity(i);

                    }
                });

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

public String getStringProperty(String key) {

    sharedPreferences = this.getActivity().getSharedPreferences("preferences", Context.MODE_PRIVATE);
    String res = null;
    if (sharedPreferences != null) {
        res = sharedPreferences.getString(key, null);
    }


    return res;
}

public void setStringProperty(String key, String value) {

    sharedPreferences = this.getActivity().getSharedPreferences("preferences", Context.MODE_PRIVATE);
    if (sharedPreferences != null) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();            
    }
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}
}

我尝试从两个片段中删除AsyncTask.THREAD_POOL_EXECUTOR,也从两个doInBackground方法中删除Toast.show(),并且在我的应用崩溃时在运行时收到了这些错误消息。

Logcat消息

07-25 07:36:19.122 13478-13478/com.example.mehedi.mytab4 V/ActivityThread: updateVisibility : ActivityRecord{92a92cb token=android.os.BinderProxy@d84150f {com.example.mehedi.mytab4/com.example.mehedi.mytab4.MainActivity}} show : true
07-25 07:36:41.202 13478-13637/com.example.mehedi.mytab4 I/System.out: AsyncTask #1 calls detatch()
07-25 07:36:41.202 13478-13637/com.example.mehedi.mytab4 W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.126 refused
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:248)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:172)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:130)
07-25 07:36:41.212 13478-13637/com.example.mehedi.mytab4 W/System.err:     at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1337)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:705)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:578)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:494)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:472)
        at com.example.mehedi.mytab4.JsonParser.getJSONFromUrl(JsonParser.java:35)
        at com.example.mehedi.mytab4.Tab2Fragment$JSONParse.doInBackground(Tab2Fragment.java:170)
        at com.example.mehedi.mytab4.Tab2Fragment$JSONParse.doInBackground(Tab2Fragment.java:121)
        at android.os.AsyncTask$2.call(AsyncTask.java:295)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-25 07:36:41.222 13478-13637/com.example.mehedi.mytab4 W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
07-25 07:36:41.232 13478-13637/com.example.mehedi.mytab4 W/System.err: Caused by: java.net.ConnectException: failed to connect to /192.168.1.126 (port 80): connect failed: ETIMEDOUT (Connection timed out)
07-25 07:36:41.262 13478-13637/com.example.mehedi.mytab4 W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
07-25 07:36:41.312 13478-13637/com.example.mehedi.mytab4 W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
        at java.net.Socket.connect(Socket.java:884)
        at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:124)
07-25 07:36:41.322 13478-13637/com.example.mehedi.mytab4 W/System.err:     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:193)
        ... 16 more
    Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
        at libcore.io.Posix.connect(Native Method)
        at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
        at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
        at libcore.io.IoBridge.connect(IoBridge.java:122)
        ... 21 more
07-25 07:36:41.322 13478-13637/com.example.mehedi.mytab4 E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
07-25 07:36:41.332 13478-13637/com.example.mehedi.mytab4 E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
07-25 07:36:41.332 13478-13478/com.example.mehedi.mytab4 D/AndroidRuntime: Shutting down VM
07-25 07:36:41.332 13478-13478/com.example.mehedi.mytab4 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.mehedi.mytab4, PID: 13478
    java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
        at com.example.mehedi.mytab4.Tab2Fragment$JSONParse.onPostExecute(Tab2Fragment.java:206)
        at com.example.mehedi.mytab4.Tab2Fragment$JSONParse.onPostExecute(Tab2Fragment.java:121)
        at android.os.AsyncTask.finish(AsyncTask.java:651)
        at android.os.AsyncTask.access$500(AsyncTask.java:180)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:158)
        at android.app.ActivityThread.main(ActivityThread.java:7224)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

1 个答案:

答案 0 :(得分:0)

LogCat具有解决方案:“ java.net.ConnectException:无法连接到/192.168.1.126(端口80):连接失败:ETIMEDOUT(连接超时)”