• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Would greatly appreciate help with a JSON Parsing error

iprivett

Lurker
Hey there everyone! I am new around here but have come hoping to find the solution to a problem that I am having with my android app. Unfortunately, I am pretty new to coding and am getting the following error in my logcat:

Code:
03-14 08:13:58.612: E/JSON(265): {"tag":"login","success":1,"error":0,"uid":"513fb03e6a8e36.15977675","user":{"name":"g","email":"g","created_at":"2013-03-12 17:46:22","updated_at":null}}n
03-14 08:13:58.842: D/dalvikvm(265): GC_FOR_MALLOC freed 3295 objects / 190800 bytes in 76ms
03-14 08:13:59.822: D/GPS Enabled(265): GPS Enabled
03-14 08:14:00.272: E/JSON(265): Invalid Requestn
03-14 08:14:00.272: E/JSON Parser(265): Error parsing data org.json.JSONException: Value Invalid of type java.lang.String cannot be converted to JSONObject
03-14 08:14:00.272: I/DashboardActivity(265): Update on geolocation success
It is probably something stupid that I am doing so it is my hope that the bug can be fixed quickly. The basic functionality that I am looking for is the app to periodically update the latitude and longitude to my database. Here is what I think is the relevant code:

Jsonparser:
Code:
public class JSONParser implements Serializable {
 
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
 
    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
 
        // Making HTTP request
        try {
            // 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();
 
        } 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");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", 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.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
 
    }
}
GPStracker
Code:
public class GPSTracker extends Service implements LocationListener {
 
    private final Context mContext;
 
    // flag for GPS status
    boolean isGPSEnabled = false;
 
    // flag for network status
    boolean isNetworkEnabled = false;
 
    // flag for GPS status
    boolean canGetLocation = false;
 
    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
 
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
 
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
 
    // Declaring a Location Manager
    protected LocationManager locationManager;
 
    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }
 
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
 
            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
 
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
 
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return location;
    }
 
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
 
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
 
        // return latitude
        return latitude;
    }
 
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
 
        // return longitude
        return longitude;
    }
 
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
 
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
 
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
 
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
 
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
 
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
 
        // Showing Alert Message
        alertDialog.show();
    }
 
   
    public void onLocationChanged(Location location) {
    }
 
    
    public void onProviderDisabled(String provider) {
    }
 
    
    public void onProviderEnabled(String provider) {
    }
 
    
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
 
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    } 
 
}
userfunctions:
Code:
public class UserFunctions implements Serializable {

   private static final long serialVersionUID = 1L;

   private JSONParser jsonParser;

  
   private static String loginURL = "URL removed";
   private static String registerURL = "URL removed";
   private static String LOCATION_UPDATE_URL = "URL removed";

   private static String login_tag = "login";
   private static String register_tag = "register";
   private static String LOCATION_UPDATE_TAG = "update_location";

   private String email;
   private String password;

   // constructor
   public UserFunctions() {
      jsonParser = new JSONParser();
   }

   /**
    * function make Login Request
    * 
    * @param email
    * @param password
    */
   public JSONObject loginUser() {
      // Building Parameters
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("tag", login_tag));
      params.add(new BasicNameValuePair("email", email));
      params.add(new BasicNameValuePair("password", password));
      JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
      // return json
      // Log.e("JSON", json.toString());
      return json;
   }

   /**
    * function make update geo location
    * 
    * @param lon
    * @param lat
    * @return
    */
   public JSONObject updateUserGeoLocation(String lon, String lat) {
      // Building Parameters
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("tag", LOCATION_UPDATE_TAG));
      params.add(new BasicNameValuePair("email", email));
      params.add(new BasicNameValuePair("password", password));
      params.add(new BasicNameValuePair("lon", lon));
      params.add(new BasicNameValuePair("lat", lat));
      JSONObject json = jsonParser.getJSONFromUrl(LOCATION_UPDATE_URL, params);
      return json;
   }

   /**
    * function make Login Request
    * 
    * @param name
    * @param email
    * @param password
    */
   public JSONObject registerUser(String name, String email, String password) {
      // Building Parameters
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("tag", register_tag));
      params.add(new BasicNameValuePair("name", name));
      params.add(new BasicNameValuePair("email", email));
      params.add(new BasicNameValuePair("password", password));

      // getting JSON Object
      JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
      // return json
      return json;
   }

   /**
    * Function get Login status
    */
   public boolean isUserLoggedIn(Context context) {
      DatabaseHandler db = new DatabaseHandler(context);
      int count = db.getRowCount();
      if (count > 0) {
         // user logged in
         return true;
      }
      return false;
   }

   /**
    * Function to logout user
    * Reset Database
    */
   public boolean logoutUser(Context context) {
      DatabaseHandler db = new DatabaseHandler(context);
      db.resetTables();
      return true;
   }

   public String getEmail() {
      return email;
   }

   public void setEmail(String email) {
      this.email = email;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

}
dbase php file
Code:
<?php


if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // get tag
    $tag = $_POST['tag'];

    // include db handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();

    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            // echo json with success = 1
            $response["success"] = 1;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = 1;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } else if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = 2;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($name, $email, $password);
            if ($user) {
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
        echo "Invalid Request";
    }
} else {
    echo "Access Denied";
}

mainactivity
Code:
private void processGPSTracker() {
      if (mUserFunctions == null || !mUserFunctions.isUserLoggedIn(getApplicationContext()))
         return;

      gps = new GPSTracker(DashboardActivity.this);
      if (gps.canGetLocation()) {

         double latitude = gps.getLatitude();
         double longitude = gps.getLongitude();

         JSONObject json = mUserFunctions.updateUserGeoLocation(Double.valueOf(longitude)
               .toString(), Double.valueOf(latitude).toString());

         // check for login response
         try {
            if (json.getString(KEY_SUCCESS) != null && json.getString(KEY_SUCCESS).equals("1")) {
               Log.i("DashboardActivity", "Update on geolocation success");
            } else {
               Log.e("DashboardActivity", "Update on geolocation Failed");
            }
         } catch (JSONException e) {
            e.printStackTrace();
         }

         // \n is for new line
         Toast.makeText(getApplicationContext(),
               "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG)
               .show();

      } else {
         // can't get location
         // GPS or Network is not enabled
         // Ask user to enable GPS/network in settings
         gps.showSettingsAlert();
      }
   }

Thanks so much in advance for the help!
 
You have a typo here 'sb.append(line + "n");' it should be 'sb.append(line + "\n");'.

You can also turn your http entity into a string in one line of code, try "String json = EntityUtils(httpEntity);".
 
Hey George. Thanks for your response and catching the typo. I don't know if I am just tired or what, but where do I put that line of code?
 
In JsonParser you can replace this:

Code:
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");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

With

Code:
json =  EntityUtils(httpEntity);
you will also need to add
Code:
import org.apache.http.util.EntityUtils;
at the top of the file.

You should also delete "is = httpEntity.getContent();" from a couple of lines before.
 
I'm sorry this is being such a pain, but when I do the replacement of

Code:
json =  EntityUtils(httpEntity);
the "httpEntity" variable part is underlined red and says that it cannot be resolved as a variable. I see it being declared a bit up in the code with

Code:
HttpEntity httpEntity = httpResponse.getEntity();
so I don't understand the error.
 
Sorry, the httpEntity variable goes out of scope (gets deleted) when you get to the close brace } character.
Stick the line of code before the close brace (where "is = httpEntity.getContent();" used to be.)
 
The string json is already declared as a member of the class.

Did you remember to add the import line at the top of the file?
 
Yes. If you put the string keyword before json, it will create a new variable called json instead of using the one defined at the top of your class. This will then get deleted at the close brace.

Now when you try and construct your JSONObject it will get given the uninitialised string instead of the one you want.
 
You wouldn't think that this would be hard since I already can get the register activity to post to the database and a timer to check the location periodically. Those functions work fine. Should be easy getting the location data to post right?
 
Code:
public class JSONParser implements Serializable {
     
    static InputStream is = null;
    static JSONObject jObj = null;

    // constructor
    public JSONParser() {
 
    }
 
    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
        String json = "";
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
 
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            json = EntityUtils.toString(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
 
        // return JSON String
        return jObj;
    }
}

I also moved the String json so that it isn't a static member of the class.
 
That didn't work either...

I found this link and tried changing the java code, but that didn't work either. The invisible character makes sense but I guess that I am supposed to change my php code as well with:

Code:
header('Content-type=application/json; charset=utf-8');

http://stackoverflow.com/questions/...lang-string-cannot-be-converted-to-jsonobject

could it be that the lat/long comes out as an int but my database is setup as them being a varchar?

When working with a database, you need to make sure your datatypes match.
 
Back
Top Bottom