-1

I have problems to get data from a JSON on Android.
My PHP is as follows:

$user_id=$_REQUEST['user_id'];

$r=mysql_query("select * from tbl_storefinder_pedidos where user_id='$user_id'",$con);

if( mysql_num_rows( $r ) > 0 ) {
    while($row = mysql_fetch_array($r))
    {
        $flag[pedidos_id]=$row[pedidos_id];
        $flag[pedidos_nome]=$row[pedidos_nome];
        $flag[pedidos_email]=$row[pedidos_email];
        print(json_encode($flag));
    }
}

mysql_close($con);

When I try to get the data in Android can catch only the first record.

Follow my activity:

class select extends AsyncTask<String, Integer, String> {

    private StringBuilder sb;
    private ProgressDialog pr;
    private HttpResponse req;
    private InputStream is;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(getApplicationContext(), "Captando ...", Toast.LENGTH_LONG).show();
    }

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

        UserAccessSession userAccess = UserAccessSession.getInstance(FinalizarPedido.this);
        UserSession userSession = userAccess.getUserSession();
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("user_id", String.valueOf(userSession.getUser_id())));

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://marketingdigitalabc.com.br/buysell/pedidos_show.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("pass 1", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
                    Toast.LENGTH_LONG).show();
        }

        try {
            BufferedReader reader = new BufferedReader
                    (new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
            Log.e("pass 2", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 2", e.toString());
        }

        try {
               JSONObject json_data = new JSONObject(result);
            for (int i = 0; i < 5; i++) {
                pedidos_nome = (json_data.getString("pedidos_nome"));
                pedidos_id = (json_data.getString("pedidos_id"));
                pedidos_email = (json_data.getString("pedidos_email"));
            }

        } catch (Exception e) {
            Log.e("Fail 3", e.toString());
        }
        return user_id;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        String[] lista = {"Produtos:" +pedidos_id};
        final ListView listaPedido = (ListView) findViewById(R.id.lista);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(FinalizarPedido.this, android.R.layout.simple_list_item_1, lista);
        listaPedido.setAdapter(adapter);

        listaPedido.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> lista, View item, int posicao, long id) {
                listaPedido.getItemAtPosition(posicao);
                AlertDialog.Builder builder = new AlertDialog.Builder(FinalizarPedido.this);//Cria o gerador do AlertDialog
                builder.setTitle("Pedido: " + pedidos_nome);
                builder.setMessage("Pedido id: " + pedidos_id + "\nPedido E-mail: " + pedidos_email+ "\nPedido Nome: " + pedidos_nome);
                builder.setNegativeButton("Fechar", null);
                alerta = builder.create();
                alerta.show();
            }
        });


    }

My goal is to list the data received via JSON. Can anybody help me?

Hatchet
  • 5,320
  • 1
  • 30
  • 42

2 Answers2

1

The reason this is happening is because you are returing only the first values, put all the values in an array and then return the array. Then you can decode the array in your app using jason.

in the php script

$user_id=$_REQUEST['user_id'];

$r=mysql_query("select * from tbl_storefinder_pedidos where user_id='$user_id'",$con);

$response= array();
$info=array();
$flag = array();

if( mysql_num_rows( $r ) > 0 ) {
    while($row = mysql_fetch_array($r))
    {
        $flag[pedidos_id]=$row[pedidos_id];
        $flag[pedidos_nome]=$row[pedidos_nome];
        $flag[pedidos_email]=$row[pedidos_email];
        array_push($info, $flag);
    }
        $response["success"] = 1;
        $response["message"] = $info;
        echo json_encode($response);
}
else
{
        $response["success"] = 0;
        $response["message"] = "No entries yet";
        echo json_encode($response);
}

Now in the activity you can play around with jsonObject and jsonArray to get all the values.

MainActivity...

The reason you were not getting the desired result was because from script you are returing jsonArray and in code you are trying to fetch JsonObject.

First declare ArrayLists..

 ArrayList<String> pedidos_nome = new ArrayList<>();
 ArrayList<String> pedidos_id = new ArrayList<>();
 ArrayList<String> pedidos_email = new ArrayList<>();

in try block put this code...

// Only the next line is what i am not sure of, you had it correct earlier, please use that and then apply the reamining code. (I got confused because i have been using volley for requests its quite easier than Http, would suggest you to try that next time :) )

JSONObject jsonData = new JSONOnject("result");
                    JSONArray arr =  jsonData.getJSONArray("message");
                    for (int i=0; i < arr.length(); i++) {
                        JSONObject  json_data = arr.getJSONObject(i);
                      
                    pedidos_nome.add((json_data.getString("pedidos_nome")));
                    pedidos_id.add((json_data.getString("pedidos_id")));
                    pedidos_email.add((json_data.getString("pedidos_email")));

                    }

Now to get the first pedidos_nome:

pedidos_nome.get(0);
Community
  • 1
  • 1
Rishabh Lashkari
  • 638
  • 1
  • 8
  • 22
  • Hi.Thank you for your help, In the case how can I retrieve a list of form matrix in my activity? – Ygor Magrii Mar 30 '16 at 11:13
  • Can you please give an example of what you are looking for? – Rishabh Lashkari Mar 30 '16 at 11:30
  • Ok, I did the array as you pointed out to me and she returned the json correctly. The problem now is the time to retrieve the data via json. Follow my activity that tries to list the data sent by json: https://github.com/ygormagrii/APPS/issues/1 – Ygor Magrii Mar 30 '16 at 12:29
  • The returned JSON is the same as that of the link: http://marketingdigitalabc.com.br/buysell/pedidos_show.php – Ygor Magrii Mar 30 '16 at 12:39
  • At the time of the first call pedidos_nome, I can not get the get the onPostExecute () method and the array ends up returning as "null" I could check if correctly implemented the code: https://github.com/ygormagrii/APPS/issues/1 – Ygor Magrii Mar 30 '16 at 13:24
  • My Bad, My bad, Sorry I have updated the correct ans please try now. – Rishabh Lashkari Mar 30 '16 at 13:47
  • No problem, tested and rolled app but when I try to view the data in onPostExecute () he keeps returning to null, as I call the array data correctly in onPostExecute? Updated again the activity so you can look: https://github.com/ygormagrii/APPS/issues/1 And thank you for strength! – Ygor Magrii Mar 30 '16 at 14:03
  • Hi, I still can not solve here, Could you check? Thank you for your help. – Ygor Magrii Mar 30 '16 at 19:53
  • Hey! Before I try the code again can you please just try and look if we are actually getting jason in the result. Simply add // Log.e("JasonCheck", result.toString) just before try block and check the log. – Rishabh Lashkari Mar 31 '16 at 00:56
  • I worked properly managed to solve. Thank you for your support. – Ygor Magrii Mar 31 '16 at 01:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107798/discussion-between-ygor-magrii-and-rishabh-lashkari). – Ygor Magrii Mar 31 '16 at 01:31
0

public class FinalizarPedido extends Activity {

private TextView tvDescricao;
private TextView tvQuantidade;
private String Descricao;
private String Unidade;
private String Categoria;
private String Qtd;
private AlertDialog alerta;
String user_id;
InputStream is=null;
String result=null;
String line=null;
ArrayList<String> pedidos_nome = new ArrayList<String>();
ArrayList<String> pedidos_id = new ArrayList<String>();
ArrayList<String> pedidos_email = new ArrayList<String>();


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

    Button novoPedido = (Button) findViewById(R.id.novo_pedido);
    Button btnEnd = (Button) findViewById(R.id.buttonFim);

    new select().execute();

    btnEnd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(FinalizarPedido.this, FormPedidos.class);
            startActivity(intent);
        }
    });


    novoPedido.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(FinalizarPedido.this, InsertNewPedidos.class);
            startActivity(intent);
        }
    });

}

class select extends AsyncTask<String, Integer, String> {

    private StringBuilder sb;
    private ProgressDialog pr;
    private HttpResponse req;
    private InputStream is;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(getApplicationContext(), "Captando ...", Toast.LENGTH_LONG).show();
    }

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

        UserAccessSession userAccess = UserAccessSession.getInstance(FinalizarPedido.this);
        UserSession userSession = userAccess.getUserSession();
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("user_id", String.valueOf(userSession.getUser_id())));

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://marketingdigitalabc.com.br/buysell/pedidos_show.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            Log.e("pass 1", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 1", e.toString());
            Toast.makeText(getApplicationContext(), "Invalid IP Address",
                    Toast.LENGTH_LONG).show();
        }

        try {
            BufferedReader reader = new BufferedReader
                    (new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
            Log.e("pass 2", "connection success ");
        } catch (Exception e) {
            Log.e("Fail 2", e.toString());
        }

        try {

            JSONObject json_data = new JSONObject(result);
            JSONArray arr =  json_data.getJSONArray("message");
            for (int i=0; i < arr.length(); i++) {
                JSONObject  json_dat = arr.getJSONObject(i);

                pedidos_nome.add((json_dat.getString("pedidos_nome")));
                pedidos_id.add((json_dat.getString("pedidos_id")));
                pedidos_email.add((json_dat.getString("pedidos_email")));
            }


        } catch (Exception e) {
            Log.e("Fail 3", e.toString());
        }
        return user_id;

    }