2016-05-14 109 views
1

我把所有我的JSON解析请求的工作,但现在当我关闭所有的互联网在我的设备,当我启动它崩溃并说:“应用程序已停止工作”应用程序崩溃的时候没有互联网连接可用

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

在先进的感谢我让你我的主要活动在这里

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; 
    } 
} 

感谢

+0

您需要首先检查ConnectionManager的连接状态 - http://stackoverflow.com/a/2326816/4252352 –

+0

什么是logcat? – Vucko

回答

0

尝试检查是否有你的OnCreate

阅读here如何检查是否有互联网连接执行你的DownloadJson方法之前互联网。

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

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

<string name="try_again">Reconnect</string> 

并添加创建一个小吃吧,如果没有互联网连接,你的代码可能看起来像这样

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(); 
    } 

} 

希望这有助于

0

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

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

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

但是,不会真的让你知道什么样的错误发生了(它是一个网络错误?是它解析错误?)

我的建议是使用一个能够处理大多数的HTTP库为你工作。 Retrofit是一个不错的选择。

相关问题