1

Don't no what's the problem,It's just every time i enter username and password dialog box shows Attempting Login and app just crashes. Server used:Wamp Below are the codes used. Any help would be appreciable.Thanks in advance.

LoginActivity.java:

package com.sam.kiet;    
import android.app.Activity;   
import android.app.ProgressDialog;   
import android.content.Intent;     
import android.os.AsyncTask;     
import android.os.Bundle;     
import android.view.View;      
import android.widget.Button;      
import android.widget.EditText;      
import android.widget.Toast;      
import android.util.Log;            


import org.apache.http.NameValuePair;       
import org.apache.http.message.BasicNameValuePair;     
import org.json.JSONException;      
import org.json.JSONObject;       

import java.util.ArrayList;     
import java.util.List;      

/**       
 * Created by Vaibhav on 10/2/2015.     
*/      


public class LoginActivity extends Activity implements View.OnClickListener                  {
   private EditText user, pass;       
   private Button bLogin;       
   private ProgressDialog pDialog;         
   JSONParser jsonParser = new JSONParser();            
   private static final String LOGIN_URL = "http://192.168.43.1/login.php";      
   private static final String TAG_SUCCESS = "success";            
   private static final String TAG_MESSAGE = "message";         
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);
    bLogin = (Button) findViewById(R.id.Blogin);
    bLogin.setOnClickListener(this);

}

@Override    
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.Blogin:
            new AttemptLogin().execute();

        default:
            break;
    }
}

class AttemptLogin extends AsyncTask<String, String, String> {
    //boolean failure = false;
    private String username,password;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Attempting for login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        username = user.getText().toString();
        password = pass.getText().toString();



    }

    @Override
    protected String doInBackground(String... args) {
        int success;

        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);
            Log.d("Login attempt", json.toString());
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Successfully Login!", json.toString());

                Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
                finish();
                startActivity(main_activity);
                return json.getString(TAG_MESSAGE);
            } else {
                return json.getString(TAG_MESSAGE);


            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String message) {
        super.onPostExecute(message);
        pDialog.dismiss();
        if (message != null){
            Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();

    }
  }
 }
}

JasonParsor.java:

package com.sam.kiet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException; 
import org.json.JSONObject;

import android.util.Log;

public class JSONParser{

  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "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 == "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;

}

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;

   }
} 

Login.xml:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".LoginActivity"
>

<!-- Login progress -->
<ProgressBar
    android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:visibility="gone"
    />

<ScrollView
    android:id="@+id/login_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >


        <LinearLayout
            android:id="@+id/email_login_form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <AutoCompleteTextView
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Username"
                android:inputType="text"
                android:maxLines="1"
                android:singleLine="true" />

            <EditText android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Password"
                android:imeActionId="@+id/login"
                android:imeActionLabel="Login"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true" />

            <Button
                android:id="@+id/Blogin"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="Login"
                android:textStyle="bold" />

        </LinearLayout>
    </LinearLayout>
</ScrollView>

Logcat(error):

10-12 09:02:22.084    1804-1819/com.sam.kiet E/Buffer Error﹕ Error converting 

result java.lang.NullPointerException: lock == null
10-12 09:02:22.084    1804-1819/com.sam.kiet E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
10-12 09:02:22.094    1804-1819/com.sam.kiet E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.sam.kiet, PID: 1804
    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:841)
     Caused by: java.lang.NullPointerException
            at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:92)
            at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:60)
            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:841)
10-12 09:02:23.744    1804-1804/com.sam.kiet E/WindowManager﹕ android.view.WindowLeaked: Activity com.sam.kiet.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1402280 V.E..... R......D 0,0-1026,288} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:286)
            at com.sam.kiet.LoginActivity$AttemptLogin.onPreExecute(LoginActivity.java:71)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.sam.kiet.LoginActivity.onClick(LoginActivity.java:53)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

New LOGCAT:

10-12 10:40:56.083    5644-5658/com.sam.kiet E/JSON Parser﹕ Error parsing data org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject
10-12 10:40:56.093    5644-5658/com.sam.kiet E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
    Process: com.sam.kiet, PID: 5644
    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:841)
     Caused by: java.lang.NullPointerException
            at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:85)
            at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:60)
            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:841)
10-12 10:40:58.003    5644-5644/com.sam.kiet E/WindowManager﹕ android.view.WindowLeaked: Activity com.sam.kiet.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1401ef8 V.E..... R......D 0,0-1026,288} that was originally added here
            at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
            at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
            at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
            at android.app.Dialog.show(Dialog.java:286)
            at com.sam.kiet.LoginActivity$AttemptLogin.onPreExecute(LoginActivity.java:71)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
            at android.os.AsyncTask.execute(AsyncTask.java:535)
            at com.sam.kiet.LoginActivity.onClick(LoginActivity.java:53)
            at android.view.View.performClick(View.java:4438)
            at android.view.View$PerformClick.run(View.java:18422)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)
vabs
  • 98
  • 9
  • 1
    what is line 92 in LoginActivity? – nano_nano Oct 12 '15 at 13:30
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Tom Oct 12 '15 at 13:32
  • it is just used for debugging purpose.it just prints a lot of messages in log cat. – vabs Oct 12 '15 at 13:35
  • yes and the line is? – nano_nano Oct 12 '15 at 13:38
  • Log.d("Login attempt", json.toString()); – vabs Oct 12 '15 at 13:41
  • NullPointerException is not hard to remove. I should debug the application and check from where the null is coming. – mubeen Oct 12 '15 at 13:48
  • @Vaibhav are you still getting same error after updating with changes mentioned by meda or some other error – Shadow Droid Oct 12 '15 at 14:56
  • still getting same error NullPointer Exception.i have also updated the logcat checkout NEW Logcat – vabs Oct 12 '15 at 15:06
  • what I can see from logcat report including new changes...you have error in converting InputStream to String as mention by log "Buffer Error﹕ Error converting" so your json = sb.toString is not executed hence json is null...so you have multiple exception propogated...I would to know the logcat report line before "Buffer Error﹕ Error converting " that is first line. – Shadow Droid Oct 12 '15 at 15:14

5 Answers5

5

ok I think you get the NullPointer because of this:

if(method == "POST"){

change it to

if("POST".equals(method)){

you compare the object reference and not the values with ==. That's the reason why the method makeHttpRequest returns null.

of course you have to change this too:

}else if(method == "GET"){
nano_nano
  • 12,351
  • 8
  • 55
  • 83
3

This part of your code

Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(main_activity);
return json.getString(TAG_MESSAGE);

You create the Intent then you finish() the activity , then you run startActivity() and finally return.

The logic order is wrong, try this approach:

class AttemptLogin extends AsyncTask<String, String, JSONObject> {
    //boolean failure = false;
    private String username,password;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Attempting for login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        username = user.getText().toString();
        password = pass.getText().toString();



    }

    @Override
    protected JSONObject doInBackground(String... args) {
            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);
            Log.d("Login attempt", json.toString());
            return json;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
        super.onPostExecute(json);
        pDialog.dismiss();
        if (json != null){
            try {
                int success = json.getInt(TAG_SUCCESS);
                String message = json.getString(TAG_MESSAGE);
                if (success == 1) {
                    Log.d("Successfully Login!", json.toString());
                    Toast.makeText(LoginActivity.this,"Login successful" + message, Toast.LENGTH_LONG).show();
                    Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(main_activity);
                    finish();//only at the end!!!
                } else {
                    Toast.makeText(LoginActivity.this, "Login failed = " + message, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
}
meda
  • 45,103
  • 14
  • 92
  • 122
0

Try to change

 try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

to

 try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data",e);
    } catch (Exception e) {
        Log.e("JSON Parser", "Error parsing data",e);
    }

My guess is that you get a null pointer exception that the JSONException doesn't catch.

In general, I would suggest to check for null object before the try->catch since its much "cheaper" than the try->catch mechanism (which is very "expensive").

Asaf Pinhassi
  • 15,177
  • 12
  • 106
  • 130
0
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);

change this to this

JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);

you are getting error because you are not getting Json so change your type and call the method again

salihgueler
  • 3,284
  • 2
  • 22
  • 33
0

Observing you code and both the logcat report...

Initially you had a error will converting InputStream to String which you handled with try catch hence due to Log.e("Buffer Error", "Error converting result " + e.toString()); you can see it in first logcat report. This error was NPE with InputStream is. But at the end your method return null jsonObject This lead to multiple errors being propagated
Solution Fix for this was given by @Stefan Beike Answer that is incorrect String comparison

Now you have error with json formation so your are getting error at mentioned in following code

try {
        jObj = new JSONObject(json); //LINE THROWING ERROR...
        //check properly String json if properly formatted json....so request for String json in question
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString()); 
        //Above line is visible in the second logcat report i.e new logcat.
    }

But again your method will return jObj which null...so in your doInBackground you get multiple error again FROM new logcat report

Error parsing data org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject

So if you want more help with fellow programmer then I would request you to post the json string i.e. string after converting InputStream to String in question.Alternatively you yourself can check the string is properly formatted JSON or not.

Shadow Droid
  • 1,696
  • 1
  • 12
  • 26