String path = "/mnt/sdcard/mydata/" ArrayList<String> myArr = new ArrayList<String>(); File[] files = file.listFiles(); for (File sfil : files) { if(sfil.isFile()) { String fileName = sfil.toString().substring( sfil.toString().lastIndexOf('/')+1, sfil.toString().length()); // myArr.add(sfil.toString()); // full path myArr.add(fileName); } }
String path = "/mnt/sdcard/mydata/" ArrayList<String> myArr = new ArrayList<String>(); File[] files = file.listFiles(); for (File sfil : files) { if(sfil.isDirectory()) { myArr.add(sfil.toString()); } }
<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" > <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" > </ListView> </RelativeLayout>
package com.myapp; import java.io.File; import java.util.ArrayList; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /*** Read Text File SD Card ***/ try { String sdcard = Environment.getExternalStorageDirectory() .toString(); // /mnt/sdcard/ String path = sdcard + "/mydata/"; // or path = "/mnt/sdcard/mydata/"; File file = new File(path); ArrayList<String> myArr = new ArrayList<String>(); // List File File[] files = file.listFiles(); for (File sfil : files) { if(sfil.isFile()) { String fileName = sfil.toString().substring( sfil.toString().lastIndexOf('/')+1, sfil.toString().length()); // myArr.add(sfil.toString()); // full path myArr.add(fileName); } } // List Directory /* File[] files = file.listFiles(); for (File sfil : files) { if(sfil.isDirectory()) { myArr.add(sfil.toString()); } } */ file = null; // listView1 final ListView lisView1 = (ListView) findViewById(R.id.listView1); // ArrayList to Array String[] myData = {}; myData = myArr.toArray(new String[myArr.size()]); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myData); lisView1.setAdapter(adapter); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(MainActivity.this, "Failed! = " + e.getMessage(), Toast.LENGTH_LONG).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท