【问题标题】:Android - Take json data via Http and list themAndroid - 通过 Http 获取 json 数据并列出它们
【发布时间】:2016-07-19 05:06:48
【问题描述】:

我需要从服务器上生成的 json 中获取数据。

目前我的 json 生成以下矩阵:

{"success":1,"message":[{"pedidos_id":"1","pedidos_nome":"Teste","pedidos_email":"ygormagrii@gmail.com"},{"pedidos_id":"19","pedidos_nome":"5","pedidos_email":"camiseta"},{"pedidos_id":"75","pedidos_nome":"6","pedidos_email":"hdj"},{"pedidos_id":"76","pedidos_nome":"5","pedidos_email":"grhd"},{"pedidos_id":"77","pedidos_nome":"5","pedidos_email":"gdf"}]}

生成这个 JSON 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);
}
mysql_close($con);

我的活动接收 json 并试图限制它:

package com.projects.activities;

import android.app.Activity;
import android.app.AlertDialog;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.libraries.usersession.UserAccessSession;
import com.libraries.usersession.UserSession;
import com.projects.storefinder.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Created by Ygor on 23/02/2016.
 */
public class FinalizarPedido extends Activity {

    private TextView tvDescricao;
    private TextView tvQuantidade;
    private String Descricao;
    private String Unidade;
    private String Categoria;
    private String Qtd;
    private String pedidos_nome;
    private String pedidos_email;
    private String pedidos_id;
    private AlertDialog alerta;
    String user_id;
    InputStream is=null;
    String result=null;
    String line=null;


    @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) {
            ArrayList<String> pedidos_nome = new ArrayList<String>();
            ArrayList<String> pedidos_id = new ArrayList<String>();
            ArrayList<String> pedidos_email = new ArrayList<String>();

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

                    pedidos_nome.get(i);
                    pedidos_id.get(i);
                    pedidos_email.get(i);
                }


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


        }

    }
}

应用程序运行正常,该问题仅出现在始终返回为“NULL”的数据列表中。

【问题讨论】:

    标签: php android mysql json


    【解决方案1】:

    在 doInBackground() 中只返回结果而不是返回 user_id

    【讨论】:

      【解决方案2】:
        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;
      
          }
      

      【讨论】:

        猜你喜欢
        • 2012-02-22
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 1970-01-01
        • 2014-12-16
        • 1970-01-01
        相关资源
        最近更新 更多