Android app closes when connecting to Mysql

Asked

Viewed 136 times

1

I’m developing an application for Android that needs to connect to my database on Locaweb servers. However, as it is in the code, the class closes if it cannot connect to the server. Am I making the connection wrong?

Follow the code of the class:

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.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;

import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


/**
 * Desenvolvido por Willian Fernando da Cunha a partir 22/10/2015.
 */

public class Recupera extends ActionBarActivity {

private String jsonResult;
private ProgressDialog pDialog;
private List<Lista> customList;
private ListView lv;
private String url = "URL DO SITE(NÃO DIVULGADO)";
private String[] prices;


@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.recupera);
    lv = (ListView)findViewById(R.id.listView);
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    boolean connected = ni != null && ni.isAvailable() && ni.isConnectedOrConnecting();
    if(connected){
        if(ni.getType() == ConnectivityManager.TYPE_WIFI || ni.getType() == ConnectivityManager.TYPE_MOBILE){
            //Carrega conteúdo.
            startWebService();
        }else{
            DialogMessageDisplay.displayWifiSettingsDialog(Recupera.this, Recupera.this, "Você está desconectado!", "Erro ao carregar. Por favor, verifique sua conexão com a internet.", AlertDialog.THEME_DEVICE_DEFAULT_DARK);
        }

    }
}



public class JsonReadTast extends AsyncTask<String, Void, String>{

    public JsonReadTast(){
        super();
    }

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pDialog = new ProgressDialog(Recupera.this);
        pDialog.setTitle("Aguarde...");
        pDialog.setMessage("Carregando...");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override
    protected String doInBackground(String... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(params[0]);
        try{
            HttpResponse response = httpClient.execute(httpPost);
            jsonResult = inputStreamToString(response.getEntity().getContent()).toString();

        }catch(Exception e){
            Recupera.this.finish();
        }
        return null;

    }

    private StringBuilder inputStreamToString(InputStream is){
        String line = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try{
            while ((line = rd.readLine()) != null){
                answer.append(line);
            }
        } catch (IOException ex) {
            Recupera.this.finish();
        }
        return answer;
    }

    @Override
    protected void onPostExecute(String s){
        ListDrawer();
        pDialog.dismiss();
        }
}//Finaliza a task de Async.

public void startWebService(){
    JsonReadTast task = new JsonReadTast();
    task.execute(new String[]{url});
}

private void ListDrawer() {
    customList = new ArrayList<>();
    try{
        JSONObject jsonResponse = new JSONObject(jsonResult);
        JSONArray jsonMain = jsonResponse.optJSONArray("metoxes");
        for(int i=0; i<jsonMain.length(); i++){
            JSONObject jsonChild = jsonMain.getJSONObject(i);

            String name = jsonChild.optString("name");
            String price = jsonChild.optString("price");
            String image = jsonChild.optString("image");
            String prices1 = jsonChild.getString("price1");
            String prices2 = jsonChild.getString("price2");
            String prices3 = jsonChild.getString("price3");
            String prices4 = jsonChild.getString("price4");

            prices = new String[]{prices1, prices2, prices3, prices4};

            customList.add(new Lista(name, price, image, prices));
        }
    }catch (Exception ee){
        Recupera.this.finish();
    }

    ArrayAdapter adapter = new Atualizador(Recupera.this, R.layout.list_items, customList);
    adapter.notifyDataSetChanged();
    lv.setAdapter(adapter);
}

}

1 answer

0


The problem is here:

try {
    HttpResponse response = httpClient.execute(httpPost);
    jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch(Exception e) {
    Recupera.this.finish();
}

The call to Recupera.this.finish() within the exception terminates the Activity Recupera when there is an error. Within the Try-catch block you should treat the error properly what you are doing at the moment. In this specific case, you can implement a warning to the user when the request goes wrong. Another thing that’s not quite right is the catch(Exception e). Exceptions should not be picked up this way. It has to be more granular and catch only those that can be fired by the code block inside the try.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.