0
Hello, in my project I have a Spinner id @+id/spnList, that is in my activity Main.
That one Spinner is populated with tables created dynamically in the database, until then everything works perfectly.
The user clicks on a button where it takes the insertion of items. By clicking on the button to go to the activity InsertProduct, give a putExtra to get the chosen table on Spinner of activity Main for the item to be added to the user’s chosen table. After it adds the item, it goes back to the activity Main, but when the activity returns Main the list selected on Spinner is the first.
Let’s assume I have five lists and the user selects and adds an item to Lista 5, when returning to the activity Main the list selected on Spinner is the Lista 1 and not the Lista 5 as the user previously selected.
I tried to give a putExtra of activity InsertProduct for Main, but he returns as null
Ex:
-- Main --
// Função do botão de adicionar item
Spinner spn = (Spinner) findViewById(R.id.spnList);
String strSpn = spn.getSelectedItem().toString(); // Vamos dizer que o valor sera "Lista 5"
Intent i = new Intent(this, InsertProduct.class);
i.putExtra("selectedItem", strSpn);
startActivityForResult(i, 1);
// Função que exibi os itens na tela
Controller controller = new Controller(getBaseContext());
String[] list = controller.getData();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnList.setAdapter(adapter);
if (getIntent() != null && getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
if (!bundle.getString("setSelectedItem").equals(null)) {
String setSpnSelected = bundle.getString("setSelectedItem");
int spinnerPosition = adapter.getPosition(setSelectedItem);
spnList.setSelection(spinnerPosition);
}
}
-- InsertProduct --
Bundle extras = getIntent().getExtras();
String strSpn = extras.getString("selectedItem");
String result = ... // Adiciona item a tabela "Lista"
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
returnIntent.putExtra("setSelectedItem", strSpn);
setResult(Activity.RESULT_OK, returnIntent);
finish();
Does anyone know how I can keep the user-selected table even after I go to another activity?
How exactly do I use these methods? I’m beginner in java and need something more "chewed" let’s say so.
– Giovani Rodrigo
It would be basically the code of my answer.
– Henrique Luiz
Would be
protected void onSaveInstanceStateandprotected void onRestoreInstanceState?onSavein activityMainandonRestorein activityInsertProduct?– Giovani Rodrigo
follow references https://developer.android.com/training/basics/activity-lifecycle/recreating.html?hl=pt-br https://www.youtube.com/watch?v=Nu5mTPRTFqg
– Henrique Luiz