3
我需要從服務器上生成的json中獲取數據。Android - 通過Http獲取json數據並列出它們
目前的json生成以下矩陣:
{"success":1,"message":[{"pedidos_id":"1","pedidos_nome":"Teste","pedidos_email":"[email protected]"},{"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」。
工作,非常感謝。 –
歡迎您:) –