web-dev-qa-db-fra.com

Tentative d'appeler la méthode virtuelle 'void Android.widget.Button.setOnClickListener (Android.view.View $ OnClickListener)' sur une référence d'objet null

Le problème est le suivant. J'ai une activité de connexion (dans Android Studio) qui fonctionnait bien quelques jours auparavant. Je ne me souviens pas d'avoir changé quoi que ce soit, mais lorsque j'ai lancé celui-ci la fois précédente, l'application s'est fermée juste après avoir cliqué sur le bouton de connexion. La dernière chose indiquée concernait la pré-exécution de AsyncTask . Et je ne comprends pas pourquoi il pourrait y avoir une exception NullPointerException . J'ai presque le même code pour mon activité d’inscription et cela fonctionne bien.

Voici le journal:

05-28 16:04:52.395    1218-1232/system_process V/WindowManager﹕ addAppToken: AppWindowToken{5d89eb token=Token{23ccc93a ActivityRecord{2fe54865 u0 utanashati.reminder/.HomepageActivity t17}}} to stack=1 task=17 at 1
05-28 16:04:52.407  19927-19927/utanashati.reminder D/AndroidRuntime﹕ Shutting down VM
05-28 16:04:52.408  19927-19927/utanashati.reminder E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: utanashati.reminder, PID: 19927
    Java.lang.RuntimeException: Unable to start activity
ComponentInfo{utanashati.reminder/utanashati.reminder.HomepageActivity}: Java.lang.NullPointerException: Attempt to invoke virtual method 'void Android.widget.Button.setOnClickListener(Android.view.View$OnClickListener)' on a null object reference
            at Android.app.ActivityThread.performLaunchActivity(ActivityThread.Java:2325)
            at Android.app.ActivityThread.handleLaunchActivity(ActivityThread.Java:2390)
            at Android.app.ActivityThread.access$800(ActivityThread.Java:151)
            at Android.app.ActivityThread$H.handleMessage(ActivityThread.Java:1303)
            at Android.os.Handler.dispatchMessage(Handler.Java:102)
            at Android.os.Looper.loop(Looper.Java:135)
            at Android.app.ActivityThread.main(ActivityThread.Java:5257)
            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:903)
            at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:698)
     Caused by: Java.lang.NullPointerException: Attempt to invoke virtual method 'void Android.widget.Button.setOnClickListener(Android.view.View$OnClickListener)' on a null object reference
            at utanashati.reminder.HomepageActivity.onCreate(HomepageActivity.Java:55)
            at Android.app.Activity.performCreate(Activity.Java:5990)
            at Android.app.Instrumentation.callActivityOnCreate(Instrumentation.Java:1106)
            at Android.app.ActivityThread.performLaunchActivity(ActivityThread.Java:2278)
            at Android.app.ActivityThread.handleLaunchActivity(ActivityThread.Java:2390)
            at Android.app.ActivityThread.access$800(ActivityThread.Java:151)
            at Android.app.ActivityThread$H.handleMessage(ActivityThread.Java:1303)
            at Android.os.Handler.dispatchMessage(Handler.Java:102)
            at Android.os.Looper.loop(Looper.Java:135)
            at Android.app.ActivityThread.main(ActivityThread.Java:5257)
            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:903)
            at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:698)
05-28 16:04:52.410    1218-1232/system_process W/ActivityManager﹕ Force finishing activity 1 utanashati.reminder/.HomepageActivity
05-28 16:04:52.411    1218-1232/system_process W/ActivityManager﹕ Force finishing activity 2 utanashati.reminder/.LoginActivity

EDIT 1

J'ai eu les yeux ouverts, le problème n'est pas avec LoginActivity, mais avec HomepageActivity. Voici le code:

import ...

public class HomepageActivity extends Activity implements AdapterView.OnItemSelectedListener {

    protected EditText mAddTaskText;
    protected Spinner mPrioritySpinner;
    protected Button mAddTaskButton;
    protected int intPriority = 0;
    protected String taskText;
    protected Timestamp taskTimestamp;
    protected Task userTask;
    protected JsonGenerator taskJSON;

    @Override
    protected void onCreate(Bundle savedInstanceState) {                        // Starts activity. The state can be restored from savedInstanceState
        super.onCreate(savedInstanceState);                                     // Calls the superclass method (IMPORTANT)
        setContentView(R.layout.activity_homepage);                             // Sets layout from activity_homepage.xml

        mPrioritySpinner = (Spinner) findViewById(R.id.prioritySpinner);        // Creates an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.priorityList, Android.R.layout.simple_spinner_item);    // Specifies the layout to use when the list of choices appears
        adapter.setDropDownViewResource(Android.R.layout.simple_spinner_dropdown_item);     // Applies the adapter to the spinner
        mPrioritySpinner.setAdapter(adapter);
        mPrioritySpinner.setOnItemSelectedListener(this);

        mAddTaskText = (EditText) findViewById(R.id.addTaskEditText);           // Finds View by its id in .xml file
        mAddTaskButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(HomepageActivity.this, "Done!", Toast.LENGTH_LONG).show();

                Calendar taskCalendar = Calendar.getInstance();             // Creates new calendar
                long taskTime = taskCalendar.getTimeInMillis();             // Gets time in milliseconds
                taskTimestamp = new Timestamp(taskTime);                    // Creates new Timestamp
                taskText = mAddTaskText.getText().toString();               // Gets description of the task

                userTask.setDate(taskTimestamp);                            // Sets date
                userTask.setText(taskText);                                 // Sets text

                /* Creating JsonGenerator */
                ObjectMapper mapper = new ObjectMapper();
                try {
                    mapper.writeValue(taskJSON, userTask);
                }
                catch (IOException e) {
                    Toast.makeText(HomepageActivity.this, "Could not create JSON", Toast.LENGTH_LONG).show();
                }

                /* Getting out email and password */
                String userPassword = ((EmailPassword) HomepageActivity.this.getApplication()).getPassword();
                String userEmail = ((EmailPassword) HomepageActivity.this.getApplication()).getUserEmail();
                Toast.makeText(HomepageActivity.this, userEmail + " " + userPassword, Toast.LENGTH_LONG).show();

                /* HTTP stuff */
                HttpPoster get = new HttpPoster();
                get.execute(userEmail, userPassword, taskJSON.toString());
            }
        });
    }

    public int getData (String username, String password, String taskJSON) {
        try {
            HttpPost httpPost = new HttpPost("http://something.com/" + username + "/tasks");
            String dataToEncode = username + ":" + password;
            String encodedData = Base64.encodeToString(dataToEncode.getBytes(), Base64.NO_WRAP);
            httpPost.setHeader("Authorization", encodedData);

            try {
                StringEntity taskEntity = new StringEntity(taskJSON, "UTF-8");
                httpPost.setEntity(taskEntity);
            }
            catch (UnsupportedEncodingException e) {
                Toast.makeText(HomepageActivity.this, "Unsupported encoding", Toast.LENGTH_LONG).show();
            }

            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                return 1;
            }
            else if (statusCode == 404) { return 2; }
            else if (statusCode == 500) { return 3; }
            else if (statusCode == 409) { return 4; }
            else { return statusCode; }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public void onItemSelected(AdapterView<?> parent, View view,
                               int pos, long id) {
        String priority = parent.getItemAtPosition(pos).toString();             // Gets chosen priority
        Toast.makeText(HomepageActivity.this, priority, Toast.LENGTH_LONG).show();
        while (!((priority.equals("Low")) || (priority.equals("Medium")) || (priority.equals("High")))) {
            Toast.makeText(HomepageActivity.this, "Something bad happened. Try to choose again", Toast.LENGTH_LONG).show();
        }
        if (priority.equals("Low")) {
            intPriority = 0;
        }
        else if (priority.equals("Medium")) {
            intPriority = 1;
        }
        else if (priority.equals("High")) {
            intPriority = 2;
        }
        userTask.setPriority(intPriority);                                      // Sets chosen priority
    }

    public void onNothingSelected(AdapterView<?> parent) {
        userTask.setPriority(intPriority);                                      // Sets default priority ("0")
    }

    public class HttpPoster extends AsyncTask<String, Void, Integer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(String... params) {
            return getData(params[0], params[1], params[3]);
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result == 1) {
                Toast.makeText(HomepageActivity.this, "Login successful", Toast.LENGTH_LONG).show();
                Intent takeUserHome = new Intent(HomepageActivity.this, HomepageActivity.class);
                startActivity(takeUserHome);
            }
            else if (result == 2) {
                Toast.makeText(HomepageActivity.this, "No such user", Toast.LENGTH_LONG).show();
            }
            else if (result == 3) {
                Toast.makeText(HomepageActivity.this, "Internal server error: unable to send email", Toast.LENGTH_LONG).show();
            }
            else if (result == 4) {
                Toast.makeText(HomepageActivity.this, "Task already exists", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(HomepageActivity.this, result.toString(), Toast.LENGTH_LONG).show();
            }
        }
    }
}

Et fichier XML:

<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="match_parent"
    Android:paddingLeft="@dimen/activity_horizontal_margin"
    Android:paddingRight="@dimen/activity_horizontal_margin"
    Android:paddingTop="@dimen/activity_vertical_margin"
    Android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="utanashati.testapp.HomepageActivity">

    <EditText
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:hint="Add a new task..."
        Android:id="@+id/addTaskEditText"
        Android:nestedScrollingEnabled="false"
        Android:minLines="1"
        Android:maxLines="1" />

    <Spinner
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:id="@+id/prioritySpinner"
        Android:layout_alignRight="@+id/addTaskButton"
        Android:layout_alignEnd="@+id/addTaskButton"
        Android:layout_below="@+id/addTaskEditText" />

    <Button
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:text="Add task"
        Android:id="@+id/addTaskButton"
        Android:layout_below="@+id/prioritySpinner"
        Android:layout_centerHorizontal="true" />

</RelativeLayout>
10
Olesya

Il semble que le bouton que vous appelez ne se trouve pas dans la présentation que vous utilisez dans setContentView(R.layout.your_layout) Vérifiez-le.

17
Mustafa Mohammadi

mAddTaskButton est null car vous ne l'initialisez jamais avec:

mAddTaskButton = (Button) findViewById(R.id.addTaskButton);

avant d'appeler mAddTaskButton.setOnClickListener().

7
ci_

C’est vrai, Mustafa ... ça marche ... ça montre deux dispositions 

  1. setContentView (R.layout.your_layout)
  2. v23 (your_layout).

Vous devriez prendre Button à la fois la mise en page d'activité ...
résoudre ce problème avec succès 

0
Prashant Shende

Assurez-vous que lors de l'utilisation de: Button "varName" = findViewById ("btID"); J'ai accidentellement mis dans l'id d'un bouton d'une autre activité similaire et il a montré la même erreur. J'espère que ça aide.

0
BeastSlayer