public class MainActivity extends Activity implements OnClickListener {
private ListView listView;
private AutoCompleteTextView mAutoText;
private Button mBT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("TAG","onCreate");
mBT =(Button)findViewById(R.id.button1);
listView = (ListView)findViewById(R.id.listView1);
mAutoText=(AutoCompleteTextView)findViewById(R.id.AutoCompleteTextView);
mBT.setOnClickListener(this);
displayDate("history",mAutoText);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Log.e("TAG","onClickButton");
// String etString = at.getText().toString();
saveData("history", mAutoText);
break;
}}
private void saveData(String field,AutoCompleteTextView auto){
SharedPreferences preferences = getSharedPreferences("fiona",0);
String city = mAutoText.getText().toString();
String history = preferences.getString("history", "nothing");
StringBuilder sb = new StringBuilder(history);
sb.append(city+",");
Editor editor = preferences.edit();
editor.putString("history",sb.toString());
editor.commit();
Log.e("TAG","saveData");
}
private void displayDate(String field,AutoCompleteTextView auto) {
Log.e("TAG","displayDate");
//获取SP对象
SharedPreferences sp = getSharedPreferences("fiona", 0);
//获取字段
String longhistory = sp.getString("history", " ");
//把字符串分割成字符串数组
String[] hisArrays = longhistory.split(",");
//把数组显示到AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, hisArrays);
listView.setAdapter(adapter);
xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp" >
</ListView>
<AutoCompleteTextView
android:id="@+id/AutoCompleteTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/listView1"
android:layout_alignParentTop="true"
android:layout_marginTop="46dp"
android:ems="10"
android:text="" >
<requestFocus />
</AutoCompleteTextView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/listView1"
android:layout_alignTop="@+id/AutoCompleteTextView"
android:text="Button" />
</RelativeLayout>