0

i am trying to get the data from database through a php file and then i want to use that data in android.i have tried a lot but it show me this error:type org.json.JSONObject cannot be converted to JSONArray. followin is my php file and android code.also json array which was return is valid.

<?php
require "config.php";
$con = mysqli_connect(HOST,USER,PASS,DB);

$pro_id=0;

$sql="SELECT user.user_id, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location 
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";


$res = mysqli_query($con,$sql) or die('i cant');

//$result = array();
$abc="";
while($row = mysqli_fetch_assoc($res)){
$abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";



}
$final = array("result"=>$abc);
//echo json_encode(array("result"=>$result));
echo json_encode($final);

mysqli_close($con);
?>

andoid code

 public void searchProfession() {
        //testin work

        String[] stringArray = new String[5];

        //



        try {
            HttpParams httpParams = new BasicHttpParams();

            HttpParams p = new BasicHttpParams();
            p.setParameter("profession", SearchProfession);
            // Instantiate an HttpClient
            HttpClient httpclient = new DefaultHttpClient(p);
            String url = "http://abh.netai.net/abhfiles/searchProfession.php";
            HttpPost httppost = new HttpPost(url);

            // Instantiate a GET HTTP method
            try {
                Log.i(getClass().getSimpleName(), "send  task - start");
                //fffffffffffffffffffffffffff
                httppost.setHeader("Content-type", "application/json");
                InputStream inputStream = null;
                String result = null;
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                // 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");
                }
                result = sb.toString();

// return JSON String


                if (inputStream != null) inputStream.close();


                //ffffffffffffffffffffffffffff
                //
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("user", "1"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String responseBody = httpclient.execute(httppost,
                        responseHandler);
                // Parse

                JSONObject json = new JSONObject(result);
                JSONArray jArray = json.getJSONArray("result");

                ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
                //testin work
                String[] myarray;

                //till here
                for (int i = 0; i < jArray.length(); i++) {

                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject e = jArray.getJSONObject(i);
                    String jsonString = jArray.getString(i);
                    stringArray[i] = e.toString();
                    Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0], Toast.LENGTH_SHORT).show();

                    mylist.add(map);
                }


            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block

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

                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // Log.i(getClass().getSimpleName(), "send  task - end");

        } catch (Throwable t) {

            Toast.makeText(this, "Request failed: " + t.toString(),
                    Toast.LENGTH_LONG).show();


        }

    }

My Json : [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id‌​":"76","crtloc_lat":"34.769642","crtloc_lng":"72.361160"},{"user_id":"87","crtloc‌​_lat":"33.697117","crtloc_lng":"72.976631"},{"user_id":"86","crtloc_lat":"33.6971‌​17","crtloc_lng":"72.976631"}]

now i want to get the data in result array and show that data in android.for example i want to use all the(user_id) from that array

4
  • I think your json response is an JSONObject not JSONArray. Add your json response. Commented Oct 8, 2015 at 6:23
  • post sample of your json Commented Oct 8, 2015 at 6:23
  • this is my json @karim mohsen Commented Oct 8, 2015 at 6:45
  • add in your question. remove from comment. Commented Oct 8, 2015 at 6:57

3 Answers 3

1

I think you got this error because jArray.getJSONObject(0); when i = 0 it's an array not an Object

your Json [[],{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},...]

So jArray.getJSONObject(0); is [] not an object {"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"}

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

Comments

0

You can check out this post on how to execute GET/POST/MULTIPART POST requests in android and then use that post to see how to parse your JSON data into pojo(s). Hope that helps.

Comments

0

The error:type org.json.JSONObject cannot be converted to JSONArray is thrown when you try to fetch a JSONObject in the place of an array. An exception will also be thrown if you try to fetch empty objects so please check your code for empties.

start by

    $abc="";
    while($row = mysqli_fetch_assoc($res)){
if(!empty($row['user_id'])&&!empty($row['crtloc_lat'])&&!empty($row['crtloc_lng'])){
    $abc=$abc.$row['user_id'].",".$row['crtloc_lat'].",".$row['crtloc_lng']."~";
    }       
    }

Then

for (int i = 0; i < jArray.length(); i++) {    
     HashMap<String, String> map = new HashMap<String, String>();
     JSONObject e = jArray.getJSONObject(i);
     String jsonString = jArray.getString("crtloc_lat");//Use a key here
     stringArray[i] = e.toString();
     Toast.makeText(MapsActivity.this, "yourrrrs"+stringArray[0],Toast.LENGTH_SHORT).show();    
     mylist.add(map);
                }

1 Comment

tried it also but getting the same error:jsonArray cannot be converted to json object

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.