Go Premium for a chance to win a PS4. Enter to Win


string cant convert to JSON error

Posted on 2016-07-18
Medium Priority
Last Modified: 2016-09-18

i have an android app and its a simple login and register app  that i found online the app compiles with no errors and loads but when i try to log in it tells me string cant be converted to jason with a TOAST message i am sending out.

 * Author: Ravi Tamada
 * URL: www.androidhive.info
 * twitter: http://twitter.com/ravitamada
package info.androidhive.loginandregistration.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import info.androidhive.loginandregistration.R;
import info.androidhive.loginandregistration.app.AppConfig;
import info.androidhive.loginandregistration.app.AppController;
import info.androidhive.loginandregistration.helper.SQLiteHandler;
import info.androidhive.loginandregistration.helper.SessionManager;

public class LoginActivity extends Activity {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    public void onCreate(Bundle savedInstanceState) {

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                            "Please enter the credentials!", Toast.LENGTH_LONG)


        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),


     * function to verify login details in mysql db
     * */
    private void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");

        StringRequest strReq = new StringRequest(Method.POST,
                AppConfig.URL_LOGIN, new Response.Listener<String>() {

            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        Toast.makeText(getApplicationContext(), "User", Toast.LENGTH_LONG).show();
                        String name = user.getString("name");
                        Toast.makeText(getApplicationContext(), "name", Toast.LENGTH_LONG).show();
                        String email = user.getString("email");
                        Toast.makeText(getApplicationContext(), "email", Toast.LENGTH_LONG).show();
                        String created_at = user.getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                                errorMsg, Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    // JSON error
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();

        }, new Response.ErrorListener() {

            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                        error.getMessage(), Toast.LENGTH_LONG).show();
        }) {

            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;


        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

    private void showDialog() {
        if (!pDialog.isShowing())

    private void hideDialog() {
        if (pDialog.isShowing())

Open in new window

the error message doe snot tel me the line but i have figured out where i think its happening

             } catch (JSONException e) {
                    // JSON error
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();

Open in new window

Question by:Chris Jones
  • 2
  • 2
  • 2
LVL 17

Assisted Solution

by:Chris Harte
Chris Harte earned 1000 total points (awarded by participants)
ID: 41718980
Have you got internet permissions set in your manifest?

Author Comment

by:Chris Jones
ID: 41719169
yes i was able to create a user in my register section but the login screen is what gave me this error.
LVL 83

Accepted Solution

leakim971 earned 1000 total points (awarded by participants)
ID: 41720051
replace current line 126 by the followin and confirm that work well so you know your string is not good.

                    JSONObject jObj = new JSONObject( "{\"user\":\"chris\",\"name\";\"Jone\",\"email\";\"chris@yahoo.com\"}" );

Open in new window

I see you placed a log, are you able to get the value passed ? why are you using .toString() ?
I see this signature : onResponse(String response)
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.


Author Comment

by:Chris Jones
ID: 41723224
ok guys i am not sure what went wrong but i removed the .to string recompiled still did not work closed the project and re opened now everything works.
LVL 83

Expert Comment

ID: 41723388
sweet :)
LVL 17

Expert Comment

by:Chris Harte
ID: 41803556
The OP had his problem solved and I have halved the points between the experts

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days software publishers make it possible to move all the possible applications on smartphones, tablets, smartwatches, and more. Although behind every logic and decision is a gross doubt: how do they make it possible? In this blog post, we sha…
The well known Cerber ransomware continues to spread this summer through spear phishing email campaigns targeting enterprises. Learn how it easily bypasses traditional defenses - and what you can do to protect your data.
This video is in connection to the article "The case of a missing mobile phone (https://www.experts-exchange.com/articles/28474/The-Case-of-a-Missing-Mobile-Phone.html)". It will help one to understand clearly the steps to track a lost android phone.
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.

916 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