Intent to play a video always plays the same one - android

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.

Related

AppCompatCallback error on setSupportActionBar

In this activity I have an implementaion with AppCompatCallback and a delegate who set my toolbar , I have this thing for other 2 activitys and works fine , but here i get an error to the line delegate1.setSupportActionBar(toolbar).. I don't understand why...
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatCallback;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class AlbumActivity extends Activity implements AppCompatCallback {
private final int REQUEST_CODE_CAMERA_IMAGE = 1000;
private final int REQUEST_CODE_EXTERNAL_IMAGE = 2000;
private AppCompatDelegate delegate1;
String nameAlbum;
// Declare variables
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
GridView grid;
GridViewAdapter adapter;
File file;
boolean deleted;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate1 = AppCompatDelegate.create(this, this);
//call the onCreate() of the AppCompatDelegate
delegate1.onCreate(savedInstanceState);
//use the delegate to inflate the layout
delegate1.setContentView(R.layout.album_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.mytoolbarr);
delegate1.setSupportActionBar(toolbar);
delegate1.setTitle("Your Pictures");
Button btnChoosePicture = (Button) findViewById(R.id.addimage);
Intent intent = getIntent();
nameAlbum = intent.getStringExtra("nameAlbum");
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
.show();
} else {
// Locate the image folder in your SD Card
file = new File(Environment.getExternalStorageDirectory()
+ File.separator + nameAlbum);
if (file.isDirectory()) {
listFile = file.listFiles();
// Create a String array for FilePathStrings
FilePathStrings = new String[listFile.length];
// Create a String array for FileNameStrings
FileNameStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++) {
// Get the path of the image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
// Locate the GridView in gridview_main.xml
grid = (GridView) findViewById(R.id.gridview);
// Pass String arrays to LazyAdapter Class
adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
// Set the LazyAdapter to the GridView
grid.setAdapter(adapter);
// Capture gridview item click
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(AlbumActivity.this, ViewImage.class);
// Pass String arrays FilePathStrings
i.putExtra("filepath", FilePathStrings);
// Pass String arrays FileNameStrings
i.putExtra("filename", FileNameStrings);
// Pass click position
i.putExtra("position", position);
startActivity(i);
}
});
grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, final View view, final int position, final long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(AlbumActivity.this);
builder.setCancelable(true);
builder.setMessage("Are you sure you want to delete this picture ?");
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File filepath = Environment.getExternalStorageDirectory();
File dir5 = new File(filepath.getAbsolutePath()
+ nameAlbum+FileNameStrings[position]);
File file3 = new File(String.valueOf(dir5));
deleted = file3.delete();
adapter.notifyDataSetChanged();
finish();
startActivity(getIntent());
dialog.dismiss();
}
});
builder.setTitle("Delete Picture");
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
}
//select picture from external storage
btnChoosePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// choose picture from gallery
Intent PhotoPickerIntent = new Intent(
Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
PhotoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(PhotoPickerIntent,
REQUEST_CODE_EXTERNAL_IMAGE);
}
});
}
#Override
but here i get an error to the line delegate1.setSupportActionBar(toolbar)
It can be two differents things :
You've imported android.widget.Toolbar instead of android.support.v7.widget.Toolbar
Your Activity has to extends AppCompatActivity if you want to use setSupportActionBar(toolbar)
If you extends AppCompatActivity you have to use Theme.AppCompat.Light.NoActionBar
#Skizo here everything works fine and extends Activity...
public class EnterDataActivity extends Activity implements AppCompatCallback {
private AppCompatDelegate delegate;
EditText editTextPersonName;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate = AppCompatDelegate.create(this, this);
//call the onCreate() of the AppCompatDelegate
delegate.onCreate(savedInstanceState);
//use the delegate to inflate the layout
delegate.setContentView(R.layout.enter_data);
editTextPersonName = (EditText) findViewById(R.id.et_person_name);
Toolbar toolbar= (Toolbar) findViewById(R.id.mytoolbar2);
delegate.setSupportActionBar(toolbar);
delegate.setTitle("Enter Album Name");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}else if(id==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
public void onClickAdd (View btnAdd) {
String personName = editTextPersonName.getText().toString();
if ( personName.length() != 0 ) {
Intent newIntent = getIntent();
newIntent.putExtra("tag_person_name", personName);
this.setResult(RESULT_OK, newIntent);
finish();
}
}
#Override
public void onSupportActionModeStarted(ActionMode mode) {
}
#Override
public void onSupportActionModeFinished(ActionMode mode) {
}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
}
I did solved my issue , I had to include my toolbar layout in my activity layout... Thank you everyone for interest in solving my issue!!

Display files on listview with MetaDataRetriver Android

The activity below has an edittext and a search button for the files of Downloads directory,
when I click the button shows me the mp3 files by title in a listview. Now the promblem is that I don't need the edittext and the search button, I want only the listview to show on activity launch. How can I achieve that.
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class DirMusic extends Activity {
ListView listSongs;
ArrayList<Song> songs;
EditText editTitle;
File musicFolder;
LinearLayout songsView;
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// search for songs on restore
searchSongs(null);
}
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_dir_music);
// get the list of files and place them in ListView
listSongs = (ListView) this.findViewById(R.id.listSongs);
editTitle = (EditText) this.findViewById(R.id.editTitle);
songsView = (LinearLayout) this.findViewById(R.id.songsView);
// songsView.setVisibility(View.INVISIBLE);
// songsView.setVisibility(View.VISIBLE);
musicFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
listSongs.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> view, View item,
int position, long id) {
// Play song using built-in audio player
String filename = songs.get(position).getFilename();
Uri audio = Uri.parse("file://" + musicFolder + "/" + filename);
Intent intent = new Intent( Intent.ACTION_VIEW);
intent.setDataAndType(audio, "audio/*");
startActivity(intent);
}
});
}
public void searchSongs(View v) {
bindSongsToListView(musicFolder, editTitle.getText().toString());
if ( songs.size() > 0 )
songsView.setVisibility(View.VISIBLE);
else
songsView.setVisibility(View.INVISIBLE);
}
private void bindSongsToListView(File musicFolder, String title) {
songs = new ArrayList<Song>();
ArrayList<Map<String,String>> songsMap = new ArrayList<Map<String,String>>();
for (File f : musicFolder.listFiles()) {
// get MediaMetaData
MediaMetadataRetriever md = new MediaMetadataRetriever();
md.setDataSource(musicFolder + "/" + f.getName());
int secs = Integer.parseInt(md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)) / 1000;
int mins= secs / 60;
secs = secs % 60;
String singer = md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
if ( singer == null || singer.equals(""))
singer = "getSinger";
String songtitle = md.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
if ( songtitle == null )
songtitle = f.getName();
String duration = String.format("%02d:%02d", mins,secs);
if (songtitle.toUpperCase().contains(title.toUpperCase())) {
Song s = new Song();
s.setTitle(songtitle);
s.setFilename(f.getName());
s.setDuration(duration);
s.setSinger(singer);
songs.add(s);
Map<String, String> mapobject = convertSongToMap(s);
songsMap.add(mapobject);
}
}
SimpleAdapter adapter = new SimpleAdapter(this, songsMap, R.layout.song,
new String[] { "title","duration","singer"},
new int[] { R.id.textTitle, R.id.textDuration, R.id.textSinger} );
listSongs.setAdapter(adapter);
}
public Map<String,String> convertSongToMap(Song s) {
HashMap<String, String> map = new HashMap<String,String>();
map.put("title", s.getTitle());
map.put("duration", s.getDuration());
map.put("singer", s.getSinger());
return map;
}
}

Get Context from Android Activiy

I have implemented an Image Gallery using a GridView displaying thumbnails of images and a Fullscreen Activity which will display each of the images in fullscreen mode. The file paths are passed using Intents (putExtra) to the GridView Activity to display different GridViews depending on folder name in SDCARD.Now the problem I have is that I cannot pass those file paths to the Fullscreen Activity in order to view every image separately.
Below are my Classes ;
MainActivity.java
package info.androidhive.imageslider;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button btn1, btn2;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
setOnClickListeners();
}
public void setOnClickListeners(){
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button1:
Toast.makeText(getApplicationContext(), "Loading Gridview 1", Toast.LENGTH_LONG).show();
intent = new Intent(MainActivity.this, GridViewActivity.class);
intent.putExtra("folder", "folder1");
startActivity(intent);
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "Loading Gridview 2", Toast.LENGTH_LONG).show();
intent = new Intent(MainActivity.this, GridViewActivity.class);
intent.putExtra("folder", "folder2");
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
So in this activity am passing different folder names for each button clicks.
GridViewActivity.java
This class will receive the intent parameters for the folder names and it will list all image thumbnails for that specific folder. Until here everything is fine and I can view the images for each different folder depending on the button clicked.
package info.androidhive.imageslider;
import info.androidhive.imageslider.adapter.GridViewImageAdapter;
import info.androidhive.imageslider.helper.AppConstant;
import info.androidhive.imageslider.helper.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Display;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.Toast;
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
//Utils
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
//utils = new Utils(this);
mContext = this;
// Initilizing Grid View
InitilizeGridLayout();
// loading all image paths from SD card
imagePaths = getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
/*
* Reading file paths from SDCard // Utils
*/
public ArrayList<String> getFilePaths() {
ArrayList<String> filePaths = new ArrayList<String>();
String folder = getIntent().getStringExtra("folder");
File directory = new File(
android.os.Environment.getExternalStorageDirectory()
+ File.separator + folder);
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
File[] listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
// check for supported file extension
if (IsSupportedFile(filePath)) {
// Add image path to array list
filePaths.add(filePath);
}
}
} else {
// image directory is empty
Toast.makeText(
mContext,
folder
+ " is empty. Please load some images in it !",
Toast.LENGTH_LONG).show();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Error!");
alert.setMessage(folder
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
return filePaths;
}
/*
* Check supported file extensions
*
* #returns boolean
*/
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppConstant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
/*
* getting screen width
*/
#SuppressLint("NewApi")
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}
Now Once I click on an image thumbnail my (FullScreenView Activity) cannot pickup the folder names so I can display the Image in Fullscreen mode.
FullScreenViewActivity.java
package info.androidhive.imageslider;
import info.androidhive.imageslider.adapter.FullScreenImageAdapter;
//import info.androidhive.imageslider.helper.Utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class FullScreenViewActivity extends Activity{
private GridViewActivity gv;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
//utils = new GridViewActivity(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
gv.getFilePaths());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
}
}
I want to know how can I receive the file parameters in my FullScreenActivity?
You can use
intent.putStringArrayListExtra("paths", getFilePaths());
when you go from GridViewActivity to FullScreenViewActivity and in onCreate of FullScreenViewActivity you can do
ArrayList<String> paths = getIntent().getStringArrayListExtra("paths");
which will give you the paths of the images

Android File Manager only allowing me to go one folder deep

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");
}
}

Java and android file browser issue

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);

Categories

Resources