为什么第一行老显示null?
总是只能查询上一步操作所填入的数据!
EditView id=text_friend 按钮id=publish
listView id=obtain
ListView中:
public class FirendSend extends Activity {
private EditText text_friend;
private SharedPreferences sp;
private SharedPreferences.Editor editor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friend_send);
Button Button_back=(Button)findViewById(R.id.back);
sp = getSharedPreferences("data", MODE_PRIVATE);
editor = sp.edit();
Button button = (Button) findViewById(R.id.publish);
text_friend = (EditText) findViewById(R.id.text_friend);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String txt = sp.getString("text", null);
editor.putString("text", txt + ";;;"
+ text_friend.getText().toString());
editor.commit();
Toast.makeText(FirendSend.this, "发表成功", Toast.LENGTH_SHORT).show();
}
});
Button_back.setOnClickListener(new ExitClickListener());
}
class ExitClickListener implements OnClickListener{
public void onClick(View v){
System.exit(0);
}
}
}
EditView中:
public class Firend extends Activity {
private SharedPreferences sp;
private ImageButton imageButton;
private ArrayList texts;
private ListView obtain;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_friend);
initData();
obtain = (ListView) findViewById(R.id.obtain);
imageButton = (ImageButton) findViewById(R.id.submit);
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(Firend.this, "欢迎进入", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Firend.this, FirendSend.class);
startActivity(intent);
}
});
obtain.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, texts));
}
private void initData() {
// TODO Auto-generated method stub
sp = getSharedPreferences("data", MODE_PRIVATE);
String str = sp.getString("text", null);
texts = new ArrayList<String>();
while (str != null && str.length()> 0) {
int index = str.indexOf(";;;");
if (index <= 0)
{
return;
}
texts.add(str.substring(0, index));
str = str.substring(index + 3);
}
}
}
用Bundle传递,在startActivity的时候,给Intent设置一个Bundle,如下
Bundle bundler = new Bundle();
bundler.putString("TEST", "test");
intent.putExtras(bundler);
第一行总显示null,是因为你初次进入FirendSend的时候在保存数据的时候,根据你上面保存数据的代码:
首先执行String txt = sp.getString("text", null);得到txt的值为null;
然后你执行txt + ";;;"+ text_friend.getText().toString()也就相当于null+";;;"+text_friend.getText().toString()",其结构就是“null;;;xxxx”
之后当你再进行解析的时候,第一行自然就是“null”了。
是不是你绑定数据没更新