我有一个应用程序可以保存youtube搜索的查询标记列表。用户在Main活动的editText中输入搜索,当用户按下保存按钮时,该搜索将保存在ListActivity的ListView中。问题是当我关闭应用程序并再次打开它时,保存的搜索消失了。我使用SharedPreferences保存搜索,但无法让我的ListView用保存的搜索填充它。有人可以给我一些关于如何使用SharedPreferences检索保存在ListView中的数据的方向吗?我的代码如下。
//This is the Main Activity
public class Main extends Activity {
Button save;
EditText text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//NEW
final WebView browser = (WebView) findViewById(R.id.webview);
browser.setWebViewClient(new MyBrowser());
browser.setBackgroundColor(Color.TRANSPARENT);
Button buttonSearch = (Button) findViewById(R.id.searchButton);
Button buttonSave = (Button) findViewById(R.id.saveButton);
Button buttonFav = (Button) findViewById(R.id.favButton);
Button buttonCancel = (Button) findViewById(R.id.cancelButton);
final EditText textItem = (EditText) findViewById(R.id.queryEditText);
final ArrayList<String> arr = new ArrayList<String>();
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String item = textItem.getText().toString();
arr.add(item);
//Add saved search to shared preferences
SharedPreferences sharedPref = getSharedPreferences("favs", 0);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("fav", item);
editor.commit();
textItem.setText("");
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
});
buttonSearch.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String sQuery = textItem.getText().toString();
browser.getSettings().setLoadsImagesAutomatically(true);
browser.getSettings().setJavaScriptEnabled(true);
browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
browser.loadUrl(getString(R.string.searchURL) + sQuery);
browser.setVisibility(v.VISIBLE);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
});
buttonFav.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ListActivity.class);
intent.putExtra("array_list", arr);
textItem.setText("");
startActivity(intent);
}
});
buttonCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
browser.setVisibility(v.GONE);
textItem.setText("");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
ListActivity
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class ListActivity extends Activity {
EditText searchTxt;
ListView lv;
StringArrayAdapter ad;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
Button backButton = (Button) findViewById(R.id.backButton);
searchTxt = (EditText) findViewById(R.id.searchText);
Bundle b = getIntent().getExtras();
SharedPreferences sharedPref = getSharedPreferences("array_list", 0);
String listItem = sharedPref.getString("fav", "");
lv = (ListView) findViewById(R.id.listViewItem);
final ArrayList<String> arr = (ArrayList<String>) b.getStringArrayList("array_list");
lv.setTextFilterEnabled(true);
ad = new StringArrayAdapter(arr, this);
lv.setAdapter(ad);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
ad.items.remove(position);
ad.notifyDataSetChanged();
ad.notifyDataSetInvalidated();
return false;
}
});
searchTxt.addTextChangedListener(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) {
ad.getFilter().filter(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String query = lv.getItemAtPosition(position).toString();
String urlString = getString(R.string.searchURL) + query;
Intent getURL = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
startActivity(getURL);
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Main.class);
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
StringArrayAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by tobyblanchard on 11/14/14.
*/
public class StringArrayAdapter extends BaseAdapter implements Filterable {
ArrayList<String> items;
Context ctxt;
LayoutInflater myInflater;
public StringArrayAdapter(ArrayList<String> arr, Context c){
items = arr;
ctxt = c;
myInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = myInflater.inflate(android.R.layout.simple_list_item_activated_1, parent, false);
TextView name = (TextView)convertView.findViewById(android.R.id.text1);
name.setText(items.get(position));
return convertView;
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArraylist = new ArrayList<String>();
if (items == null){
items = new ArrayList<String>(items);
}
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = items.size();
results.values = items;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < items.size(); i++) {
String data = items.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArraylist.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArraylist.size();
results.values = FilteredArraylist;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
items = (ArrayList<String>) results.values; // has the filtered values
notifyDataSetChanged();
}
};
return filter;
}
}