0

I am creating an app and when I click login in the android simulator it says unfortunately the app has stopped but I checked my code multiple times and I don't see any errors with the code . I am following a tutorial so it should all be correct because it works for the guy doing the tutorial .

MainActivity.java :

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

EditText UsernameEt, PasswordEt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    UsernameEt = (EditText)findViewById(R.id.etUserName);
    PasswordEt = (EditText)findViewById(R.id.etPassword);

}

public void OnLogIn(View view) {
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();
    String type = "login";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, username, password);

}

}

Backgroundworker.java :

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
    context = ctx;
}

@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "http://192.168.1.7/login.php";
    if (type.equals("login")){
        try {
            String user_name = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("user_name" , "UTF-8")+"="+URLEncoder.encode(user_name , "UTF-8")+"&"
                    +URLEncoder.encode("user_pass" , "UTF-8")+"="+URLEncoder.encode(password , "UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result="";
            String line;
            while((line = bufferedReader.readLine())!= null ){
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result) {
    alertDialog.setMessage(result);
    alertDialog.show();
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
}

Login button in content_main.xml :

  <Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="LogIn"
    android:id="@+id/login"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="OnLogIn"
    />

  <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:hint="Username"
    android:ems="10"
    android:id="@+id/etUserName"
    android:layout_below="@+id/textView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

  <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPassword"
    android:ems="10"
    android:hint="Password"
    android:id="@+id/etPassword"
    android:layout_below="@+id/etUserName"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

login.php :

<?php
require"db.php";

$user_name = "user";
$password = "pass";

$mysql_qry = "select * from users where username = '$user_name' and password = '$password';";

$result = mysqli_query($conn, $mysql_qry);

if(mysqli_num_rows($result) > 0) {
echo"login success";
}
else {
echo"not success";
}
?>

Error :

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference at com.example.User.App.MainActivity.OnLogIn(MainActivity.java:22)

(line 22 mainactivity: String username = UsernameEt.getText().toString();)

Harshad Pansuriya
  • 20,189
  • 8
  • 67
  • 95
  • 3
    `"... so it should all be correct because it works for the guy doing the tutorial"` -- until you know the source of your bug, **never** say this. – Hovercraft Full Of Eels Jun 11 '16 at 03:27
  • But I can't find the source of the bug that's the problem –  Jun 11 '16 at 03:28
  • Indeed, nor can I, but assume that there **is** a bug first, that you are wrong somewhere. Otherwise you'll be eating your words. – Hovercraft Full Of Eels Jun 11 '16 at 03:29
  • 2
    can you show your android logcat – Channa Jayamuni Jun 11 '16 at 03:44
  • Try to debug the code and find the point where it is crashing..So that it will be easy to find the bug in the code.. – srinivas Jun 11 '16 at 03:50
  • What's that ? @ChannaJayamuni –  Jun 11 '16 at 03:57
  • Android runtime log – Channa Jayamuni Jun 11 '16 at 03:59
  • I only see an event log @ChannaJayamuni –  Jun 11 '16 at 04:10
  • Either print out the response from the server or add more exception handling, but first, please refer to this post. http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – OneCricketeer Jun 11 '16 at 05:20
  • @cricket_007 this is what it says : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference –  Jun 11 '16 at 05:34
  • at com.example.User.App.MainActivity.OnLogIn(MainActivity.java:22) –  Jun 11 '16 at 05:35
  • public void OnLogIn(View view) { String username = UsernameEt.getText().toString(); String password = PasswordEt.getText().toString(); String type = "login"; BackgroundWorker backgroundWorker = new BackgroundWorker(this); backgroundWorker.execute(type, username, password); –  Jun 11 '16 at 05:36
  • The code where the error is is at string username .... But I can't find the problem at all –  Jun 11 '16 at 05:36
  • @cricket_007 I just did –  Jun 11 '16 at 05:40
  • That error is likely caused by referencing the wrong xml ids in the code. I've updated my answer below – OneCricketeer Jun 11 '16 at 05:41
  • please update your `setContentView(R.layout.activity_main);` xml also – Amit Basliyal Jun 11 '16 at 08:32

2 Answers2

0

Once you fix the app crashing, such as making sure activity_main.xml (or content_main, if you have one) contains those two button ids that you've used in the code, you have a second problem with the server as well.

Your PHP file always uses user:pass as the credentials to try to login to the database, and never receives anything else.

If you would like to get the values that android set in the POST request, you can do like so

if (isset($_POST['user_name']) && isset($_POST['user_pass'])) {

    // receiving the post params
    $name = $_POST['user_name'];
    $password = $_POST['user_pass'];

    // TODO: Call database function 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Not sure why you say they are the same ids. `android:id="@+id/editText"` does not say `etUserName` – OneCricketeer Jun 11 '16 at 05:49
  • Did you correct both of the ids? Username and password? – OneCricketeer Jun 11 '16 at 05:57
  • yes . android:id="@+id/UsernameEt" android:id="@+id/PasswordEt" –  Jun 11 '16 at 06:08
  • Okay. Stop messing with the XML. Make sure that the Java code R.id values are the exact same as the XML id values. Because what you just said, they still are not the same – OneCricketeer Jun 11 '16 at 06:11
  • Whenever I it the way you told me too when I click the login button it doesn't work –  Jun 11 '16 at 06:15
  • Okay, so if the ids are the exact same, and you are 100% sure of that, then you either have no errors, or the error message is different. In either case, update your question again with the correct xml and the error message – OneCricketeer Jun 11 '16 at 06:18
  • android:inputType="textPersonName" android:hint="Username" android:ems="10" android:id="@+id/etUserName" –  Jun 11 '16 at 06:20
  • android:inputType="textPassword" android:ems="10" android:hint="Password" android:id="@+id/etPassword" android:layout_below="@+id/etUserName" –  Jun 11 '16 at 06:20
  • the same as the java –  Jun 11 '16 at 06:21
  • Then you have a different error message. Like I said, please update your question with the new code – OneCricketeer Jun 11 '16 at 06:28
  • You'll need to fix the other id `android:layout_below="@+id/textView"`, but still, you should not be getting the same error as before, so please update that as well, even if it looks the same – OneCricketeer Jun 11 '16 at 06:33
0

There is no problem in server side. Here, NullPointerException in EditText means you are getting value from Edittext, that is not initialized.

Possible cause of NullPointerException is:

  1. You are using multi-screen layout. That means your each layout has multiple copy in multiple layout folder. And your device suitable folder not contains desired EditText.

Solution: make sure etUserName is in your desired xml.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Md. Sajedul Karim
  • 6,749
  • 3
  • 61
  • 87
  • Read the comments under my answer. OP did fix the code, just didn't bother updating the question with the actual error. Plus, look at the PHP, there is a logical error in how the values are retrieved and queried. – OneCricketeer Jun 11 '16 at 10:30