Restore data

Asked

Viewed 21 times

2

I am creating an app that contains a form and when the user clicks on an address search field it is taken to another Activity and then this address is retrieved in a textView in the initial Activity (the form). For address search I am using the Google Places Autocomplete. But when the application goes back to this initial application the other fields of the form that had already been filled lose their data and appear empty again. I logged in and saw that Activity is being destroyed and onCreate is running again. So I tried to save the data with onSaveInstanceState and then restore them with the onRestoreInstanceState but still nothing has changed. I wonder if using these methods would really be the best solution and if I did them correctly or if I would have another more appropriate solution.

Below follows the codes of the form class and the address search class:

Form class:

 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    Log.d("CicloA","SaveInstance");
    final EditText textBox1 = (EditText) findViewById(R.id.editText_NomeEvent);

    CharSequence userText = textBox1.getText();
    outState.putCharSequence("savedText", userText);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    Log.d("CicloA","Restore");

    final EditText textBox1 = (EditText) findViewById(R.id.editText_NomeEvent);

    CharSequence userText = savedInstanceState.getCharSequence("savedText");
    textBox1.setText(userText);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_criar_evento);

    Log.d("CicloA","onCreate");

    storage = FirebaseStorage.getInstance();


    getSupportActionBar().setTitle("Criar evento");

    dados.add("Festas e Baladas");
    dados.add("Música ao vivo");
    dados.add("Aprender");
    dados.add("Negócios");
    dados.add("Cultura");
    dados.add("Bem estar");


    spinner=(Spinner)findViewById(R.id.spinner_T);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,dados);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(adapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            informacaoSelecionada = dados.get(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });


    editTextNomeEvento = findViewById(R.id.editText_NomeEvent);
    editTextDescricao = findViewById(R.id.editText_descricao);


    txtDataEventoInicio = findViewById(R.id.txt_DataEventInicio);
    cdwDataEventoInicio = findViewById(R.id.cdw_DataEventInicio);
    cdwDataEventoInicio.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            flag = FLAG_START_DATE;
            scheduleHoraData(v);
        }
    });

    txtDataEventoFim = findViewById(R.id.txt_DataEventFim);
    cdwDataEventoFim = findViewById(R.id.cdw_DataEventFim);
    cdwDataEventoFim.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            flag = FLAG_END_DATE;
            scheduleHoraData2(v);
        }
    });

    txtendereco = findViewById(R.id.txt_endereco);
    txtendereco.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            finish();
            startActivity(new Intent(getBaseContext(), MapActivity.class));
        }

    });

    Intent intentReceber = getIntent();
    Bundle parametro = intentReceber.getExtras();

    if (parametro != null) {

       String endereco = parametro.getString("chave_endereco");
        txtendereco.setText(endereco);

    }


    cdwImgEvento = findViewById(R.id.cardView_uploadEvento);
    imageViewEvento = findViewById(R.id.img_uploadEvento);

    final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.layout_descricao_img);


    imageViewEvento.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            permissao();
            obterImagem_Galeria();

            linearLayout.setVisibility(View.GONE);
        }
    });


    database = FirebaseDatabase.getInstance();
    storage = FirebaseStorage.getInstance();


}

Search class of the address:

@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); materialSearchBar = findViewById(R.id.searchBar);

    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MapActivity.this);

    placesClient = Places.createClient(this);
    final AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();


    materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
        @Override
        public void onSearchStateChanged(boolean enabled) {
        }

        @Override
        public void onSearchConfirmed(CharSequence text) {
            startSearch(text.toString(), true, null, true);
        }

        @Override
        public void onButtonClicked(int buttonCode) {
            if (buttonCode == MaterialSearchBar.BUTTON_NAVIGATION) {
            } else if (buttonCode == MaterialSearchBar.BUTTON_BACK) {
                materialSearchBar.disableSearch();
                startActivity(new Intent(getBaseContext(), CriarEventoActivity.class));
                finish();
            }
        }
    });
    materialSearchBar.addTextChangeListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            FindAutocompletePredictionsRequest predictionsRequest = FindAutocompletePredictionsRequest.builder()
                    .setCountry("br")
                    .setTypeFilter(TypeFilter.ADDRESS)
                    .setTypeFilter(TypeFilter.ESTABLISHMENT)
                    .setSessionToken(token)
                    .setQuery(s.toString())
                    .build();
            placesClient.findAutocompletePredictions(predictionsRequest).addOnCompleteListener(new OnCompleteListener<FindAutocompletePredictionsResponse>() {
                @Override
                public void onComplete(@NonNull Task<FindAutocompletePredictionsResponse> task) {
                    if (task.isSuccessful()) {
                        FindAutocompletePredictionsResponse predictionsResponse = task.getResult();
                        if (predictionsResponse != null) {
                            predictionList = predictionsResponse.getAutocompletePredictions();
                            List<String> suggestionsList = new ArrayList<>();
                            for (int i = 0; i < predictionList.size(); i++) {
                                AutocompletePrediction prediction = predictionList.get(i);
                                suggestionsList.add(prediction.getFullText(null).toString());
                            }
                            materialSearchBar.updateLastSuggestions(suggestionsList);
                            if (!materialSearchBar.isSuggestionsVisible()) {
                                materialSearchBar.showSuggestionsList();
                            }
                        }
                    } else {
                        Log.i("mytag", "prediction fetching task unsuccesful");
                    }
                }
            });
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });


    materialSearchBar.setSuggstionsClickListener(new SuggestionsAdapter.OnItemViewClickListener() {
        @Override
        public void OnItemClickListener(int position, View v) {
            if(position >= predictionList.size()){
                return;
            }

            AutocompletePrediction selectedPrediction = predictionList.get(position);
            String suggestion = materialSearchBar.getLastSuggestions().get(position).toString();
            materialSearchBar.setText(suggestion);


            Intent intentEnviar = new Intent(getApplicationContext(), CriarEventoActivity.class);
            Bundle parametro = new Bundle();
            parametro.putString("chave_endereco",suggestion);

            intentEnviar.putExtras(parametro);
            startActivity(intentEnviar);
            finish();


            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    materialSearchBar.clearSuggestions();
                }
            }, 1000);
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            if(imm != null)
                imm.hideSoftInputFromWindow(materialSearchBar.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
            final String placeId = selectedPrediction.getPlaceId();
            List<Place.Field> placeFields = Arrays.asList(Place.Field.LAT_LNG);

            FetchPlaceRequest fetchPlaceRequest = FetchPlaceRequest.builder(placeId, placeFields).build();
            placesClient.fetchPlace(fetchPlaceRequest).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
                @Override
                public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
                    Place place = fetchPlaceResponse.getPlace();
                    Log.i("mytag", "Place found: " + place.getName());



                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    if(e instanceof ApiException){
                        ApiException apiException = (ApiException) e;
                        apiException.printStackTrace();
                        int statusCode = apiException.getStatusCode();
                        Log.i("mytag", "place not found: " + e.getMessage());
                        Log.i("mytag", "status code: " + statusCode);
                    }
                }
            });
        }

        @Override
        public void OnItemDeleteListener(int position, View v) {

        }
    });

}
  • It is not easy to follow the logic of your code. Please note that the method onRestoreInstanceState is called only after the onStart. How all boot logic is in the onCreate it is possible that this is the cause of the problem. Perhaps it is preferable to use the received Bundle on onCreate.

  • Okay. I’ll check it out. Thank you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.