Result AsyncTask

0

I have rephrased the question again to try to better clarify the need for my situation:

I need to run between the following activity's activityaa, by clicking the button, the application sends an information to a php page, which from this information generates a Query, validates the data and creates a JSON file on the server, then the application takes this file and le the JSON file.

I can now send the information to a PHP that generates JSON and I can also read the JSON file, but I can not run the two functions in sequence in the application . Someone has a vision of how to run this process with AsyncTask or another native Android class.

Below the code I retrieve the information in the JSON file that is saved on the server.

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

Context context;

public BackGroundWorkerItensActivity(Context context){
    this.context = context;
}

@Override
protected String doInBackground(String... params) {

    String iddist = params[0];

    String url_receber = "http://minhaurl.com/teste/dados.json";

    try {
        URL url = new URL(url_receber);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
        String result="";
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            result += line;
        }
        bufferedReader.close();
        inputStream.close();
        httpURLConnection.disconnect();
        return result;
    } catch (IOException e) {
        Log.i("DadosDist", "Erro na lista dos itens!");
        e.printStackTrace();
    }

    return null;
}
@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    Intent intentLD = new Intent(context, MainActivity.class);
    Log.i("Vem JSON", s);
    intentLD.putExtra("JSON", s);
    context.startActivity(intentLD);
}

If it is not well detailed, let me know what I will add more information.

    
asked by anonymous 16.03.2018 / 01:28

1 answer

1

Simplest form:

Create a class with connection name as follows:

public class Conexao {

public static String postDados(String urlUsuario, String parametrosUsuario) {
    URL url;
    HttpURLConnection connection = null;

    try {

        url = new URL(urlUsuario);
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        connection.setRequestProperty("Content-Lenght", "" + Integer.toString(parametrosUsuario.getBytes().length));

        connection.setRequestProperty("Content-Language", "pt-BR");

        //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Envio
        OutputStreamWriter outPutStream = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        outPutStream.write(parametrosUsuario);
        outPutStream.flush();
        outPutStream.close();
        //Recepção
        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

        String linha;
        StringBuffer resposta = new StringBuffer();

        while((linha = bufferedReader.readLine()) != null) {
         resposta.append(linha);
            resposta.append('\r');
        }

        bufferedReader.close();

        return resposta.toString();

    } catch (Exception erro) {

        return  null;
    } finally {

        if(connection != null) {
            connection.disconnect();
        }
    }
}
}

To call it on your project do:

public class main extends AppCompatActivity {

String url = "";
String parametros = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Se fosse um get bastava colocar no final da string url o ?nome=seuget
    url = "url do arquivo php";

    //parâmetros do post
    parametros = "texto=" + "123";

    new main.solicita().execute(url);

   }

    private class solicita extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        return Conexao.postDados(urls[0], parametros);
    }

    @Override
    protected void onPostExecute(String resultado) {

        //A string resultado tem os dados vindos do seu arquivo php

    }
}
}

Soon after your submission you get the answer in the onPostExecute, the answer is in the String result. That way, in addition to sending and receiving in simpler ways, you decrease the number of codes in your project

    
19.03.2018 / 14:41