首页 > 解决方案 > Variable 'Button' never assigned (Java using android studio)

问题描述

First: Apologies if this question has been asked several times already. I just couldn't find a fix.

Compiler in android studio returns "1 error":

Button button_go2activity findViewById(R.id.button_go2activity);

Error code: variable 'button_go2activity' never assigned

This is confusing to me. I also have another button, which I assigned the same (and which works fine). I also tried to add the variable 'button' in the strings.xml (although it works with the other button without that declaration).

Please see the code attached. Many thanks for your help.

Best, Constantin

package paperpad.app;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    //private Button button;              //button because otherwise not declared???
    @Override


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button_openHelp = findViewById(R.id.button_openHelp);    //connect button "open help" to xml
        button_openHelp.setOnClickListener(new View.OnClickListener() {     //find button
            @Override
            public void onClick(View view) {                  //activity when button "open help" is clicked
                Intent openHelp = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"));      //link to paperPad youtube channel
                startActivity(openHelp);
            }
        });


        Button button_go2activity findViewById(R.id.button_go2activity);
        button_go2activity.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                openActivity_loadPicture();                 //activity defined below
            }
        });
    }
    public void openActivity_loadPicture() {
        Intent intent = new Intent(this, loadpicture.class);
        startActivity(intent);

    }
}

标签: javabuttonunassigned-variable

解决方案


在您的代码中,您缺少=赋值运算符。定义的行button_go2activity应如下所示:

Button button_go2activity = findViewById(R.id.button_go2activity);

推荐阅读