【问题标题】:get JSON array data + MYSQL + ANDROID获取 JSON 数组数据 + MYSQL + ANDROID
【发布时间】:2016-03-30 01:50:31
【问题描述】:

我无法从 Android 上的 JSON 获取数据。
我的PHP如下:

$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);

当我尝试在 Android 中获取数据时,只能捕获第一条记录。

关注我的活动:

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();
            }
        });


    }

我的目标是列出通过 JSON 接收的数据。有人可以帮帮我吗?

【问题讨论】:

  • 英文问题
  • 编辑过对我有帮助吗?
  • 尝试使用“EntityUtils.toString(entity)”而不是“entity.getContent()”
  • 我已投票决定重新开放。同时,虽然和你的问题无关,don't use the mysql_* API!
  • 我使用了 EntityUtils.toString (entity) 但还无法获取所有的 json 数据。 :(

标签: java php android mysql json


【解决方案1】:

发生这种情况的原因是因为您只返回第一个值,将所有值放入一个数组中,然后返回该数组。然后您可以使用 jason 在您的应用中解码数组。

在 php 脚本中

$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);
}

现在在活动中,您可以使用 jsonObject 和 jsonArray 来获取所有值。

MainActivity...

你没有得到想要的结果的原因是你从脚本中返回 jsonArray 并且在代码中你试图获取 JsonObject。

首先声明 ArrayLists..

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

在 try 块中输入这段代码...

// 只有下一行是我不确定的,你之前已经正确了,请使用它然后应用 reaming 代码。 (我很困惑,因为我一直在使用 volley 来请求它比 Http 更容易,建议你下次尝试一下 :))

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")));

                    }

现在获取第一个 pedidos_nome:

pedidos_nome.get(0);

【讨论】:

  • 嗨。谢谢您的帮助,如果我在我的活动中检索表单矩阵列表?
  • 你能举个例子说明你在找什么吗?
  • 好的,我按照你的指示做了数组,她正确地返回了 json。现在的问题是通过 json 检索数据的时候了。关注我尝试列出 json 发送的数据的活动:github.com/ygormagrii/APPS/issues/1
  • 返回的JSON和链接的一样:marketingdigitalabc.com.br/buysell/pedidos_show.php
  • 在第一次调用 pedidos_nome 时,我无法获取 onPostExecute () 方法,并且数组最终返回为“null”我可以检查是否正确实现了代码:github.com/ygormagrii/APPS/issues/1
【解决方案2】:

公共类 FinalizarPedido 扩展 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;

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    相关资源
    最近更新 更多