Answer the question
In order to leave comments, you need to log in
How to automatically save last listview values and display offline?
When creating an application that takes data (json) from the bank's api using retrofit2, I receive the latest exchange rate values in the listview in response. I was able to implement what I wanted, but when I re-open the application offline, the application automatically requests data from the server, an obvious error arrives in response and therefore: I cannot work with the data without an Internet connection.
Question: How to implement automatic saving of data, in my case: the exchange rate. So that the user re-enters the application already in offline mode and can use the values that were automatically saved in the listview.
public class MainActivity extends AppCompatActivity {
Float trip;
Float trip2 = 34.2f;
SharedPreferences sPref;
String flo3 = "EUR: ";
EditText etText;
Button saveBtn;
final String SAVED_TEXT = "saved_text";
final String LOG_TAG = "myLogs";
private float selectedFromList;
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.listView);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api = retrofit.create(Api.class);
Call<List<Hero>> call = api.getHeroes();
call.enqueue(new Callback<List<Hero>>() {
@Override
public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
List<Hero> heroes = response.body();
Float[] heroNames = new Float[heroes.size()];
for(int i = 0; i < heroes.size(); i++) {
heroNames[i] = heroes.get(i).getBuy();
}
listView.setAdapter(
new ArrayAdapter<Float>(
getApplicationContext(),
android.R.layout.simple_list_item_single_choice,
heroNames
)
);
Float selectedFromList = (Float) listView.getItemAtPosition(1);
System.out.println("EUR = : " + selectedFromList);
listView.setItemChecked(1, true);
trip = selectedFromList;
TextView ob5 = (TextView)findViewById(R.id.textView23);
ob5.setText(Float.toString(trip));
}
@Override
public void onFailure(Call<List<Hero>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
Answer the question
In order to leave comments, you need to log in
In ListView, as in other views, nothing is saved. You want persistent saving. You can save to preferences, file, database. Choose whichever is more convenient for you.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question