Gonçalo Ribeiro
Gonçalo Ribeiro

Reputation: 115

Android JAVA getting array from php

I've this php that returns an array with values from database:

public function getHashTags(){
    $res = array();
    $i = 0;

    $userID = $this->getUserID();
    $db_ = $this->dbSelect("hashTags","userID = '$userID' ORDER BY hashTag ASC");

    while($db = $this->dbAssoc($db_)){
        $key = $db['id'];
        $res[$key] = $db['hashTag'];
        $i++;
    }

    return $this->genResponse($res);
}

And I don't know how can I receive this array on JAVA, because this array have no name... I've tried this:

class LoadHashTags extends AsyncTask<String, String, String> {

    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("token", token));

        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(getHashTagsURL, "POST", params);

        // Check your log cat for JSON response
        Log.d("All hashTags: ", json.toString());

        try { //Trying to get hashTags

            JSONArray hashTagsArray = new JSONArray(json.toString());

            // Looping through all videos
            for (int i = 0; i < hashTagsArray.length(); i++) {

                JSONObject c = hashTagsArray.getJSONObject(i);

                    int hashTagId = c.getInt("id");
                String hashTagTxt = c.getString("hashTag");

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

                // adding each child node to HashMap key => value
                map.put("hashId", hashTagId);
                map.put("hashTagTxt", hashTagTxt);

                // adding HashList to ArrayList
                hashTagsList.add(map);

            } //End for

        } catch (JSONException e) {

            e.printStackTrace();

        }

        return null;
    }

    protected void onPostExecute(String file_url) {

        runOnUiThread(new Runnable() {

            public void run() {

                Toast.makeText(getApplicationContext(), "HashTags Loaded", Toast.LENGTH_LONG).show();       
            }
        });

        // dismiss the dialog after getting all hashTags
        pDialog.dismiss();

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {

            public void run() {

                ListAdapter adapter = new SimpleAdapter(

                    VideoUpload.this, hashTagsList,
                    R.layout.hashTags_list_item, new String[] { "hashTagId", "hashTagTxt"}, 
                    new int[] { R.id.hashTagId, R.id.hashTagTxt}
                );

                // updating spinner
                setListAdapter(adapter);        
            }
        });

    } //Close PostExecute

} // CLOSER LOAD HASHTAGS

But it's throwing an exception:

02-25 22:48:58.450: W/System.err(1639): org.json.JSONException: Value {"270":"My hashTag      test","272":"my hastag test2","271":"my hashtag test2","274":"my hashtag test5","273":"my   hashtag test3"} of type org.json.JSONObject cannot be converted to JSONArray
02-25 22:48:58.450: W/System.err(1639):     at org.json.JSON.typeMismatch(JSON.java:111)
02-25 22:48:58.460: W/System.err(1639):     at org.json.JSONArray.<init>  (JSONArray.java:96)
02-25 22:48:58.460: W/System.err(1639):     at org.json.JSONArray.<init>(JSONArray.java:108)
02-25 22:48:58.460: W/System.err(1639):     at com.example.kroosky.VideoUpload$LoadHashTags.doInBackground(VideoUpload.java:484)
02-25 22:48:58.480: W/System.err(1639):     at com.example.kroosky.VideoUpload$LoadHashTags.doInBackground(VideoUpload.java:1)
02-25 22:48:58.480: W/System.err(1639):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-25 22:48:58.490: W/System.err(1639):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-25 22:48:58.490: W/System.err(1639):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-25 22:48:58.490: W/System.err(1639):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-25 22:48:58.490: W/System.err(1639):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-25 22:48:58.490: W/System.err(1639):     at java.lang.Thread.run(Thread.java:841)

Any idea ? Thanks

Upvotes: 0

Views: 94

Answers (1)

ahmed_khan_89
ahmed_khan_89

Reputation: 2773

this is what I use to get json array :

// send a httpRequest to the url
// and parse the json response to a string
public String sendHttpRequest(String url) {
    try {
        // the HTTP request
        HttpParams p = new BasicHttpParams();
        HttpClient httpclient = new DefaultHttpClient(p);
        HttpPost httppost = new HttpPost(url);
        httppost.setHeader("charset", "UTF-8");
        httppost.setHeader("Content-Type", "application/json");

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        inputStream = entity.getContent();

    } catch (Exception e) {
        Log.e("taghttppost", "" + e.toString());
    }
    // conversion of the httpResponse to a string
    try {
        InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8");
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        inputStream.close();
        result = sb.toString();
        result = new String(sb.toString().getBytes("UTF-8"));

    } catch (Exception e) {
        Log.e("tagconvertstr", "" + e.toString());
    }

    return result;
}

then I call it like this :

JSONArray jArray;
JSONObject jobj = new JSONObject(); // if you need it
String result = sendHttpRequest("www.yourUrl.com");
// Parse the string to get a json array
try {
    jArray = new JSONArray(result);
    jobj = jArray.getJSONObject(0); // 0 is the index in the json array...
} catch (JSONException e) {
}

then you can use this json object as you like...

int id = Integer.parseInt(jobj.getString("id")); 
// or simply :
int id=jobj.getInt("op_country_id");
String str = jobj.getString("str");

I hope it helps you.

Upvotes: 1

Related Questions