Dúvida ao consumir web service rails

  • Respostas:0
  • AbertoNão stickySem resposta
  • Posts no fórum: 1

4/nov/2015 13:37:47 via Web

Olá, estou desenvolvimento um projeto de conclusão de curso.

Este possui um Web Service para consumir em android, meu problema está em passar o parâmetro que seria o ID para consumir e preencher a proxima intent.

Vejam o JSON que estou consumindo na primeira tela:
é uma estrutura de três níveis, Establishments>Menus>Items

{
"establishments": [
    {
        "id": 20,
        "name": "Restaurante Fictício",
        "city": "Jaraguá do Sul",
        "status": false,
        "menus": [
            {
                "id": 8,
                "data": "2015-10-27T02:50:00.000Z",
                "weekday": null,
                "price": "19,90 Livre",
                "status": true,
                "establishment_id": 20,
                "items": [
                    {
                        "id": 9,
                        "plate": "Arroz",
                        "status": false,
                        "menu_id": 8
                    },
                    {
                        "id": 10,
                        "plate": "Feijão",
                        "status": false,
                        "menu_id": 8
                    }
                ]
            },
            {
                "id": 7,
                "data": "2015-10-26T02:49:00.000Z",
                "weekday": null,
                "price": "19,90 Livre",
                "status": true,
                "establishment_id": 20,
                "items": []
            }
        ]
    }
]

}

A URL para este JSON é .../api/v1/establishments preciso então na intent menusListActivity fazer .../api/v1/establishments/20

Segue EstablishmentsActivity.class

package com.renaldoviola.cardapcommultilevel;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.renaldoviola.cardapcommultilevel.helper.AlertDialogManager;
import com.renaldoviola.cardapcommultilevel.helper.ConnectionDetector;
import com.renaldoviola.cardapcommultilevel.helper.JSONParser;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EstablishmentsActivity extends ListActivity {


    ConnectionDetector cd;

    AlertDialogManager alert = new AlertDialogManager();

    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> establishmentList;

    JSONArray establishments = null;

    private static final String URL_ESTABLISHMENTS = "...com/api/v1/establishments";

    private static final String TAG_ID           = "id";
    private static final String TAG_NAME         = "name";
    private static final String TAG_NEIGHBORHOOD = "neighborhood";
    private static final String TAG_ZIPCODE      = "zipcode";
    private static final String TAG_CITY         = "city";
    private static final String TAG_STATE        = "state";
    private static final String TAG_STATUS_EST   = "status";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_establishments);

        cd = new ConnectionDetector(getApplicationContext());

        if (!cd.isConnectingToInternet()) {
            alert.showAlertDialog(EstablishmentsActivity.this, "Sem conexão com internet",
                    "Por favor, conecte-se com a internet para visualizar os cardápios", false);

            return;
        }

        establishmentList = new ArrayList<HashMap<String, String>>();

        new LoadEstablishments().execute();

        ListView lv = getListView();

        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {

                Intent i = new Intent(getApplicationContext(), MenusListActivity.class);

                String establishment_id = ((TextView) view.findViewById(R.id.establishment_id)).getText().toString();
                i.putExtra("establishment_id", establishment_id);

                startActivity(i);
            }
        });
    }

    class LoadEstablishments extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EstablishmentsActivity.this);
            pDialog.setMessage("Listando estabelecimentos...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            String json = jsonParser.makeHttpRequest(URL_ESTABLISHMENTS, "GET",
                    params);

            Log.d("Establishments JSON: ", "> " + json);

            try {
                JSONObject jsonObj = new JSONObject(json);
                establishments = jsonObj.getJSONArray("establishments");

                if (establishments != null) {
                    for (int i = 0; i < establishments.length(); i++) {
                        JSONObject JOEstablishment = establishments.getJSONObject(i);

                        String name = JOEstablishment.optString(TAG_NAME);
                        String city = JOEstablishment.optString(TAG_CITY);
                        String neighborhood = JOEstablishment.optString(TAG_NEIGHBORHOOD);
                        String zipcode = JOEstablishment.optString(TAG_ZIPCODE);
                        String state = JOEstablishment.optString(TAG_STATE);
                        String status_est = JOEstablishment.optString(TAG_STATUS_EST);

                        HashMap<String, String> establishment = new HashMap<String, String>();

                        establishment.put(TAG_NAME, name);
                        establishment.put(TAG_CITY, city);
                        establishment.put(TAG_NEIGHBORHOOD, neighborhood);
                        establishment.put(TAG_ZIPCODE, zipcode);
                        establishment.put(TAG_STATE, state);
                        establishment.put(TAG_STATUS_EST, status_est);

                        establishmentList.add(establishment);
                    }
                }else{
                    Log.d("Establishments: ", "null");
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                    ListAdapter adapter = new SimpleAdapter(
                            EstablishmentsActivity.this, establishmentList,
                            R.layout.list_establishments, new String[] {TAG_ID,
                            TAG_NAME}, new int[] {
                            R.id.establishment_id, R.id.establishment_name});

                    setListAdapter(adapter);
                }
            });

        }

    }
}

MenuListActivity.class

package com.renaldoviola.cardapcommultilevel;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.renaldoviola.cardapcommultilevel.helper.AlertDialogManager;
import com.renaldoviola.cardapcommultilevel.helper.ConnectionDetector;
import com.renaldoviola.cardapcommultilevel.helper.JSONParser;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by renaldo on 30/10/15.
 */
public class MenusListActivity extends ListActivity {

    ConnectionDetector cd;

    AlertDialogManager alert = new AlertDialogManager();

    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();

    ArrayList<HashMap<String, String>> menuList;

    JSONObject establishments = null;
    JSONArray menus = null;


    // establishment id
    String establishment_id, establishment_name;


    private static final String URL_MENUS = "...com/api/v1/establishments";

    // JSON menus
    private static final String TAG_ID_MEN      = "id";
    private static final String TAG_DATA        = "data";
    private static final String TAG_WEEKDAY     = "weekday";
    private static final String TAG_PRICE       = "price";
    private static final String TAG_STATUS_MEN  = "status";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menus);

        cd = new ConnectionDetector(getApplicationContext());

        // Check if Internet present
        if (!cd.isConnectingToInternet()) {

            alert.showAlertDialog(MenusListActivity.this, "Sem conexão com internet",
                    "Por favor, conecte-se com a internet para visualizar os cardápios", false);
            // stop executing code by return
            return;
        }

        Intent i = getIntent();
        establishment_id = i.getStringExtra("establishment_id");

        menuList = new ArrayList<HashMap<String, String>>();

\        new LoadTracks().execute();

        // get listview
        ListView lv = getListView();

        /*
        lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {
                /
            }
        }); */

    }

    /**
     * Background Async Task to Load all tracks under one establishment
     * */
    class LoadTracks extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MenusListActivity.this);
            pDialog.setMessage("Carregando cardápios...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair(TAG_ID_MEN, establishment_id));

            String json = jsonParser.makeHttpRequest(URL_MENUS, "GET",
                    params);


            Log.d("Menu List JSON: ", json);

            try {
                JSONObject jsonObj = new JSONObject(json);
                establishments = jsonObj.getJSONObject(
                        "establishments");

                if (establishments != null) {

                    for (int i = 0; i < establishments.length(); i++){

                        menus = jsonObj.getJSONArray("menus");

                        if (menus != null) {
                            // looping through All songs
                            for (int j = 0; j < menus.length(); j++) {
                                JSONObject JOMenu = menus.getJSONObject(j);

                                String id_men = JOMenu.optString(TAG_ID_MEN);
                                String data = JOMenu.optString(TAG_DATA);
                                String weekday = JOMenu.optString(TAG_WEEKDAY);
                                String price = JOMenu.optString(TAG_PRICE);
                                String status_men = JOMenu.optString(TAG_STATUS_MEN);

                                HashMap<String, String> menu = new HashMap<String, String>();

                                menu.put(TAG_ID_MEN, id_men);
                                menu.put(TAG_DATA, data);
                                menu.put(TAG_WEEKDAY, weekday);
                                menu.put(TAG_PRICE, price);
                                menu.put(TAG_STATUS_MEN, status_men);

                                menuList.add(menu);
                            }
                        } else {
                            Log.d("Menus: ", "null");
                        }
                    }
                }else {
                    Log.d("Establishments: ", "null");
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(String file_url) {

            pDialog.dismiss();

            runOnUiThread(new Runnable() {
                public void run() {

                    ListAdapter adapter = new SimpleAdapter(
                            MenusListActivity.this, menuList,
                            R.layout.list_menus, new String[] { "establishment_id", TAG_DATA,
                            TAG_WEEKDAY, TAG_PRICE}, new int[] {
                            R.id.establishment_id, R.id.establishment_name, R.id.menu_id, R.id.menu_data, R.id.menu_diasemana, R.id.menu_preco});
                    setListAdapter(adapter);

                    setTitle(establishment_name);
                }
            });
        }
    }
}

Desde já agradeço quem se despuser me ajudar.