【问题标题】:populate listview from database with json and php使用 json 和 php 从数据库中填充 listview
【发布时间】:2015-06-03 05:39:56
【问题描述】:

我正在尝试按照http://www.learn2crack.com/2013/11/listview-from-json-example.html 此处的教程填充列表视图,但是当我按下 getData 按钮时数据没有显示。看来我无法使用 json 将数组从 php 传递到我的 android 应用程序,所以我需要帮助

编辑:最近我能够从 php 传递值,但我无法在 listview 中设置值,当我运行活动时,logcat 输出文本将是这样的:

06-04 09:10:23.844: D/JSON Parser(4058): {"pendaftar":[[{"no_pendaftaran":"AD-15-001","nama_lengkap":"Wanda"},{"no_pendaftaran":"AD-15-002","nama_lengkap":"Skndje"},{"no_pendaftaran":"AD-15-003","nama_lengkap":"Aksn"}]]} 

然后我编辑我的 php 代码:

 //fetching all the rows from the query
	$row = $stmt->fetchAll();
	$response["pendaftar"][]= $row;
    
	echo json_encode($response);

所以这是我的活动,它将显示列表视图:

package subactivity;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import id.wanda.smkkkristenimmanuelii.JSONParser;
import id.wanda.smkkkristenimmanuelii.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class SeleksiNilai extends Activity {

	ListView list;
    TextView noPendaftaran;
    TextView namaPendaftar;
    Button Btngetdata;
    ArrayList<HashMap<String, String>> calonSiswa = new ArrayList<HashMap<String, String>>();
    JSONParser jParser = new JSONParser();
    
  //URL to get JSON Array
    private static String url = "http://192.168.1.110/smkkimmanuel2/seleksiNilai.php";
 
    //JSON Node Names
    private static final String TAG_OS = "pendaftar";
    private static final String TAG_NO_PENDAFTARAN = "no_pendaftaran";
    private static final String TAG_NAMA_LENGKAP = "nama_lengkap";
    
    JSONArray pendaftar = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_seleksi_nilai);
		calonSiswa = new ArrayList<HashMap<String, String>>();
		 
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View view) {
                 new GetData().execute();
 
            }
        });
	}

	private class GetData extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;
       @Override
       protected void onPreExecute() {
           super.onPreExecute();
            noPendaftaran = (TextView)findViewById(R.id.noPendaftar);
            namaPendaftar = (TextView)findViewById(R.id.namaPendaftar);
           pDialog = new ProgressDialog(SeleksiNilai.this);
           pDialog.setMessage("Getting Data ...");
           pDialog.setIndeterminate(false);
           pDialog.setCancelable(true);
           pDialog.show();

       }

       @Override
       protected JSONObject doInBackground(String... args) {

           // Getting JSON from URL
           JSONObject json = jParser.getJSONFromUrl(url);
           return json;
       }
        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();
            try {
                   // Getting JSON Array from URL
                   pendaftar = json.getJSONArray(TAG_OS);
                   for(int i = 0; i < pendaftar.length(); i++){
                   JSONObject c = pendaftar.getJSONObject(i);

                   // Storing  JSON item in a Variable
                   String ver = c.getString(TAG_NO_PENDAFTARAN);
                   String name = c.getString(TAG_NAMA_LENGKAP);

                   // Adding value HashMap key => value

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

                   map.put(TAG_NO_PENDAFTARAN, ver);
                   map.put(TAG_NAMA_LENGKAP, name);

                   calonSiswa.add(map);
                   list=(ListView)findViewById(R.id.list);

                   ListAdapter adapter = new SimpleAdapter(SeleksiNilai.this, calonSiswa,
                           R.layout.single_item_seleksi_nilai,
                           new String[] { TAG_NO_PENDAFTARAN,TAG_NAMA_LENGKAP }, new int[] {
                                   R.id.noPendaftar,R.id.namaPendaftar});

                   list.setAdapter(adapter);
                   list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						Toast.makeText(SeleksiNilai.this, "You Clicked at "+calonSiswa.get(+position).get("name"), Toast.LENGTH_SHORT).show();
						
					}
                   });

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

        }
   }
}

这是获取数据的 php 代码:

<?php

//load and connect to MySQL database stuff
require("config.php");

    //gets user's info based off of a username.
    $query = "SELECT no_pendaftaran,nama_lengkap FROM pendaftaran";
    
    
    try {
        $stmt   = $db->prepare($query);
        $stmt->execute();
    }
    catch (PDOException $ex) {
        // For testing, you could use a die and message. 
        //die("Failed to run query: " . $ex->getMessage());
        
        //or just use this use this one to product JSON data:
        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));
        
    }
    
    //fetching all the rows from the query
	$row = $stmt->fetchAll();
	$arr['pendaftar'][]= $row;
    
    
	$json = json_encode($arr);

	$json_encoded_string = json_encode($arr);
	$json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
	echo $json_encoded_string;

?> 

PHP 输出:

{"pendaftar":[[{"no_pendaftaran":"AD-15-001","nama_lengkap":"Wanda"}]]} 

【问题讨论】:

  • @Viral 感谢您的建议。
  • pendaftar = json.getJSONArray(TAG_OS); JSonArray temp= pendaftar.getjsonArray(0);比使用循环
  • @NaveenTamrakar 你的意思是替换循环?

标签: javascript php android json listview


【解决方案1】:

我终于能够在 listview 上显示数组,问题仍然存在于我的 php 代码中:

//fetching all the rows from the query
	$row = $stmt->fetchAll();
  
  //here, the problem is the bracket []
	$response["pendaftar"][]= $row;
  //here

	echo json_encode($response);

我需要做的只是删除括号,我通过查看其他人的数组输出来弄清楚, 我的php输出是这样的,有双括号[]:

{"pendaftar":[[{"no_pendaftaran":"AD-15-001","nama_lengkap":"Wanda"},{"no_pendaftaran":"AD-15-002","nama_lengkap":"Skndje"},{"no_pendaftaran":"AD-15-003","nama_lengkap":"Aksn"}]]} 

虽然其他人只有 1 个括号,但我不确定原因,但我的问题自己解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 2011-09-10
    • 1970-01-01
    相关资源
    最近更新 更多