简体   繁体   English

无论我做什么,捆绑始终是 null

[英]Bundle is always null no matter what I do

Everytime I try to go between activities, I save the editText texts because user experience and all that, but for some reason, while intents get through no problem, the savedinstanceState just won't ever be not null.每次我在活动之间尝试 go 时,我都会保存 editText 文本,因为用户体验等等,但由于某种原因,虽然意图没有问题,但保存的实例状态永远不会不是 null。 I've added the onSave and onRestore methods, overrided them, did what had to be done inside, yet it is always null.我添加了 onSave 和 onRestore 方法,覆盖了它们,做了必须在里面做的事情,但它总是 null。 What am I missing here?我在这里想念什么?

package com.gmproxy.pastilarma;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.gmproxy.DAO.PathologyUserRepository;
import com.gmproxy.Entities.Pathology;
import com.gmproxy.Entities.User;
import com.gmproxy.Util.ImageConverter;
import com.gmproxy.ViewModels.UserViewModel;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class UserAddScreen extends AppCompatActivity {

    Button gotoBack, addObservation, saveUser, addPathologies;
    EditText addUsername, addSurname, addAge, addRoomNumber;
    Spinner addGender;
    ImageView selectImage;
    String obs;
    Pathology paths;
    Context context;
    UserViewModel userViewModel;
    int pathAct = 0;
    int obsAct = 0;
    PathologyUserRepository paUsRe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        Intent intent = this.getIntent();
        context = this.getApplicationContext();
        pathAct = getIntent().getIntExtra("path-record", 0);
        obsAct = getIntent().getIntExtra("obs-record", 0);

        paUsRe = new PathologyUserRepository(this.getApplication());

        setContentView(R.layout.activity_user_add_screen);
        gotoBack = findViewById(R.id.GotoBack);
        addObservation = findViewById(R.id.AddObservation);
        saveUser = findViewById(R.id.SaveUser);
        addPathologies = findViewById(R.id.AddPathologies);
        addUsername = findViewById(R.id.AddUsername);
        addSurname = findViewById(R.id.AddSurname);
        addAge = findViewById(R.id.AddAge);
        addRoomNumber = findViewById(R.id.AddRoomNumber);
        addGender = findViewById(R.id.AddGender);
        selectImage = findViewById(R.id.SelectImage);

        if (pathAct == 1 || obsAct == 1 && savedInstanceState!=null) {
            onRestoreInstanceState(savedInstanceState);
        }

        if (savedInstanceState == null){
            Log.println(Log.INFO,"Test","El bundle está vacio");
        }

        userViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(UserViewModel.class);

        /*
        From this line to 94, we create the spinner, since there's only two options there really is no need of poblating the list from the database.
         */
        List<String> genderList = new ArrayList<>();
        genderList.add("M");
        genderList.add("F");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner, genderList);
        adapter.setDropDownViewResource(R.layout.spinner);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        addGender.setAdapter(adapter);
        addGender.setSelection(0);

        if (savedInstanceState == null){
            obs = intent.getStringExtra("observation");
        } else {
            obs = savedInstanceState.getString("Observacion-usuario");
        }
        if (obs != null){
            Log.println(Log.INFO,"test obs", obs);
        }
        paths = (Pathology) intent.getSerializableExtra("paths");
    }


    public void gotoBack(View view) {
        Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
        startActivity(mainAct);
        finish();
    }

    public void addObservation(View view) {
        Intent mainAct = new Intent(UserAddScreen.this, UserObservationScreen.class);
        startActivity(mainAct);
        finish();
    }

    public void addPathology(View view) {
        Intent mainAct = new Intent(UserAddScreen.this, PathologiesSearchScreen.class);
        startActivity(mainAct);
        finish();
    }

    /**
     * This saves all recorded data for when we come back to the activity
     * @param savedInstanceState
     */
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        if (!addUsername.getText().toString().equals("")) {
            savedInstanceState.putString("Nombre_usuario", addUsername.getText().toString());
        }
        if (!addSurname.getText().toString().equals("")) {
            savedInstanceState.putString("Apellido_usuario", addSurname.getText().toString());
        }
        if (!addAge.getText().toString().equals("")) {
            savedInstanceState.putString("Edad_usuario", addAge.getText().toString());
        }
        if (!addRoomNumber.getText().toString().equals("")) {
            savedInstanceState.putString("Habitacion_usuario", addRoomNumber.getText().toString());
        }

        savedInstanceState.putInt("Sexo_usuario", addGender.getSelectedItemPosition());
        if (obs != null){
            savedInstanceState.putString("Observacion-usuario", obs);
        }

        if (paths != null){
            savedInstanceState.putSerializable("Patologia-usuario", paths);
        }
        super.onSaveInstanceState(savedInstanceState);
        Log.println(Log.INFO,"Guardado","guardado");
    }

    /**
     * This loads up all recorded things in the view
     * @param savedInstanceState
     */
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
            addUsername.setText(savedInstanceState.getString("Nombre_usuario"));
            addSurname.setText(savedInstanceState.getString("Apellido_usuario"));
            addAge.setText(savedInstanceState.getString("Edad_usuario"));
            addRoomNumber.setText(savedInstanceState.getString("Habitacion_usuario"));
            addGender.setSelection(savedInstanceState.getInt("Sexo_usuario"));
            obs = savedInstanceState.getString("Observacion-usuario");
            paths = (Pathology) savedInstanceState.getSerializable("Patologia-usuario");
    }

    /*
    The next two methods are for
    A: Opening either the camera, gallery, or getting a picture from assets
    B: Actually selecting the image and making it show in the imageButton
     */

    public void selectImageAction(View view) {
        final CharSequence[] options = {"Hacer una foto", "Elegir de la galería", "Usar una genérica", "Cancelar"};
        AlertDialog.Builder builder = new AlertDialog.Builder(UserAddScreen.this);
        builder.setTitle("¡Añade una foto!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Hacer una foto")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivity(intent);
                    finish();
                } else if (options[item].equals("Elegir de la galería")) {
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivity(intent);
                    finish();
                } else if (options[item].equals("Cancelar")) {
                    dialog.dismiss();
                } else if (options[item].equals("Usar una genérica")) {
                    selectImage.setImageResource(R.drawable.ic_user_generic_foreground);
                    selectImage.setBackgroundResource(R.drawable.ic_user_generic_foreground);
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bitmap;
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            bitmapOptions);
                    selectImage.setImageBitmap(bitmap);
                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream outFile = null;
                    File file = new File(path, System.currentTimeMillis() + ".jpg");
                    try {
                        outFile = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                        outFile.flush();
                        outFile.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                Log.w("..******************...", picturePath + "");
                ImageView viewImage;
                selectImage.setImageBitmap(thumbnail);
            }
        }
    }


    /**
     * Actually creates the user in the database
     * @param view
     */
    public void saveUser(View view) {

        //Just this to turn the image into a blob

        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.id.SelectImage);
        ImageConverter imgCon = new ImageConverter();
        byte[] bytearray = imgCon.bitmapToBiteArray(bitmap);

        if (addUsername.getText().toString() != null || addSurname.getText().toString() != null
        || addAge.getText().toString() != null || addRoomNumber.getText().toString() != null){
            Toast.makeText(this, "Usuario creado.", Toast.LENGTH_SHORT).show();
            User user = new User(addUsername.getText().toString(), addSurname.getText().toString(), addAge.getText().toString(),
                    Integer.parseInt(addRoomNumber.getText().toString()), addGender.getSelectedItem().toString(), obs, bytearray);
            userViewModel.insert(user);
            paUsRe.insertObject(userViewModel.getIdByNameAndSurname(user.getUser_name(), user.getUser_surname()), paths.getId_pathology());
            Toast.makeText(this, "Patología " + paths.getPathologyName() + " añadida", Toast.LENGTH_SHORT).show();
            Intent mainAct = new Intent(UserAddScreen.this, UserListScreen.class);
            startActivity(mainAct);
            finish();
        } else {
            Toast.makeText(this, "Por favor, introduce todos los parámetros necesarios.", Toast.LENGTH_SHORT).show();
        }

    }
}

onSaveInstanceState() is called right before your activity is about to be killed or restarted because of memory pressure or screen orientation change .由于memory pressurescreen orientation change ,在您的活动即将被终止或重新启动之前调用onSaveInstanceState() Since you are just switching between activities, onSaveInstance() is not called thus the null instance .由于您只是在活动之间切换,因此不会调用onSaveInstance() ,因此不会调用null instance Wound suggest SharedPreference instead Wound 建议使用SharedPreference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM