0

Hi i am developing an app which uses mysql db but when i try to get the values and display it i get the following error.

02-20 05:48:33.021: W/System.err(1723): org.json.JSONException: Value [{"3":"images\/BigBazaar.png","2":"Jayanagar 4th Block","outlet_name":"Big Bazaar","1":"Big Bazaar","0":"1","outlet_image":"images\/BigBazaar.png","outlet_location":"Jayanagar 4th Block","outlet_id":"1"}] of type org.json.JSONArray cannot be converted to JSONObject

I am also able to see the output in log ie;

02-20 05:48:33.380: I/TAG(1723): [{"0":"1","outlet_id":"1","1":"Big Bazaar","outlet_name":"Big Bazaar","2":"Jayanagar 4th Block","outlet_location":"Jayanagar 4th Block","3":"images\/BigBazaar.png","outlet_image":"images\/BigBazaar.png"}]

This is my code.

public class StoreActivity extends Activity {
    private String mBaseUrl="http://192.168.1.5/Flutura/PHP/";  
    private String mDataUrl=mBaseUrl+"Core/Data/android.data3.php";
    private String mAssetsUrl=mBaseUrl+"Assets/";
    private String mRequest="outlet";
    private String mOutletID="0";

    private String mRecommendedProducts="";
    private String mOutletDetails="";
    private SharedPreferences myPrefs ;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store);      
        myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);             
        mOutletID = myPrefs.getString("outlet_id", "0");
        mOutletDetails = myPrefs.getString("outlet_details","{}");
        Log.v("outlet_details",myPrefs.getString("outlet_details","{}"));
        if(mOutletDetails != "{}"){
            setOutletData(mOutletDetails);
        }
        else{
            executeAjaxRequest();
        }
    }    

    private void executeAjaxRequest(){

       String url = mDataUrl+"?request="+mRequest+"&outlet_id="+mOutletID;
       Log.v("url",url);

       AsyncHttpClient httpclient = new AsyncHttpClient();
       httpclient.get(url, new AsyncHttpResponseHandler() {
         @Override
         public void onSuccess(String response) {
            setOutletData(response);
            Log.i("TAG",response);
         }
       });
     }
    private void setOutletData(String response){
        try{            


        JSONObject store = new JSONObject(response); 

        ImageView store_avatar = (ImageView) findViewById(R.id.store_avatar);  
        TextView store_id      = (TextView)  findViewById(R.id.store_id);
        TextView store_name    = (TextView)  findViewById(R.id.store_name);
        TextView store_loc     = (TextView)  findViewById(R.id.store_location); 

        if(store_avatar != null){
        /*  
          int resid;
          resid = getApplicationContext().getResources().getIdentifier(store.getString("outlet_image").replaceAll(".png",""), "drawable", "org.flutura.recommendation");                  
          store_avatar.setImageResource(resid);*/
            ImageDownloader imdload = new ImageDownloader();
            imdload.setMode(ImageDownloader.Mode.CORRECT);
            imdload.download(mAssetsUrl+store.getString("outlet_image"),store_avatar    );  

          mOutletDetails = store.toString();
          mRecommendedProducts = store.getString("recommended_products");
          store_avatar.setClickable(true);
          store_avatar.setOnClickListener(new View.OnClickListener() {

           @Override
           public void onClick(View v) {
             // TODO Auto-generated method stub
             Intent myIntent = new Intent(StoreActivity.this,StoreMapActivity.class);
             SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
             SharedPreferences.Editor prefsEditor = myPrefs.edit();

             prefsEditor.putString("outlet_details", mOutletDetails);
             prefsEditor.commit();
             startActivity(myIntent);
           }
         });
        }

        mOutletID = store.getString("outlet_id");

        if(store_id != null){
          store_id.setText(mOutletID);
        }

        if(store_name != null){
          store_name.setText(store.getString("outlet_desc"));
        }

        if(store_loc != null){
          store_loc.setText(store.getString("outlet_loc"));
        }

        Button recommended_products_button = (Button) findViewById(R.id.recommended_products_button);
        recommended_products_button.setOnClickListener(new View.OnClickListener(){

           @Override
           public void onClick(View v){

              // Load the recommended products screen
              Intent myIntent = new Intent(StoreActivity.this,RecommendedProductsListActivity.class);
               SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
               SharedPreferences.Editor prefsEditor = myPrefs.edit();               

               prefsEditor.putString("outlet_id",mOutletID);
               prefsEditor.putString("recommended_products", mRecommendedProducts);
               prefsEditor.commit();
               startActivity(myIntent);                    
           }

        });

        Button category_wise_sales_button = (Button) findViewById(R.id.category_wise_sales_button);
        category_wise_sales_button.setOnClickListener(new View.OnClickListener(){

           @Override
           public void onClick(View v){

              // Load the recommended products screen
              Intent myIntent = new Intent(StoreActivity.this,CategoryWiseSalesActivity.class);
               SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
               SharedPreferences.Editor prefsEditor = myPrefs.edit();               

               prefsEditor.putString("outlet_id",mOutletID);
               prefsEditor.commit();
               startActivity(myIntent);                    
           }

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

}

This is my php code.

<?php
error_reporting(0);

//$url = $_GET['url'];
//$mR = $_GET['mRequest'];
$mOid = $_GET['mOutletId'];
//$mloc = $_GET['mLocation'];
//connect to the db
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT outlet_id,outlet_name,outlet_location,outlet_image FROM outlets WHERE outlet_id = '$mOid'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());

//while($row = mysql_fetch_array($result))
  //{
  $output[] = mysql_fetch_array($result); 
  //}
print( json_encode($output));
?>

Can anyone tell me what is wrong as i am on a tight schedule and need to finish this today.

Code for search button.

search_button.setClickable(true);
      search_button.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        String outlet_no = outlet_id.getText().toString();
        if(!outlet_no.isEmpty()){
        @SuppressWarnings("deprecation")
        SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        SharedPreferences.Editor prefsEditor = myPrefs.edit();

        prefsEditor.putString("outlet_id", outlet_no);
        prefsEditor.commit();

        Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);       
        startActivity(myIntent);
        HomeActivity.this.startActivity(myIntent);
        }
        else{
          Toast.makeText(getApplicationContext(), "Please enter an outlet id", Toast.LENGTH_SHORT);
        }  
      }
    });

1 Answer 1

3

Getting cannot convert jsonarray to json object

because your are getting JSONArray instead of JSONObject from server so just change your code by converting String to jsonArray as :

JSONArray jsonArr = new JSONArray(response);  //<<< convert to jsonarray

// extract jsonObejct from JsonArray
JSONObject store = jsonArr.getJSONObject(0); 

instead of

JSONObject store = new JSONObject(response); 
Sign up to request clarification or add additional context in comments.

12 Comments

hi can you tell me how to return the value in the form of an object instead of an array from the php file...
@JayantShinde : no need to change in PHP code just first convert String to JSONArray and then extract JSONObject from it
@JayantShinde : or for returning JsonObject from PHP just change print( json_encode($output)); to print( json_encode($output, JSON_FORCE_OBJECT));
ok i have 1 more problem in the above code it is that i have a text box in that when i enter a number and press a search button it needs to pass that value to the php file which returns the data but that value is not getting passed do you know why.
@JayantShinde : on which button click u want to semd textbox value?
|

Your Answer

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