Asynctask result

Asked

Viewed 72 times

0

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

I need to run between asa Activity s the following operation, when clicking the button, the application sends information to a php page, which from that information generates a Query, validates the data and creates a JSON file on the server, then the application takes this file and reads the JSON file.

Currently, I can send the information to a PHP that generates JSON and I can also read the JSON file, but I cannot run both functions in sequence in the application. Someone has a view of how to run this process with Asynctask or other 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);
}

In case it is not well detailed, let me know that I will add more information.

  • You want to generate a JSON with the data sent by the client (from Android)? '-'

  • No, I edited my question to specify better

  • It’s not clear yet.

  • It’s still very broad. Is this data generated in a database or would you extract it from a website? What you have tried to do (code interface) to generate this data?

  • For example, I send the code "1" to a php page, which will generate the JSON file, after generating the JSON file, I will read this file by the application and present the file data to the user. In case there is an easier way to send/receive data between an application and webservice, we welcome the answer..

  • Gabriel take a look here, much easier and you don’t even have to do the async https://github.com/koush/ion#get-json

  • would not just pass Query to webservice?

  • No, I need to pass only one parameter to my PHP that already does the Query and receive a JSON back from PHP to load into the App.

Show 3 more comments

1 answer

1


Simplest form:

Create a connection name class 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 her in 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

    }
}
}

Right after your upload you get the answer in onPostExecute, the answer is in the String result. This way in addition to sending and receiving in simpler ways, you decrease the amount of codes in your project

  • Man, I was gonna do this way just missed fitting one thing into Mainactivity.. Thank you, mythed!!

  • @Gabrielhenrique vlw kkk

Browser other questions tagged

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