I've created a file manager that I will use in my other program, however I am having problems with it. It displays a list of files on my android phone, and I can click through one folder deep, however going more than one it stops working. Mainly I think because of "if(K.getAbsoluteFile().isDirectory()==true)", if I get rid of this line though it simply crashes. So it seems to only allow me to go one folder deep, can anyone figure out what I've done wrong here?
Also any guides or what have you on this topic would be appreciated, its kind of a mangling of random code I've found.
package book.BouncySquare;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class FileManager extends ListActivity {
public File clickedFile = null;
private List<String> directoryEntries = new ArrayList<String>();
//private List<String> directoryEntries = new ArrayList<String>();
private File currentDirectory = new File("/");
#Override
public void onCreate(Bundle icicle) {
Log.d("startx", "start");
super.onCreate(icicle);
browseToRoot();
}
public void browseToRoot() {
Log.d("Browse", "browse"+currentDirectory.getAbsoluteFile());
browseTo(new File("/"));
}
private void browseTo(File file) {
Log.d("mew", "too");
if(file.isDirectory()){
Log.d("check", "it");
fill(file); }
}
private void browse(String x) {
Log.d("created", "newfile");
final File K=new File(x);
Log.d("broke", "ass");
if(K.getAbsoluteFile().isDirectory()==true){
Log.d("Z"+K.getAbsoluteFile(), "directory");
fill(K.getAbsoluteFile());}
else{
Log.d("X"+K.getName(), "NotADirectoryOrHidden");
Log.d("A"+K.getAbsoluteFile(), "directory");
}
}
private void fill(File files) {
File[] meow=null;
this.directoryEntries.clear();
meow= files.listFiles();
Log.d("sss", "sss");
this.directoryEntries.add(getString(R.string.current_dir));// directoryentries is an arraylist that holds our Directories names
this.directoryEntries.add(getString(R.string.up_one_level));
for (File file : meow) {
this.directoryEntries.add(file.getName()); //fill our string array directoryentries with each files getName, then we pass it to arrayAdapter to populate
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,R.layout.file_row, this.directoryEntries); //our context,layout, and array of directories is created
this.setListAdapter(directoryList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String clickedEntry =this.directoryEntries.get((int) id);
Log.d("clickedID="+id, "clickedPosition="+clickedEntry);
browse(clickedEntry);
}
}
Try prepending your current directory to what you are wanting to list.
private void browse(String x) {
Log.d("created", "newfile");
final File K=new File(currentDirectory, x);
Log.d("broke", "ass");
if(K.getAbsoluteFile().isDirectory()==true){
Log.d("Z"+K.getAbsoluteFile(), "directory");
currentDirectory = K.getAbsoluteFile();
fill(K.getAbsoluteFile());}
else{
Log.d("X"+K.getName(), "NotADirectoryOrHidden");
Log.d("A"+K.getAbsoluteFile(), "directory");
}
}
Related
I'm writing a DialogFragment for browsing the filesystem, which works really nice by now. I just got one Problem.
The files are shown in an ListView, and when the user selects a file, this event is send to the Activity that has called the Fragment over an OnFileSelectedListener-Interface. This is fine for files, but it feels wrong to send out the directory names to the activity, then destroying and recreating the Fragment, when all that should happen is that the Fragment should show a new Directory. It also makes the whole Fragement disapearing and then reapearing which isn't really nice and smooth.
Furthermore every Activity using the Fragment has to use the logic for recreating the Fragment, which is far from "don't repeat yourself".
So, in short, is there a way to do a changeout of the Listview within the Fragment? Calling the AlertDialog.Builder more than once sadly doesn't work.
Heres my DialogFragment. I hope it's ok to post the whole thing:
package de.fusionsystems.firmenlaufmonitor;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FileChooserFragment extends DialogFragment {
private OnFileSelectedListener mCallback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return createDialog();
}
private AlertDialog createDialog(){
// Create the AlertDialog object and return it
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
ArrayList<File> files = getFilesInDir(options.getString("BaseDir", ""));
ArrayList<ListEntry> fileEntries = new ArrayList<ListEntry>();
if (!isBaseDir(options.getString("BaseDir", ""))){
fileEntries.add(new ListEntry("..", getResources().getDrawable( R.drawable.ic_folder)));
}
for (File file : files){
if (file.isDirectory()){
fileEntries.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_folder)));
}else{
if (file.getName().endsWith(".kml")){
fileEntries.add(new ListEntry(file.getName(),getResources().getDrawable( R.drawable.ic_file)));
}
}
}
final FileAdapter adapter = new FileAdapter(getActivity(), fileEntries);
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String path;
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (adapter.getItem(which).name.equals("..")){
//navigate back
path = options.getString("BaseDir", "/");
path=path.substring(0, path.length());
path=path.substring(0,path.lastIndexOf("/"));
path = !path.equals("")?path:("/");
}else {
path = options.getString("BaseDir", "");
path += ((path.equals("/"))?(""):("/"))+adapter.getItem(which).name;
}
Log.d("Path", path);
Editor editor = options.edit();
File dirTest = new File(path);
if (dirTest.isDirectory()){
editor.putString("BaseDir", path);
editor.commit();
//mCallback.onFileSelected("");
//createDialog();
//*******************DO THE RIGHT THING HERE***********************
}else{
mCallback.onFileSelected(path);
}
}
};
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setAdapter(adapter, clickListener)
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
builder.setTitle("Datei wählen");
return builder.create();
}
private ArrayList<File> getFilesInDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.e("FileBrowser","Something's really fishy");
}
}
ArrayList<File> fileList = new ArrayList<File>(Arrays.asList(folder.listFiles()));
return fileList;
}
private boolean isBaseDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.e("FileBrowser","Something's really fishy");
}
}
File baseDir = new File("/");
if (folder.equals(baseDir)){
return true;
}else{
return false;
}
}
// Container Activity must implement this interface
public interface OnFileSelectedListener {
public void onFileSelected(String file);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFileSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
class ListEntry {
public String name;
public Drawable item ;
public ListEntry(String name, Drawable item) {
this.name = name;
this.item = item;
}
}
class FileAdapter extends ArrayAdapter<ListEntry>{
public FileAdapter(Context context, ArrayList<ListEntry> fileEntry) {
super(context, R.layout.filechooser_list_item,fileEntry);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ListEntry entry = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.filechooser_list_item, parent, false);
}
// Lookup view for data population
TextView filechooserEntry = (TextView) convertView.findViewById(R.id.filechooser_entry);
// Populate the data into the template view using the data object
filechooserEntry.setText(entry.name);
filechooserEntry.setCompoundDrawablesWithIntrinsicBounds(entry.item, null, null, null);
// Return the completed view to render on screen
return convertView;
}
}
}
Here's my solution for a Filebrowser as a DialogFragment. It turns out there are methods to add() remove() and clean() items to the adapter, so the answer to the initial question was real simple. The tricky part was to prevent the Dialog from closing after selecting a List item. This answer helped a lot: https://stackoverflow.com/a/15619098/3960095. Here's my working code for future visitors:
package de.yourCompany.yourProject;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FileChooserFragment extends DialogFragment{
private OnFileSelectedListener mCallback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Create the AlertDialog object and return it
final FileAdapter adapter = new FileAdapter(getActivity(), new ArrayList<ListEntry>());
adapter.getFiles();
OnClickListener clickListener = new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//do nothing here to prevent dismiss after click
}
};
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setAdapter(adapter, clickListener)
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.setTitle("Datei wählen");
final AlertDialog theDialog = builder.show();
theDialog.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String path;
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (adapter.getItem(position).name.equals("..")){
//navigate back
path = options.getString("BaseDir", "/");
path=path.substring(0, path.length());
path=path.substring(0,path.lastIndexOf("/"));
path = !path.equals("")?path:("/");
}else {
//get the Slashes right and navigate forward
path = options.getString("BaseDir", "");
path += ((path.equals("/"))?(""):("/"))+adapter.getItem(position).name;
}
Editor editor = options.edit();
File dirTest = new File(path);
if (dirTest.isDirectory()){
editor.putString("BaseDir", path);
editor.commit();
adapter.clear();
adapter.getFiles();
}else{
mCallback.onFileSelected(path);
theDialog.dismiss();
}
}
});
return theDialog;
}
private boolean isBaseDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.wtf("FileBrowser","Something's really fishy");
}
}
File baseDir = new File("/");
if (folder.equals(baseDir)){
return true;
}else{
return false;
}
}
// Container Activity must implement this interface
public interface OnFileSelectedListener {
public void onFileSelected(String file);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnFileSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
class ListEntry {
public String name;
public Drawable item ;
public ListEntry(String name, Drawable item) {
this.name = name;
this.item = item;
}
}
class FileAdapter extends ArrayAdapter<ListEntry>{
//show only files with the suffix FILE_SUFFIX, use "*" to show all files;
private static final String FILE_SUFFIX = ".kml";
public FileAdapter(Context context, ArrayList<ListEntry> fileEntry) {
super(context, R.layout.filechooser_list_item,fileEntry);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ListEntry entry = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.filechooser_list_item, parent, false);
}
// Lookup view for data population
TextView filechooserEntry = (TextView) convertView.findViewById(R.id.filechooser_entry);
// Populate the data into the template view using the data object
filechooserEntry.setText(entry.name);
filechooserEntry.setCompoundDrawablesWithIntrinsicBounds(entry.item, null, null, null);
// Return the completed view to render on screen
return convertView;
}
private FileAdapter getFiles() {
SharedPreferences options = PreferenceManager.getDefaultSharedPreferences(getActivity());
ArrayList<File> files = getFilesInDir(options.getString("BaseDir", ""));
if (!isBaseDir(options.getString("BaseDir", ""))){
this.add(new ListEntry("..", getResources().getDrawable( R.drawable.ic_folder)));
}
for (File file : files){
if (file.isDirectory()){
this.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_folder)));
}else{
if (file.getName().endsWith(FILE_SUFFIX)||FILE_SUFFIX.equals("*")){
this.add(new ListEntry(file.getName(),getResources().getDrawable(R.drawable.ic_file)));
}
}
}
return this;
}
private ArrayList<File> getFilesInDir(String dir) {
File folder = new File(dir);
if (!folder.exists()){
folder = new File("/");
if (!folder.exists()){
Log.wtf("FileBrowser","Something's really fishy");
}
}
ArrayList<File> fileList;
if (folder.listFiles()!=null){
fileList = new ArrayList<File>(Arrays.asList(folder.listFiles()));
}else{
fileList = new ArrayList<File>();
}
return fileList;
}
}
}
and in your Activity:
public class YourActivity extends Activity implements FileChooserFragment.OnFileSelectedListener{
#Override
public void onFileSelected(String file) {
//Do whatever you want to do with the files
}
// And whereever you want to start the Fragment:
FileChooserFragment fileFragment = new FileChooserFragment();
fileFragment.show(getFragmentManager(), "fileChooser");
I have been busy with school and all that and currently working on an android multimedia app i'd like to use. i created a list and was able to filter the files on the sdcard (both .mp3s and .mp4s) but i have a problem. i want the app to launch activities i created (HomeaudioActivity, which deals with .mp3 files and HomevideoActivity, which deals with video files) when selected from the list (i created a class and called it "AllMediaActivity". in this activity, the whole media files have been pulled from the sdcard) based on its extension.
please i'm confused at this, i wrote some codes and i'm stuck at somewhere. below is the code with the issue, please where did i go wrong?
package com.src.imagine.playmedia;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListActivity;
public class AllPlayListActivity extends SherlockListActivity {
// All the lists
public ArrayList<HashMap<String, String>> aMediaList = new ArrayList<HashMap<String, String>>();
Intent in;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
ArrayList<HashMap<String, String>> aMediaListData = new ArrayList<HashMap<String, String>>();
AllMediaManager amm = new AllMediaManager();
// getting all the songs from sdcard
this.aMediaList = amm.getPlayList();
// lopping through the playlist
for (int i = 0; i < aMediaList.size(); i++) {
// creating new HashMap
HashMap<String, String> media = aMediaList.get(i);
// adding HashList to ArrayList
aMediaListData.add(media);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, aMediaListData,
R.layout.playlist_item, new String[] { "mediaTitle" },
new int[] { R.id.songTitle });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
final int mediaIndex = position;
#SuppressWarnings("unused")
class FileExtensionFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
if (name.endsWith(".mp3") || name.endsWith(".MP3")) {
// Starting new intent
in = new Intent(getApplicationContext(),HomeAudioActivity.class);
// Sending mediaIndex to the audioPlayerActivity
in.putExtra("songIndex", mediaIndex);
setResult(100, in);
// closing playlistview
finish();
} else if (name.endsWith(".mp4")
|| name.endsWith(".MP4")
|| name.endsWith(".h.264 avc")
|| name.endsWith(".H.264 AVC")
|| name.endsWith(".h.263")
|| name.endsWith(".H.263")
|| name.endsWith(".mpeg-4 sp")
|| name.endsWith(".MPEG-4 SP")
|| name.endsWith(".mpeg-4")
|| name.endsWith(".MPEG-4")
|| name.endsWith(".vp8")
|| name.endsWith(".VP8")) {
// Starting new Intent
in = new Intent(getApplicationContext(), HomeVideoActivity.class);
// Sending mediaIndex to the videoPlayerActivity
in.putExtra("videoIndex", mediaIndex);
setResult(100, in);
// closing playlistView
finish();
} else {
Toast.makeText(getApplicationContext(),
"Unsupported video format",Toast.LENGTH_SHORT).show();
}
return false;
}
}
}
});
}
}
http://www.androidsnippets.com/open-file-with-default-application-using-intents
google -> "android open file in default application" -> this post.
might help.
You have written FileExtensionFilter class that has never been used. I am not sure if you are getting all media list.
You may refer here for further details.
I am creating an intent to play videos stored in the sdcard. It happens that I play the first one, everything is OK. But when I play another one, it just plays everytime the first one I played. Here is my code:
package com.remote;
import java.io.File;
import java.io.IOException;
import com.remote.R.drawable;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.VideoView;
public class MyVideos extends Activity{
private String path="/sdcard/Movies/Telmex";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myvideos);
createLinks(new File(path));
}
public void createLinks(File path)
{
LinearLayout layout = (LinearLayout) findViewById(R.id.myvideoslayout);
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++)
{
if(files[i].getName().toString().charAt(0)!='.')
{
String videoName;
Button video=new Button(this);
video.setBackgroundColor(2);
video.setTextSize(23);
video.setCompoundDrawablesWithIntrinsicBounds(0,0,drawable.videoicon,0);
videoName=new String(files[i].getName());
video.setText(videoName);
createListener(video,videoName);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
layout.addView(video,p);
}
}
}
}
public void createListener(Button video, final String name)
{
video.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
videoPlayer(path,name,true);
}
});
}
public void videoPlayer(String path, String fileName, boolean autoplay)
{
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse(path+"/"+fileName);
intent.setDataAndType(data, "video/mp4");
startActivity(intent);
}
}
Rewrite
I did some digging and wrote the code below, if this has the same problem then it is your external video player not you app.
public class ExampleActivity extends Activity {
// Change this path
private final String path = Environment.getExternalStorageDirectory() + "/android/data/com.example/files/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File dir = new File(path);
List<String> files = new ArrayList<String>();
Collections.addAll(files, dir.list());
Collections.sort(files);
while(files.get(0).startsWith("."))
files.remove(0);
ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String uri = path + ((TextView) view).getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(uri), "video/*");
startActivity(intent);
}
});
}
}
Addition
I'm glad the internal video player works. The reason why it resets is that every time you change orientation the OS destroys and rebuilds your app from scratch... It's the same as if you exited the app by pressing the back button and ran it again. If you are using the tutorial from below, you need to save the video's location in onDestroy() to a class variable and in your onCreate() check to see if that variable has a valid location or just start at the beginning of the video.
I am trying to display the steps to a recipe, the recipe is stored in a string array.
Im trying to get each step to be inserted into a text view, and have the following code:
public class MethodActivity extends ListActivity{
ListView recipes;
Intent myIntent;
String value;
TextView editvalue;
Intent intent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipemethod);
editvalue = (TextView)findViewById(R.id.method);
value = getIntent().getStringExtra("searchValue");
editvalue.setText(value);
final String[] words = getResources().getStringArray(R.array.Lasagna);
final TextView tw=(TextView)findViewById(R.id.method);
for(int item = 0;item<words.length;item++){
tw.setText(words [item]);
}
}
}
I am also wanting to make it dynamic so does anyone know how I can do that? (e.g. depending on what the user clicked that recipe is shown).
Thanks
It might be easier to actually use your ListActivity's ListView... You can even show your recipe in another ListView, as it will undoubtedly be more intuitive for the user...
A simple code that does this would go somewhat in the following lines:
File 1: RecipeListActivity.java (shows list of recipes)
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
Intent intent = new Intent(this, RecipeActivity.class);
intent.putExtra(RecipeActivity.EXTRA_RECIPEARRAY, mRecipesArray[position].steps);
startActivity(intent);
}
}
File 2: RecipeActivity.java (shows a recipe in a list)
package com.epichorns.testproject;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class RecipeActivity extends ListActivity {
final static public String EXTRA_RECIPEARRAY = "recipeArray";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] recipeArray = getIntent().getStringArrayExtra(EXTRA_RECIPEARRAY);
if(recipeArray!=null){
if(recipeArray.length>0){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, recipeArray);
setListAdapter(adapter);
}
}
}
}
Alternately, here is a code which composites a TextView below the recipes list in order to show the recipe content without opening another Activity:
File: RecipeListActivity.java
package com.epichorns.testproject;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RecipeListActivity extends ListActivity {
final Recipe[] mRecipesArray = { new Recipe("Lasagna", new String[]{"Some lasagna noodles", "Some tomato sauce"}),
new Recipe("PortalCake", new String[]{"GlaDOS' wit","Is a lie"}),
new Recipe("EarthDestruction", new String[]{"Asteroid", "Kinetic energy"})};
TextView mTextView_recipeTitle;
TextView mTextView_recipe;
public class Recipe{
public String name;
public String[] steps;
Recipe(String name, String[] steps){
this.name = name;
this.steps = steps;
}
}
public ArrayList<String> FetchRecipesRawArray(Recipe[] recipes){
ArrayList<String> ret = new ArrayList<String>();
for(int i=0;i<recipes.length;i++){
ret.add(recipes[i].name);
}
return ret;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView_recipe = (TextView)findViewById(R.id.recipeText);
mTextView_recipeTitle = (TextView)findViewById(R.id.recipeTitle);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FetchRecipesRawArray(mRecipesArray));
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
mTextView_recipeTitle.setText(mRecipesArray[position].name);
mTextView_recipe.setText("");
String[] recipeSteps = mRecipesArray[position].steps;
for(int i=0;i<recipeSteps.length;i++){
mTextView_recipe.append(recipeSteps[i]+"\n");
}
}
}
File: main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="#400000FF"
/>
<TextView
android:id="#+id/recipeTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#4000FF00"
/>
<TextView
android:id="#+id/recipeText"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#40FF0000"
/>
</LinearLayout>
You will want to use tw.append() instead of setText, otherwise all you will ever see is the last string in the array.
Make it dynamic, I would use a fragments (using the Android Support Library if on older android versions) model, load each array, attaching the string array as a bundle to the fragment before launching.
Fragment tut:http://developer.android.com/guide/topics/fundamentals/fragments.html
Support library: http://developer.android.com/training/basics/fragments/support-lib.html
Im starting to work with Honeycomb, and im trying to make a simple fragmented layout with the list of file on the left side, and the details of the file on the right (when a file is selected). Well, it was going well until I actually tried to list the files, and now I just get a "/" slash, and thats it. Nothing else. I set up a log to track the number of files in the directory im in, and it sees 26, but it wont list them. Heres my code
package com.bv.dual_fragments;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class fragment_one extends ListFragment{
private File currentDirectory = new File("/");
private List<String> directoryEnteries = new ArrayList<String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.fragment_one,container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
//Inflate the layout for this fragment
super.onCreate(savedInstanceState);
//Browse to root directory
browseTo(new File("/"));
}
private void upOneLevel() {
if (this.currentDirectory.getParent() !=null) {
this.browseTo(this.currentDirectory.getParentFile());
}
}
private void browseTo(final File aDirectory) {
//if we want to browse directory
if (aDirectory.isDirectory()){
this.currentDirectory = aDirectory;
Integer fileLength = aDirectory.listFiles().length;
Log.i("File",fileLength.toString() );
File[] files = new File[fileLength];
for (File file : files) {
Log.i("File", file.getAbsolutePath());
}
fill(aDirectory.listFiles());
//set the titlemanger text
TextView titleManager = (TextView)getView().findViewById(R.id.titlemanager);
titleManager.setText(aDirectory.getAbsolutePath());
} else {
//if we want o open file, show this dialog:
//listener when Yes button clicked
OnClickListener okButtonListener = new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//intent to navigate file
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("file://" + aDirectory.getAbsolutePath()));
startActivity(i);
}
};
OnClickListener cancelButtonListener = new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
};
//create dialog
new AlertDialog.Builder(getActivity())
.setTitle("Dialog Title")
.setMessage("File Name " + aDirectory.getName() + "?")
.setPositiveButton("Ok", okButtonListener)
.setNegativeButton("No", cancelButtonListener)
.show();
}
}
private void fill(File[] files) {
//clear the list
this.directoryEnteries.clear();
if (this.currentDirectory.getParent() != null)
this.directoryEnteries.add("..");
//add every file in the list
for (File file : files) {
this.directoryEnteries.add(file.getAbsolutePath());
}
//create array adapter to show everything
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(getActivity(), R.layout.row, directoryEnteries);
this.setListAdapter(directoryList);
}
}
So, it runs, I got my fragments to layout,but it wont list the files. Any help would be appreciated. Oh, when I try to put in a for loop to add each name of the files to my log, it gives a nullpoint exception
Edit: I think I have chased it down to the resource file for the Row that its actually using, which is R.layout.row, but I dont see whats wrong. Heres the layout for that file
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="40sp"
android:padding="5dip"
android:background="#color/white"
android:gravity="center_vertical"/>
Add the follow after the call to
//Browse to root directory
browseTo(new File("/"));
ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setCacheColorHint(Color.TRANSPARENT);