2

i'm trying to populate the listview by following the tutorial here http://www.learn2crack.com/2013/11/listview-from-json-example.html, but the data is not showing up when i press the getData button. it seems i fail to pass the array from php to my android app using json, so i need help

Edit : recently i was able to pass the value from php, but i was unable to set the value in listview, when i run the activity, the logcat output text will be like this :

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"}]]} 

and i edit my php code:

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

so here's my activity which will display the listview :

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

        }
   }
}

and here's the php code which will fetch the data :

<?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 Output :

{"pendaftar":[[{"no_pendaftaran":"AD-15-001","nama_lengkap":"Wanda"}]]} 
2
  • pendaftar = json.getJSONArray(TAG_OS); JSonArray temp= pendaftar.getjsonArray(0); than using loop Commented Jun 3, 2015 at 5:51
  • @NaveenTamrakar you mean replace the loop? Commented Jun 3, 2015 at 6:20

1 Answer 1

1

i finally able to show the array on listview, the problem is remain in my php code here:

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

	echo json_encode($response);

all i need to do is just remove the bracket, i figure it out by seeing someone else array output, my php output is like this, there are double brackets [] :

{"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"}]]} 

while other only got 1 bracket, i'm not sure the reason, but my problem solved, by myself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.