使用java的Android studio,可变生命周期

问题描述 投票:0回答:1

我遇到了一个错误,我有这个代码:

  public String enteredText="";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bts_scan = findViewById(R.id.scanning);
        helpButton = findViewById(R.id.helpButton);
        nextPage = findViewById(R.id.button2);

        bts_scan.setOnClickListener(v->{
            openPopupDialog();
        });
        helpButton.setOnClickListener(v -> {
            contactMail();

        });
        nextPage.setOnClickListener(v -> {
            next();
        });


    }

    private void openPopupDialog() {
        Dialog popupDialog = new Dialog(this);
        popupDialog.setContentView(R.layout.popup);
        Button popupButton = popupDialog.findViewById(R.id.popupButton);
        editText = popupDialog.findViewById(R.id.edit_the_text_of_scan);

        popupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                enteredText = editText.getText().toString();
                if (enteredText.isEmpty()) {
                    Log.e("PopupDialog", "Entered text is empty.");
                } else {
                    Log.d("PopupDialog", "Entered text: " + enteredText);
                    scanCode();
                }
                popupDialog.dismiss();
            }
        });

        popupDialog.show();
    }

    ActivityResultLauncher<ScanOptions> barLauncher=registerForActivityResult(new ScanContract(),result -> {
        if(result.getContents() !=null)
        {

            String scan_results = null;
            try {
                scan_results = scanResults(result.getContents(),enteredText);
            } catch (IOException exception) {
                throw new RuntimeException(exception);
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(page1ScanQRCode.this);
            builder.setTitle("Results");
            builder.setMessage(scan_results);
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i)
                        {
                            dialogInterface.dismiss();
                        }
                    }

            ).show();
        }
        else{
            AlertDialog.Builder builder = new AlertDialog.Builder(page1ScanQRCode.this);
            builder.setMessage("I can't read that output!!");
            builder.show();
        }
    });

  private void scanCode() {
        ScanOptions options = new ScanOptions();
        options.setPrompt("Volume up to flash on");
        options.setBeepEnabled(true);
        options.setOrientationLocked(true);
        options.setCaptureActivity(CaptureAct.class);
        barLauncher.launch(options);
    }

我的enteredText变量的生命周期有时不会持续。假设我在移动应用程序“X32E2”上输入“X32E2”,有时在按下按钮进行扫描后,我的变量变为 null 并且没有将 X32E2 检索到我的 scanResults() 方法,为什么?我该如何解决这个问题。

我希望我的变量能够将值保留到最后。有时它有效,但有时变量值为空

java android android-studio variables
1个回答
0
投票

这背后的主要原因是

Activity
Andorid
的生命周期。 当用户与您的应用程序交互时,
Android
可以重新创建
activities
以响应各种事件。当重新创建
activity
时,它的状态可能不会被保留,并且所有成员变量都会重置为其默认值,除非您显式保存并恢复它。

在您的代码中,您已将

enteredText
变量声明为
class
字段,但在重新创建活动时您并未保存和恢复其状态。当您设置
Activity
的值之后,但在
enteredText
中使用它之前,重新创建
scanResults()
时,
enteredText
将重置为其默认值(此处为 null) .

您应该将

enteredText
变量保存在
savedInstanceState
方法中的
onSaveInstanceState()
捆绑包中,然后在
onCreate()
onRestoreInstanceState()
中恢复它。

public String enteredText="";
Button bts_scan, helpButton, nextPage;
EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bts_scan = findViewById(R.id.scanning);
    helpButton = findViewById(R.id.helpButton);
    nextPage = findViewById(R.id.button2);

    if (savedInstanceState != null) {
        enteredText = savedInstanceState.getString("EnteredText");
    }

    bts_scan.setOnClickListener(v->{
        openPopupDialog();
    });
    helpButton.setOnClickListener(v -> {
        contactMail();
    });
    nextPage.setOnClickListener(v -> {
        next();
    });
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putString("EnteredText", enteredText);
}

private void openPopupDialog() {
    Dialog popupDialog = new Dialog(this);
    popupDialog.setContentView(R.layout.popup);
    Button popupButton = popupDialog.findViewById(R.id.popupButton);
    editText = popupDialog.findViewById(R.id.edit_the_text_of_scan);

    popupButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            enteredText = editText.getText().toString();
            if (enteredText.isEmpty()) {
                Log.e("PopupDialog", "Entered text is empty.");
            } else {
                Log.d("PopupDialog", "Entered text: " + enteredText);
                scanCode();
            }
            popupDialog.dismiss();
        }
    });

    popupDialog.show();
}

ActivityResultLauncher<ScanOptions> barLauncher=registerForActivityResult(new ScanContract(),result -> {
    if(result.getContents() !=null)
    {

        String scan_results = null;
        try {
            scan_results = scanResults(result.getContents(),enteredText);
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(page1ScanQRCode.this);
        builder.setTitle("Results");
        builder.setMessage(scan_results);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                        dialogInterface.dismiss();
                    }
                }

        ).show();
    }
    else{
        AlertDialog.Builder builder = new AlertDialog.Builder(page1ScanQRCode.this);
        builder.setMessage("I can't read that output!!");
        builder.show();
    }
});
private void scanCode() {
  ScanOptions options = new ScanOptions();
  options.setPrompt("Volume up to flash on");
  options.setBeepEnabled(true);
  options.setOrientationLocked(true);
  options.setCaptureActivity(CaptureAct.class);
  barLauncher.launch(options);
}
© www.soinside.com 2019 - 2024. All rights reserved.