Solved

Return rresult of a query from php server to android as listView

Posted on 2013-02-05
8
923 Views
Last Modified: 2013-02-09
I am trying to develop an app..
After successfully saving the names of polls in mySQL (using WAMP), i would like to display the name of ongoing polls that i would like people to take part.
I am getting an error that JSONarray cannot be converted to JSONobject. I have researched over the net for days but without success. Could you please, experts, come to my rescue...

my php file
=========
<?php
 

 
// array for JSON response
//$response = array();
//$output = array();
 
// check for required fields
//if (isset($_POST['name']) && isset($_POST['answer_1']) && isset($_POST['answer_2']) && isset($_POST['answer_3'])) {
 
 //
 //   && isset($_POST['profession']) && isset($_POST['income']) && isset($_POST['religion'])
   // $name = $_POST['name'];
   // $answer_1 = $_POST['answer_1'];
   // $answer_2 = $_POST['answer_2'];
	//$answer_3 = $_POST['answer_3'];
	
 
    // include db connect class
    require_once __DIR__ . '/DB_connect.php';
 
    // connecting to db
    $db = new DB_Connect();
 
    // mysql inserting a new row
    $query = mysql_query("SELECT name FROM polls") or die ('Query is invalid: ' . mysql_error());
 
 
    // write the results
	$output = array();
	while ($row = mysql_fetch_array($query)) 
	
	$output[]=$row;
	
	//$output[]=$row['name'];
	//print($output=json_encode($output));
	//$output = json_encode(array('0' => $output));
	//$output = json_encode($output);
	echo json_encode($output);
    //mysql_close();
	
	
	//echo (json_encode($row['name'] . " ")) ;

 
   
 

?>

Open in new window


call from the browser, i am getting this result:

[{"0":"who will win the next election","name":"who will win the next election"},{"0":"who ","name":"who "}]


my  activity.java file

import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONException;
import org.json.JSONObject;


//import android.app.Activity;
import android.app.ListActivity;
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.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Explore_Poll_Activity extends ListActivity {
	
	private ProgressDialog pDialog;
	 JSONParser jsonParser = new JSONParser();
	 //private JSONObject jobj;
	 
	 //private ArrayList<HashMap<String, String>> pollsList;
	 ArrayList<HashMap<String, String>> pollsList ;
	 //private Clsgetjson getjson;
	 
	 private static String url_create_poll = "http://10.0.2.2/android_login_api/retrieve_polls_names.php";
	 // JSON Response node names
	   // private static String TAG_SUCCESS = "success";
	   // private static String KEY_ERROR = "error";
	 
	  // JSON Node names
	    private static final String TAG_NAME = "name";
	    private ListView polls_list;
	    private JSONObject json;
	    
	    // polls JSONArray
	   // private JSONArray polls_array = null;
	    
	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        // TODO Auto-generated method stub
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.explore_poll);

	     // Creating JSON Parser instance
	       // getjson = new Clsgetjson();
	        // Get listview
	        polls_list = (ListView) findViewById(android.R.id.list);

	        // Hashmap for ListView
	        pollsList = new ArrayList<HashMap<String, String>>();
	        
	        
	        //jobj= getjson.getJSONFromUrl(url_create_poll);
	        Log.d("Problem LIST:", pollsList.toString());
	         

	        new LoadAllPolls().execute();


	    }
	    
	    class LoadAllPolls extends AsyncTask<String, String, String>{

	      	  
	      	  protected void onPreExecute() {
	                super.onPreExecute();
	                pDialog = new ProgressDialog(Explore_Poll_Activity.this);
	                pDialog.setMessage("Loading Polls..");
	                pDialog.setIndeterminate(false);
	                pDialog.setCancelable(true);
	                pDialog.show();
	            }

			@Override
			protected String doInBackground(String... arg0) {
				// TODO Auto-generated method stub
				
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				json = jsonParser.makeHttpRequest(url_create_poll, "GET", params);
				 Log.d("All Polls: ", json.toString());
				 Log.d("Problem to sort:", pollsList.toString());
				
				
				 
				 
				 
				return null;
			}
			
			protected void onPostExecute(String file_url) {
	            // dismiss the dialog once done
				
				
				ListAdapter adapter = new SimpleAdapter(
						Explore_Poll_Activity.this, pollsList,
	                    R.layout.simplerow, new String[] {
	                          TAG_NAME},
	                   new int[] {android.R.id.list });
				
				
	            //updating listview
		 polls_list.setAdapter(adapter);
		 
		 
		 Log.d("Problem to sort:", pollsList.toString());
				 
	           pDialog.dismiss();
	        }
	      	 
	    }


}

Open in new window


the error i am getting:


02-05 15:40:23.859: D/dalvikvm(451): GC_EXTERNAL_ALLOC freed 55K, 53% free 2559K/5379K, external 2043K/2137K, paused 92ms
02-05 15:40:57.899: D/dalvikvm(451): GC_EXTERNAL_ALLOC freed 13K, 52% free 2597K/5379K, external 2656K/2796K, paused 72ms
02-05 15:40:59.799: W/KeyCharacterMap(451): No keyboard for id 0
02-05 15:40:59.809: W/KeyCharacterMap(451): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-05 15:41:04.760: I/log_tag(451): Line reads: {"success":1}
02-05 15:41:04.768: I/JSON Parser(451): {"success":1}
02-05 15:41:08.198: D/Problem LIST:(451): []
02-05 15:41:09.439: I/log_tag(451): Line reads:
02-05 15:41:10.119: I/log_tag(451): Line reads: [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:41:10.280: I/JSON Parser(451): [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:41:10.289: I/JSON Parser:::OUSMAN(451): [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:41:10.299: E/JSON Parser:::SOMBE(451): Error parsing data org.json.JSONException: Value [{"name":"who will win the next election","0":"who will win the next election"},{"name":"who  ","0":"who  "}] of type org.json.JSONArray cannot be converted to JSONObject
02-05 15:41:10.299: D/All Polls:(451): {"success":1}
02-05 15:41:10.299: D/Problem to sort:(451): []
02-05 15:41:10.332: D/Problem to sort:(451): [null]
02-05 15:43:00.379: D/dalvikvm(485): GC_EXTERNAL_ALLOC freed 45K, 53% free 2559K/5379K, external 2043K/2137K, paused 63ms
02-05 15:43:38.539: D/dalvikvm(485): GC_EXTERNAL_ALLOC freed 13K, 52% free 2597K/5379K, external 2656K/2796K, paused 72ms
02-05 15:43:40.319: W/KeyCharacterMap(485): No keyboard for id 0
02-05 15:43:40.399: W/KeyCharacterMap(485): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-05 15:43:44.949: I/log_tag(485): Line reads: {"success":1}
02-05 15:43:44.949: I/JSON Parser(485): {"success":1}
02-05 15:43:48.099: D/Problem LIST:(485): []
02-05 15:43:50.129: I/log_tag(485): Line reads:
02-05 15:43:50.129: I/log_tag(485): Line reads: [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:43:50.139: I/JSON Parser(485): [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:43:50.170: I/JSON Parser:::OUSMAN(485): [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:43:50.179: E/JSON Parser:::SOMBE(485): Error parsing data org.json.JSONException: Value [{"name":"who will win the next election","0":"who will win the next election"},{"name":"who  ","0":"who  "}] of type org.json.JSONArray cannot be converted to JSONObject
02-05 15:43:50.179: D/All Polls:(485): {"success":1}
02-05 15:43:50.179: D/Problem to sort:(485): []
02-05 15:43:50.189: I/System.out(485): 1
02-05 15:43:50.189: D/Problem to sort:(485): [null]
02-05 15:52:54.329: D/dalvikvm(524): GC_EXTERNAL_ALLOC freed 46K, 53% free 2559K/5379K, external 2043K/2137K, paused 83ms
02-05 15:53:02.958: D/dalvikvm(524): GC_EXTERNAL_ALLOC freed 13K, 52% free 2598K/5379K, external 2656K/2796K, paused 66ms
02-05 15:53:05.799: W/KeyCharacterMap(524): No keyboard for id 0
02-05 15:53:05.799: W/KeyCharacterMap(524): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-05 15:53:10.129: I/log_tag(524): Line reads: {"success":1}
02-05 15:53:10.129: I/JSON Parser(524): {"success":1}
02-05 15:53:13.859: D/Problem LIST:(524): []
02-05 15:53:15.739: I/log_tag(524): Line reads:
02-05 15:53:15.789: I/log_tag(524): Line reads: [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:53:15.849: I/JSON Parser(524): [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:53:15.919: I/JSON Parser:::OUSMAN(524): [{"0":"who will win the next election","name":"who will win the next election"},{"0":"who  ","name":"who  "}]
02-05 15:53:15.919: E/JSON Parser:::SOMBE(524): Error parsing data org.json.JSONException: Value [{"name":"who will win the next election","0":"who will win the next election"},{"name":"who  ","0":"who  "}] of type org.json.JSONArray cannot be converted to JSONObject
02-05 15:53:15.929: D/All Polls:(524): {"success":1}
02-05 15:53:15.929: D/Problem to sort:(524): []
02-05 15:53:15.939: I/System.out(524): 1
02-05 15:53:15.951: D/Problem to sort:(524): [null]
0
Comment
Question by:ozzyfanta
  • 3
  • 2
  • 2
  • +1
8 Comments
 

Author Comment

by:ozzyfanta
ID: 38855815
JSONParser class

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.util.Log;
 
public class JSONParser {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
 
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {
 
        // Making HTTP request
        try {
 
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
 
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
 
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
 
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                Log.i("log_tag","Line reads: " + line);
            }
            is.close();
            json = sb.toString();
            Log.i("JSON Parser", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
        	Log.i("JSON Parser:::OUSMAN", json);
            Log.e("JSON Parser:::SOMBE", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
 
    }
}

Open in new window

0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 125 total points
ID: 38859147
{"JSON": "Hello, World"} is a JSONObject
[{"JSON": "Hello, World"}] is a JSONArray

So line 91, replace :
jObj = new JSONObject(json);
by :
jObj = new JSONArray(json);

To loop use :
            jArr = new JSONArray(json);
            for(int i=0;i<jArr.length();i++) {
            	jObj = jArr.getJSONObject(i);
                // do something with the object
            }

Open in new window

0
 
LVL 33

Assisted Solution

by:Slick812
Slick812 earned 125 total points
ID: 38860247
greetings  ozzyfanta, , I looked at your code above, and you seem to be incorrectly "Mixing" your PHP output to a JSON string, although the JSONParser class should detect the "Object" or "Array" string type, and call appropriate handlers for that type, it does not seem so, and expects the "{ }" object json string. What I would do is try and switch your PHP output to just Objects in the encode JSON string, maybe something like -

$query = mysql_query("SELECT name FROM polls") or die ('{"invalid":"'.mysql_error().'"}');// be careful this is AJAX

$output = new stdClass;
$num = 0;
while ($row = mysql_fetch_object($query)) {
	$str = 'row'.$num++;
	$output->$str = $row;
	}
if ($num > 0) 
    echo json_encode($output);
    else
    echo '{"empty":"No Results"}';

Open in new window


I could not test this code, but it should give you an Idea for changing the JSON output to have an outer Object in the JSON string for AJAX output.
ask questions if you need more info.
0
 

Author Comment

by:ozzyfanta
ID: 38861969
Thanks for your suggestions...

I have changed the code accordingly and i am not receiving any errors but the emulator is blank...it doest not display any data from the database...I assume the problem is the way i have coded the listView in my listActivity...


import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
//import org.json.JSONArray;
//import org.json.JSONException;
//import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;


//import android.app.Activity;
import android.app.ListActivity;
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.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Explore_Delete_Activity extends ListActivity {
	
	private ProgressDialog pDialog;
	 JSONParser jsonParser = new JSONParser();
	 //private JSONObject jobj;
	 JSONParser jsonP = new JSONParser();
	 JSONArray jArray ;
	 
	 //private ArrayList<HashMap<String, String>> pollsList;
	 ArrayList<HashMap<String, String>> pollsList ;
	 //private Clsgetjson getjson;
	 
	// private static String url_create_poll = "http://10.0.2.2/android_login_api/retrieve_polls_names.php";
	 // JSON Response node names
	   // private static String TAG_SUCCESS = "success";
	   // private static String KEY_ERROR = "error";
	 
	  // JSON Node names
	    private static final String TAG_NAME = "name";
	    private ListView polls_list;
	    private JSONObject json;
	    
	    // polls JSONArray
	   // private JSONArray polls_array = null;
	    
	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        // TODO Auto-generated method stub
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.explore_poll);

	     // Creating JSON Parser instance
	       // getjson = new Clsgetjson();
	        // Get listview
	        polls_list = (ListView) findViewById(android.R.id.list);

	        // Hashmap for ListView
	        pollsList = new ArrayList<HashMap<String, String>>();
	        
	        
	        //jobj= getjson.getJSONFromUrl(url_create_poll);
	        Log.d("Problem LIST:", pollsList.toString());
	         

	        new LoadAllPolls().execute();


	    }
	    
	    class LoadAllPolls extends AsyncTask<String, String, String>{

	      	  
	      	  protected void onPreExecute() {
	                super.onPreExecute();
	                pDialog = new ProgressDialog(Explore_Delete_Activity.this);
	                pDialog.setMessage("Loading Polls..");
	                pDialog.setIndeterminate(false);
	                pDialog.setCancelable(true);
	                pDialog.show();
	            }

			@Override
			protected String doInBackground(String... arg0) {
				// TODO Auto-generated method stub
				
				//List<NameValuePair> params = new ArrayList<NameValuePair>();
				//json = jsonParser.makeHttpRequest(url_create_poll, "GET", params);
				 //Log.d("All Polls: ", json.toString());
				 //Log.d("Problem to sort:", pollsList.toString());
try{
					
					jArray = jsonP.getJSONFromUrl("http://10.0.2.2/android_login_api/retrieve_polls_names.php");
					//JSONO
					//JSONObject getJSONFromUrl(String url, List<NameValuePair> params)	
					
					
				}
				catch(Exception e){
					
					
				}
				
				
				
				 
				 
				 
				return null;
			}
			
			protected void onPostExecute(String file_url) {
	            // dismiss the dialog once done
				
			?????????? THINK THE PROBLEM IS HERE	
				ListAdapter adapter = new SimpleAdapter(
						Explore_Delete_Activity.this, pollsList,
	                    R.layout.simplerow, new String[] {
	                          TAG_NAME},
	                   new int[] {android.R.id.list });
				
				
	            //updating listview
		 polls_list.setAdapter(adapter);
		 
		 
		 Log.d("Problem to sort:", pollsList.toString());
				 
	           pDialog.dismiss();
	        }
	      	 
	    }


}

Open in new window

0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 33

Expert Comment

by:Slick812
ID: 38862282
I tried to look at your last code post, but you have changed the methods you use from

json = jsonParser.makeHttpRequest(url_create_poll, "GET", params);

to

jArray = jsonP.getJSONFromUrl("http://10.0.2.2/android_login_api/retrieve_polls_names.php");

I looked to see where you next use the jArray to parse or "get list" or use it to "View" it's contents, but I could not find it, and do not want to spend the time to analyze it. Anyway, I did a web search for "JsonParser" and the methods and their return types, and I was not successful in get you any help for this, But, I would think that you could at least get some sort of Debug info to display for the returned  jArray   with
jArray.length

or get a string to view using
str3 = jArray.join(" | ");

but if you think the original code might work you might try changing the the PHP output to OBJECTS as this is intended to use OBJECTS in JSON as far as I can tell, and see if the pHP code I had up can do that for you.
0
 
LVL 12

Assisted Solution

by:PCableGuy
PCableGuy earned 250 total points
ID: 38866727
Hi ozzyfanta,

I was looking at your code and wondering where it puts the data into the HashMap named  pollsList, which is the 2nd argument in the call to create a new SimpleAdapter?

?????????? THINK THE PROBLEM IS HERE      
                        ListAdapter adapter = new SimpleAdapter(
                                    Explore_Delete_Activity.this, pollsList,
                          R.layout.simplerow, new String[] {
                                TAG_NAME},
                         new int[] {android.R.id.list });

Is that why the ListView is blank because the pollsList HashMap is empty?
0
 

Author Comment

by:ozzyfanta
ID: 38866894
How to add item to the HashMap? is it map.add(...) and where exactily should i put that piece of code???
0
 
LVL 12

Accepted Solution

by:
PCableGuy earned 250 total points
ID: 38870504
You might need to transfer your JArray data to the HashMap, try looking over this link for some code:
http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
How do I edit this Drupal page? 9 30
php image upload 3 27
wordpress issue 2 21
php connect() failed error 25 16
You should read OS supplied guidelines before developing. I can't stress that enough. The guidelines will help you understand the reasons mobile app developers do what they do.  Apple is very particular when they review appstore submissions.
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now