I am trying to develop a login app in which I am facing some problems. I looked for solutions to these at various places but couldnt find any.
The errors are:
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
I would really appreciate if someone could help.
My login.java class :
public class Login extends Activity implements View.OnClickListener {
private EditText user, pass;
Button bLogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.15.103/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    user = (EditText)findViewById(R.id.username);
    pass = (EditText)findViewById(R.id.password);
    bLogin = (Button)findViewById(R.id.login);
    bLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
        case R.id.login:
            new AttemptLogin().execute();
            break;
        default:
            break;
    }
}
class AttemptLogin extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }
    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));
            Log.d("request!", "starting");
            JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
            if (json != null) {
                // check your log for json response
                Log.d("Login attempt", json.toString());
            }
            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                //Options.PHONE=username;
                Intent ii = new Intent(Login.this,NewActivity.class);
                //here Options.class is the activity where we will move once login is authenticated.
                startActivity(ii);
                //finish();
                // this finish() method is used to tell android os that we are done with current
                // activity now! Moving to other activity
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}
}
My JSONParser.java class:
    public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj ;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(final String url) {
        // Making HTTP request
        try {
            // Construct the client and the HTTP request.
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            // Execute the POST request and store the response locally.
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // Extract data from the response.
            HttpEntity httpEntity = httpResponse.getEntity();
            // Open an inputStream with the data content.
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
// Create a BufferedReader to parse through the inputStream.
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
            StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
            String line = null;
// Build the string until null.
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
// Close the input stream.
            is.close();
// Convert the string builder data to an actual string.
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
// Try to 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 the JSON Object.
        return jObj;
    }
    // function get json from url
// by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {
// Making HTTP request
        try {
// check for request method
            if(method.equalsIgnoreCase("POST")){
// request method is POST
// 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();
            }else if (method.equalsIgnoreCase("GET")) {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                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();
        } 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;
    }
}
Login.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" >
<Button
    android:id="@+id/login"
    android:layout_width="118dp" android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/password"
    android:layout_alignRight="@+id/password"
    android:layout_below="@+id/password"
    android:text="Login" />
<EditText
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/password"
    android:ems="10"
    android:focusable="true"
    android:hint="Enter username"
    android:imeOptions="actionNext" />
<EditText
    android:id="@+id/password"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/username"
    android:layout_centerHorizontal="true"
    android:ems="10"
    android:hint="Enter password"
    android:imeOptions="actionDone"
    android:inputType="textPassword" />
</RelativeLayout>
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.devikanigam.login" 
    android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk
        android:minSdkVersion=""
        android:targetSdkVersion="18"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Login"
            android:label="@string/app_name"
            android:configChanges="orientation|keyboardHidden"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".NewActivity"
            android:label="Login">
        </activity>
    </application>
</manifest>
Logcat :
06-24 16:33:49.315    3364-3364/com.devikanigam.login I/art﹕ Not late-enabling -Xcheck:jni (already on)
06-24 16:33:49.395    3364-3364/com.devikanigam.login W/ActivityThread﹕ Application com.devikanigam.login is waiting for the debugger on port 8100...
06-24 16:33:49.399    3364-3364/com.devikanigam.login I/System.out﹕ Sending WAIT chunk
06-24 16:33:49.419    3364-3371/com.devikanigam.login I/art﹕ Debugger is active
06-24 16:33:49.608    3364-3364/com.devikanigam.login I/System.out﹕ Debugger has connected
06-24 16:33:49.609    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:49.826    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:50.035    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:50.245    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:50.454    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:50.664    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:50.874    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:51.084    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:51.294    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:51.505    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:51.715    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:51.925    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:52.135    3364-3364/com.devikanigam.login I/System.out﹕ waiting for debugger to settle...
06-24 16:33:52.346    3364-3364/com.devikanigam.login I/System.out﹕ debugger has settled (1351)
06-24 16:33:52.399    3364-3383/com.devikanigam.login D/OpenGLRenderer﹕ Render dirty regions requested: true
06-24 16:33:52.431    3364-3364/com.devikanigam.login D/﹕ HostConnection::get() New Host Connection established 0xae0fdf20, tid 3364
06-24 16:33:52.437    3364-3364/com.devikanigam.login D/Atlas﹕ Validating map...
06-24 16:33:52.517    3364-3383/com.devikanigam.login D/﹕ HostConnection::get() New Host Connection established 0xae088de0, tid 3383
06-24 16:33:52.541    3364-3383/com.devikanigam.login I/OpenGLRenderer﹕ Initialized EGL, version 1.4
06-24 16:33:52.616    3364-3383/com.devikanigam.login D/OpenGLRenderer﹕ Enabling debug mode 0
06-24 16:33:52.637    3364-3383/com.devikanigam.login W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-24 16:33:52.637    3364-3383/com.devikanigam.login W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c4bc20, error=EGL_SUCCESS
06-24 16:34:09.066    3364-3384/com.devikanigam.login D/request!﹕ starting
06-24 16:34:09.112    3364-3383/com.devikanigam.login W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-24 16:34:09.112    3364-3383/com.devikanigam.login W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa56281c0, error=EGL_SUCCESS
06-24 16:34:09.540    3364-3376/com.devikanigam.login I/art﹕ Background partial concurrent mark sweep GC freed 3906(194KB) AllocSpace objects, 0(0B) LOS objects, 55% free, 832KB/1856KB, paused 22.484ms total 152.752ms
06-24 16:34:09.633    3364-3384/com.devikanigam.login E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
06-24 16:34:09.634    3364-3384/com.devikanigam.login E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    Process: com.devikanigam.login, PID: 3364
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
            at com.devikanigam.login.Login$AttemptLogin.doInBackground(Login.java:110)
            at com.devikanigam.login.Login$AttemptLogin.doInBackground(Login.java:70)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
06-24 16:34:11.366    3364-3364/com.devikanigam.login E/WindowManager﹕ android.view.WindowLeaked: Activity com.devikanigam.login.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{200d5161 V.E..... R......D 0,0-729,232} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:298)
            at com.devikanigam.login.Login$AttemptLogin.onPreExecute(Login.java:84)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.devikanigam.login.Login.onClick(Login.java:57)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
06-24 16:34:12.806    3364-3384/com.devikanigam.login I/Process﹕ Sending signal. PID: 3364 SIG: 9
Login.php :
<?php
$conn = mysqli_connect("localhost","root","divy");
$db= mysqli_select_db($conn,"users");
$password=$_POST["password"];
$username=$_POST["username"];
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both first Username and Password.";
//die will kill the page and not execute any code below, it will also
//display the parameter... in this case the JSON data our Android
//app will parse
die(json_encode($response));
}
$query = " SELECT * FROM yardusers WHERE username = '$username'and password ='$password'";
$sql1=mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row)) {
$response["success"] = 1;
$response["message"] = "Present, this username is already in use";
die(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "Invalid Username or Password.";
die(json_encode($response));
}
}
else{
$response["success"] = 0;
$response["message"] = "One or both fields are empty";
die(json_encode($response));
}
mysql_close();
?>
				
                        
Try using the following code to send json to webservice..
and to create json object u can use the following code..
This works perfect for me.. Hope this helps you :)