henrique romao
henrique romao

Reputation: 560

Pass parameter to a URL AsyncTask android

I'm developing an app and now I have to pass a parameter to a RESTful Service's URL.
I'm using AsyncTask, and I need to pass a text from a list view as a parameter to the URL, for example:
the URL is http://ip:7001/product?product_name=PARAM
I need to get the text from the selected item from my list view, and pass as a parameter in PARAM, using AsyncTask.
I've already got the text from the item in the listView, now I just need to pass it as a parameter.

This is my AsycTask class:

package com.tumta.henrique.teste;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.tumta.henrique.teste.ProdutoFragment;

/**
 * Created by Henrique on 18/05/2015.
 */
public class FiltraProduto extends AsyncTask<String, Void, List<String>> {

    private ConsultaConcluidaFiltroProdutoListener listener;

    public static String URL_STRING = "http://192.168.0.20:7001/com.henrique.rest/api/v1/status/pro_filtro?pro_nome=";

    public FiltraProduto(ConsultaConcluidaFiltroProdutoListener listener) {
        this.listener = listener;
    }





    private List<String> InterpretaResultado(String resultado) throws JSONException {
        JSONObject object = new JSONObject(resultado);
        JSONArray jsonArray = object.getJSONArray("produto");
        //JSONObject jsonProduto = jsonArray.getJSONObject(0);
       // String id = jsonProduto.getString("pro_id");
        //proId = id;
        List<Object> listaNomes = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonProdutoInfo = jsonArray.getJSONObject(i);
            String proNome= jsonProdutoInfo.getString("pro_nome");
            double proPreco = jsonProdutoInfo.getDouble("pro_preco");
            double proSdAtual = jsonProdutoInfo.getDouble("pro_sdAtual");
            listaNomes.add(i, proNome);
            listaNomes.add(i, proPreco);
            listaNomes.add(i, proSdAtual);
        }
        List<String> strings = new ArrayList<String>();
        for (Object o : listaNomes) {
            strings.add(o != null ? o.toString() : null);
        }
        return strings;
    }

    private String ConsultaServidor() throws IOException {
        InputStream is = null;

        try {
            URL url = new URL(URL_STRING);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            conn.getResponseCode();

            is = conn.getInputStream();

            Reader reader = null;
            reader = new InputStreamReader(is);
            char[] buffer = new char[2048];
            reader.read(buffer);
            return new String(buffer);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    @Override
    protected List<String> doInBackground(String... params) {
        try {
            String resultado = ConsultaServidor();
            return InterpretaResultado(resultado);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(List<String> result) {
        listener.onConsultaConcluida(result);
        super.onPostExecute(result);
    }


    public interface ConsultaConcluidaFiltroProdutoListener {
        void onConsultaConcluida(List<String> result);
    }
}

In the URL_STRING I need to pass the param at pro_nome=?

Here I get the item text. This is in my Fragment that has the List View:

 public String retornaParam(String param){
        return param;
    }

    @Override
    public void onConsultaConcluida(List<String> result) {
        final ListView listaProdutos = (ListView) getView().findViewById(R.id.listaprodutos);
        ArrayAdapter arrayAdapter = new ArrayAdapter<>(getView().getContext(),android.R.layout.simple_list_item_1, result);
        listaProdutos.setAdapter(arrayAdapter);
        listaProdutos.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
                                    long id) {
                String nomeProduto = listaProdutos.getItemAtPosition(position).toString();
                retornaParam(nomeProduto);
                Intent intent = new Intent(getActivity(), DetalhesProdutoActivity.class);
                //intent.putExtra("pro_nome", listaProdutos.getItemAtPosition(position).toString());
                startActivity(intent);
            }
        });
    }

I get the text and store it in param from the retornaParam method.
Does somebody know how to do it?
If you need more information, just let me know.

Upvotes: 0

Views: 1928

Answers (2)

Greg T
Greg T

Reputation: 3404

You pass in params to an AsyncTask using:

YourAsyncTask.execute(yourview.getText(), "and", "more", "params");

You can then access them in

@Override
protected String doInBackground(String... params) {
URL_STRING += params[0];
...

Upvotes: 1

Just add the following code before sending executing your httpClient:

URL_STRING + = textInsideYourTextView;

It should work, just avoid to manipulate your ui elements outside your UI thread.

Upvotes: 0

Related Questions