PDA

Ver la Versión Completa : Cierre forzado sin internet


portal47
12/05/15, 16:57:39
Hola, estoy haciendo una app en la que tomo datos de un JSON y los muestra en el mainactivity pero cuando no estoy conectado a Internet la aplicación se cierra

Mi MainActivity:
package com.androidbegin.jsonparsetutorial;

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.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 TITLE = "title";
static String PLACE = "place";
static String DATE = "date";
static String FLAG = "imagen";

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 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://cmx.org.mx/wp-content/uploads/json.txt");

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

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("title", jsonobject.getString("title"));
map.put("place", jsonobject.getString("place"));
map.put("date", jsonobject.getString("date"));
map.put("imagen", jsonobject.getString("imagen"));
// 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();
}
}
}

y mi JSONfunctions:
package com.androidbegin.jsonparsetutorial;

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

soy nuevo en android y en java, no se si me falte poner otro de los .java

kohario88
12/05/15, 17:17:23
Se cierra porque le pides que haga algo que no puedo hacer. es como si te digo que corras sin mover las piernas. Haz un condicionante que compruebe si tienes conexion a internet y si es asi que lo haga. si no, que te muestre un toast advirtiendote de que no se puede conectar o algo asi.

portal47
12/05/15, 17:37:27
Soy nuevo en esto, donde lo tendría que poner? lo intente hacer en el main pero no aparecía nada

kriogeN
12/05/15, 20:11:25
Fácil, si después de esta línea:

jsonobject = JSONfunctions
.getJSONfromURL("http://cmx.org.mx/wp-content/uploads/json.txt");

jsonobject es NULL, es que ha habido algún error conectando con la URL.

kaiser75
12/05/15, 23:04:34
Yo solucione algo parecido poniendo una condicion como dice kohario88.

portal47
12/05/15, 23:51:59
yo lo intente de varias formas y no me sale:cry:

Zwart Apps
03/07/15, 21:05:42
Amigo a mi me ha pasado lo mismo, pero era por culpa de los anuncios de admob........en el código de admob tenía que estar contectado para poder ver los ads sino la app se cerraba nada más abrir.... :O
no sé si tienes algo de eso en tu codigo?

saludos