web-dev-qa-db-ja.com

nullオブジェクト参照で仮想メソッド「void Android.widget.Button.setOnClickListener(Android.view.View $ OnClickListener)」を呼び出そうとしました

問題は次のとおりです。ログインアクティビティがあります(Android Studio)。これは数日前に正常に機能しました。何も変更したことを覚えていません。ログインボタン最後に示されたのは、AsyncTaskの事前実行についての乾杯でした。

ログは次のとおりです。

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

編集1

私は目を開けていましたが、問題はLoginActivityではなく、HomepageActivityにあります。コードは次のとおりです。

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();
            }
        }
    }
}

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>
11
Olesya

呼び出しているボタンは、setContentView(R.layout.your_layout)チェックで使用しているレイアウトにないようです。

20

mAddTaskButtonは、次で初期化しないためnullです。

_mAddTaskButton = (Button) findViewById(R.id.addTaskButton);
_

mAddTaskButton.setOnClickListener()を呼び出す前に。

8
ci_

本当、Mustafa ....その働き..その2つのレイアウトを指す

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

あなたは両方のアクティビティレイアウトをボタンを取る必要があります...
この問題を解決する

0
Prashant Shende

使用中に次のことを確認してください。Button "varName" = findViewById( "btID");正しい「btID」を入力します。他の同様のアクティビティからボタンのIDを誤って入力すると、同じエラーが表示されました。それが役に立てば幸い。

0
BeastSlayer