没有互联网连接时,应用程序崩溃

时间:2016-05-14 23:28:01

标签: android json listview

我得到了所有的json解析请求,但是现在当我在我的设备中禁用所有互联网时,当我启动它时它会崩溃并且说'#34; app已停止工作"

现在我的问题是这个,我应该在我的代码中添加一个例外,说明"你没有互联网连接来使用这个应用程序"和一个按钮,说"再试一次"所以人们按下按钮,应用程序再次重新加载

先谢谢我,让我在这里开展我的主要活动

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String FLAG = "flag";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }




    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Actualizando Información");
            // Set progressdialog message
            mProgressDialog.setMessage("Cargando...");
            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://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

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



                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("rank", jsonobject.getString("rank"));
                    map.put("country", jsonobject.getString("country"));
                    map.put("population", jsonobject.getString("population"));
                    map.put("flag", jsonobject.getString("flag"));
                    // 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) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

和我的JsonFunctions

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

由于

3 个答案:

答案 0 :(得分:1)

在OnCreate

中执行DownloadJson方法之前,请尝试检查是否有互联网

阅读here,了解如何检查您是否有互联网连接。

这是一个创建Snackbar的片段,告诉用户没有连接。

首先在strings.xml中添加一个字符串

boolean internet_connection(){
    //Check if connected to internet, output accordingly
    ConnectivityManager cm =
            (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
    return isConnected;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.listview_main);
    if (internet_connection()){
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }else{
        //create a snackbar telling the user there is no internet connection and issuing a chance to reconnect
        final Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), 
                                                  "No internet connection.", 
                                                    Snackbar.LENGTH_SHORT);
        snackbar.setActionTextColor(ContextCompat.getColor(getApplicationContext(),
                                      R.color.lime));
        snackbar.setAction(R.string.try_again, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //recheck internet connection and call DownloadJson if there is internet
            }
        }).show();
    }

}

如果没有互联网连接,请添加创建小吃栏,您的代码可能如下所示

{{1}}

希望这有帮助

答案 1 :(得分:0)

您的应用程序崩溃了,因为即使在捕获到异常并且InputStream为空之后您仍继续执行代码。

快速解决方法是在所有三个catch块中返回null

onPostExecute()中,检查结果是否为null,这意味着doInBackground()发生了错误。

然而,这并不能让你知道发生了什么样的错误(是网络错误吗?是解析错误吗?)

我的建议是使用可以为您处理大部分工作的HTTP库。 Retrofit是一个不错的选择。

答案 2 :(得分:0)

处理此问题的最佳和最简单的解决方案是在异步任务中的onPost execute()中使用try catch块。像这样

    @Override
    protected void onPostExecute(String s) {
        try {
            super.onPostExecute(s);
            loading.dismiss();
        }catch (Exception ex){
            Toast.makeText(UserLogin.this, "Something is going wrong, please try again!", Toast.LENGTH_LONG).show();
        }
    }

这样可以防止您的应用崩溃。