2013年1月24日 星期四

[Android]用intent將SDCard的路徑傳送到另一個Activity的ListView顯示

Activity to Activity   使用intent    傳送SDCard的路徑 給ListView顯示

主程式一:
public class MainActivity extends Activity {
//宣告button
        private Button bt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
                //宣告button物件及點擊事件
bt1 = (Button)this.findViewById(R.id.bt1);
bt1.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
                                //設定sdcard路徑
File file = new File("/sdcard"); 
                                //取得檔案清單並丟到String array中    
String filelist[] = file.list();  
Intent intent = new Intent();
Bundle bundle = new Bundle();
                                //設定本地class跟目的class 記得將ma2註冊在AndroidManifest.xml中
intent.setClass(MainActivity.this,ma2.class);
                                //將filelist這個StringArrat 放進bundle中 標籤為sdlist  ,put的資料型態要注意
bundle.putStringArray("sdlist", filelist);
intent.putExtras(bundle);
startActivity(intent);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
});
}
主程式二:

public class ma2 extends Activity {
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.ma2);
                //設定listview
lv = (ListView)this.findViewById(R.id.lv);
//設定intent 及bundle並解開
                Intent intent= this.getIntent();
Bundle bundle = intent.getExtras();
                //取資料丟到一個string中
final String filelist[] = bundle.getStringArray("sdlist");
System.out.println(filelist);//會出現[Ljava.lang.String;@405275e8 是正常 因為是對應位址(隨機)
        //設定ArrayAdapter並將filelist丟進去顯示
        ArrayAdapter aad = new ArrayAdapter(this, android.R.layout.simple_list_item_1,filelist);
        lv.setAdapter(aad);
        }     
}
執行結果:

點擊開啟sdcard的按鈕會將sdcard路徑丟到intent傳到ma2 並存在ma2的ArrayAdapter容器中給listview顯示出來 如下圖:


大家可能會認為 為什麼不到這一層再顯示就好 還要設一個intent傳送sdcard的路徑
一方面是練習用 intent傳各種資料 接下來會想玩session或是 List
一方面 我可以設定不同的按鈕來傳不同的路徑
ma2負責取得並顯示filelist 但 不一定filelist就是sdcard路徑
若我想土法煉鋼寫一個直接打開/video 的按鈕 另外寫好路徑傳給ma2他就會如實的show出來了
好維護!


無意間看到一篇文章寫道:

activity间互传list是很讲究的,推荐使用如下方式:
List names = new ArrayList();
names.add("cc");
Intent intent = new Intent(IntentActivity.this, SecActivity.class);
intent.putExtra("names", (Serializable)names);
startActivity(intent);
 传递的值必须确保它实现了Serializable接口
留著供存查 希望以後需要時可以派上用場!












沒有留言:

張貼留言