I am trying to create a history.I have two activities. One is for the user to input value in an editText and storing it in shared preferences and the other one is for displaying the value in listview form using shared preferences. I dont know what is the error because the app crashes.
First Activity
package com.example.sy.list;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
public class History extends AppCompatActivity {
Button translate;
Button next;
EditText enterText;
private SharedPreferences hPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
enterText = findViewById(R.id.editText);
next = findViewById(R.id.btnNext);
translate = findViewById(R.id.buttonTranslate);
View.OnClickListener addlistener = new View.OnClickListener() {
@Override
public void onClick(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(enterText.getWindowToken(), 0);
hPreferences = getSharedPreferences("SaveHistory",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = hPreferences.edit();
editor.putString("history",enterText.getText().toString());
editor.apply();
enterText.setText("");
}
};
translate.setOnClickListener(addlistener);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(History.this,MainActivity.class);
startActivity(intent);
}
});
}
}
Second Activity
package com.example.sy.list;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> itemList = new ArrayList<String>();
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemList);
listView.setAdapter(adapter);
listView = findViewById(R.id.listView);
SharedPreferences transHistory = getSharedPreferences("SaveHistory",Context.MODE_PRIVATE);
String tHistory = transHistory.getString("history","Data Not Found");
itemList.add(tHistory);
adapter.notifyDataSetChanged();
}
}