Reading items from directory to listview in android - android

I am making an android application that needs to display all of the items in a specific directory on the sd-card onto a listview. I have gone though several tutorials but none seemed to give me any help. I have managed to add and delete things from my sd card and listview. But i need to show the items(files) from a directory onto the listview. I am using a dynamic listview. Please help and thanks SO much in advance! This is the code that i am using so far and i need to read the items on the onCreate method.
public class NotesActivity extends ListActivity implements OnClickListener {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton, CancelButton, DeleteButton,CancelButton2, DeleteAllButton;
LinearLayout AddItemToListViewLinearLayout, DeleteItemFromListViewLinearLayout, DeleteAllItemsFromListViewLinearLayout;
public int DeleteIndexNumber;
public String NameOfSaveItemToSdCard = "";
public String NameOfDeleteItemFromSdCard = "";
public int DeleteIndexNumber2;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
DeleteIndexNumber = position;
DeleteIndexNumber2 = position;
NameOfDeleteItemFromSdCard = myList.get(position);
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
CancelButton = (Button)findViewById(R.id.CancelButton);
DeleteButton = (Button)findViewById(R.id.DeleteButton);
CancelButton.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
case R.id.DeleteAllNotes:
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.VISIBLE);
CancelButton2 = (Button)findViewById(R.id.CancelButton2);
DeleteAllButton = (Button)findViewById(R.id.DeleteAllButton);
CancelButton2.setOnClickListener(this);
DeleteAllButton.setOnClickListener(this);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
myList.add(AddItemToListViewEditText.getText().toString());
NameOfSaveItemToSdCard = AddItemToListViewEditText.getText().toString();
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
AddItemToListViewEditText.setText("");
AddItemToListViewEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
AddItemToListViewLinearLayout.setVisibility(View.GONE);
//Check if directory exists
checkIfDirectoryExist();
break;
case R.id.CancelButton:
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteButton:
myList.remove(DeleteIndexNumber);
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
File f = new File(Environment.getExternalStorageDirectory() + "/SchoolAppNotes/" + NameOfDeleteItemFromSdCard);
if(f.exists()) {
boolean deleted = f.delete();
}
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteAllButton:
myList.removeAll(myList);
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.CancelButton2:
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
}
}
private void checkIfDirectoryExist() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/SchoolAppNotes");
if(f.exists()) {
try {
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
+ "/SchoolAppNotes/" + NameOfSaveItemToSdCard);
Toast.makeText(getApplicationContext(), "File created:-)",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "We failed to create the file",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
else {
//Create directory
File folder = new File(Environment.getExternalStorageDirectory() + "/SchoolAppNotes");
boolean success = false;
if(!folder.exists())
{
success = folder.mkdir();
}
if (!success)
{
// Do something on success
//Writing file...(It doesn't work)
}
else
{
// Do something else on failure
}
checkIfDirectoryExist();
}
}
}

I assume that myList is supposed to be holding the file names from your directory? It looks like you never instantiated it.
To do that you'll need to get a list of your file names and load it in to there before you use it to make an adapter.
So add something like this before your .setAdapter() calls:
File mFile = new File(Environment.getExternalStorageDirectory() + "yourDirectory");
myList = mFile.list();
You should be good to go if that fills your array correctly.
p.s. File.list() docs
EDIT:
Whoops, didn't notice the type on myList. Use this instead
myList = Arrays.asList(mFile.list());

Related

Blank screen when opening a pdf using 'com.github.barteksc:android-pdf-viewer:2.8.2' library

I have an issue with using this library
compile 'com.github.barteksc:android-pdf-viewer:2.8.2'
Well I have a couple of pdfs created from my app and I want to give th user an option to view them from the app.Im loading the files from a dialog and on select the selected pdf shoulld open.Here is the dialog.
public class FileExplore extends BaseActivityAlt {
private static final String TAG = "F_PATH";
private static final int DIALOG_LOAD_FILE = 1000;
ArrayList<String> str = new ArrayList<String>();
ListAdapter adapter;
private Boolean firstLvl = true;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory() + "/Travelite/Saved/");
private String chosenFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
#Override
public void onBackPressed(){
Intent intent = new Intent(this,TicketActivity.class);
startActivity(intent);
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.mipmap.pdf_icon);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.company;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Up", R.drawable.forward);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle(R.string.choose_file);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
File file = new File(Environment.getExternalStorageDirectory(),
chosenFile);
Intent intent = new Intent(FileExplore.this,PdfViewer.class);
intent.putExtra("Filename",chosenFile);
startActivity(intent);
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}}
And here is the class loaded onClicking an item in the dialog
public class PdfViewer extends BaseActivityAlt implements OnLoadCompleteListener, OnPageErrorListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pdf_viewer);
PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
String filename = getIntent().getStringExtra("Filename");
File pdffile = new File(Environment.getExternalStorageDirectory(),filename);
Uri file = Uri.fromFile(pdffile);
Toast.makeText(PdfViewer.this, filename, Toast.LENGTH_LONG).show();
pdfView.fromUri(file)
.defaultPage(1)
.password(null)
.load();
}
#Override
public void loadComplete(int nbPages) {
}
#Override
public void onPageError(int page, Throwable t) {
}}
I just realised my mistake: I completely forgot to add the path.

ArrayList turn becomes when an app is resumes after onKill in android

My arraylist becomes null after restarting the app i.e after onKill.
I have declared the array list as Private
I dnt know what is the problem please help .
I have used shared preferences But somehow that dosnt help as welll
When i close the app/kill and restart the arraylist becomes null
private ArrayList<String> PlacardHolder = new ArrayList<String>();
private ArrayList<String> SecondaryPlacardArray = new ArrayList<String>();
private ArrayList<String> DangerousGoodsArray = new ArrayList<String>();
private ArrayList<String> Existing_placards= new ArrayList<String>();
private int PlacardHolderRemainingslots = 2;
private int PlacardHolderPositions=0;
private int PrimaryPlacardCount=0;
private int SecondaryPlacardCount=0;
private boolean Flag_Dangerous_placard_Existing=false;
//String[] PrimaryPlacardArray=new String[3];
private int DangerousGoodsArrayCount=0;
private static int CommonCount=0;
int PrimaryConditionCount=0;
//to take the positions of the placards in the placard holder so that it can be replaced
//Array to store position of placards in the position holder
int[] NoOfPrimaryCount= new int [3];
int count=0;
private localization localLanguage;
public static String filename="MySharedString";
SharedPreferences PlacardHolderData;
SharedPreferences.Editor sEdit;
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
PlacardHolderData=getSharedPreferences(filename, 0);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
///Adding to the placard code in between...Its quite big
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
// menuInflater.inflate(R.menu.menu, menu);
menu.add(menu.NONE,menu_undo,menu.NONE, localization.Menu_Items_Undo_Last);
menu.add(menu.NONE,menu_placards,menu.NONE, localization.Menu_Items_Show_Placard);
menu.add(menu.NONE,menu_dall,menu.NONE,localization.Menu_Items_Deliver_All);
menu.add(menu.NONE,menu_delete,menu.NONE,localization.Menu_Items_Delete);
menu.add(menu.NONE,info,menu.NONE,"Info");//localization reqired
menu.add(menu.NONE,change_locale,menu.NONE,localization.Menu_change_locale);
menu.add(menu.NONE,menu_office,menu.NONE,localization.Menu_Items_Sync_With_Office);
menu.add(menu.NONE,menu_trackSettings,menu.NONE,"Track Settings");//localization reqired
menu.add(menu.NONE,menu_quit,menu.NONE,localization.Menu_Items_Quit);
return super.onCreateOptionsMenu(menu);
}
#SuppressWarnings("deprecation")
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// undo last item from list
case menu_undo:
try {
String idUndo = Utils.idForUndo.get("idUndo");
Log.e(TAG," Utils ids size " + Utils.idForUndo.size() );
for(int i = 0; i < Utils.Placard_Detailss.size(); i++ )
{
Log.e(TAG," placards hash map content " + Utils. Placard_Detailss.get(idUndo));
Log.e(TAG," placards hash map content " + Utils. Placard_Detailss.get(Utils. Placard_Detailss.get(idUndo) ));
}
if (idUndo != null) {
Log.e(TAG, "idUndo--> "+idUndo);
UpdateDBData ud = new UpdateDBData(getApplicationContext());
ud.undoLast(idUndo);
ArrayList<String> Placard_Details_Undo= new ArrayList<String>(Utils.Placard_Details_for_undo);
Log.e(TAG,"pLACARD DETAILS FOR UNDO sixze"+ Utils.Placard_Details_for_undo.size());
for(int i = 0; i <Placard_Details_Undo.size();i++)
{
Log.e(TAG,"pLACARD DETAILS FOR UNDO"+Placard_Details_Undo.get(i));
}
undoLastPlacard( Utils. Placard_Detailss.get(idUndo) , Utils. Placard_Detailss.get(Utils. Placard_Detailss.get(idUndo) ) );
} else {
Toast.makeText(context,localization.Undo_last_message,Toast.LENGTH_LONG).show();
}
getBannerData();
} catch (Exception e2) {
//
e2.printStackTrace();
}
return true;
// show all placards that are selected
case menu_placards:
try {
// PlacardHolderData=PreferenceManager.getDefaultSharedPreferences(context);
// sEdit= PlacardHolderData.edit();
//
// ArrayList<String> myAList=new ArrayList<String>();
// int size = PlacardHolderData.getInt("size", 0);
// PlacardHolderData=getSharedPreferences(filename, 0);
// Log.e(TAG, "size" + size);
//
// for(int j=0;j<size;j++)
// {
// myAList.add(PlacardHolderData.getString("val"+j, "No Data"));
// }
//
// Log.e(TAG, "size" + size);
//
for(int j=0;j< PlacardHolder.size();j++)
{
Log.e(TAG, "Alist" + PlacardHolder.get(j));
}
if (PlacardHolder.size() < 1) {
Toast.makeText(context,localization.Sorry_No_Items_to_Show,Toast.LENGTH_LONG).show();
return false;
}
alconvert = new AlertDialog.Builder(MainActivity.this).create();
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom_listview, null);
alconvert.setView(convertView);
TextView titleSAll = new TextView(this);
titleSAll.setText(localization.Placards_on_the_Truck);
titleSAll.setBackgroundColor(Color.BLACK);
titleSAll.setPadding(10, 10, 10, 10);
titleSAll.setGravity(Gravity.CENTER);
titleSAll.setTextColor(Color.WHITE);
titleSAll.setTextSize(20);
alconvert.setCustomTitle(titleSAll);
CustomAdapterShowAllPlacards myAdptShowAll = new CustomAdapterShowAllPlacards(PlacardHolder,MainActivity.this);
ListView lv = (ListView) convertView.findViewById(R.id.listView2);
lv.setAdapter(myAdptShowAll);
alconvert.setButton(localization.Dialog_Ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int arg1) {
dialog.dismiss();
}
});
alconvert.show();
} catch (Exception e1) {
//
e1.printStackTrace();
}
return true;
Yes when you killed your app or finish your activity all the object created into the heap is cleaned by the garbage collector. so after killing your app or finish your activity your array list object is not available into the heap memory. so when u access it it always gives you null value.
so you need to again initialized array list reference variable. to do it :-
you need to store all the arrayList value into the cache or into the data base. and after storing it into the cache or database. then initialize the arrayList reference from cache or data base.

how to convert an class extends activity into independent class

I have a class that is currently extending Activity and I have methods like onCreate(),OnBackPress() etc. I want to turn it into an independent class but all the above methods become undefined. What is the problem? Shouldn't importing the classes be enough? For eg, I import android.view.View for findViewById but it still makes no difference. Please advise.
File_Explore
public class File_Explorer extends Activity {
// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;
String aDataRow = "";
static StringBuilder aBuffer = new StringBuilder();
String aBuffer1="";
private static final String TAG = "F_PATH";
static long fileSizeInMB;
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 0;
static String fileExtension="";
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.ic_launcher);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.ic_launcher;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Back", R.drawable.ic_launcher);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablePadding(
fileList[position].icon);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("Back") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
fileExtension
= MimeTypeMap.getFileExtensionFromUrl(sel.toString());
// Toast.makeText(getApplication(), fileExtension, Toast.LENGTH_LONG).show();
long fileSizeInBytes = sel.length();
fileSizeInMB = fileSizeInBytes/(1024*1024);
Toast.makeText(getApplication(), String.valueOf(fileSizeInMB).toString(), Toast.LENGTH_LONG).show();
if(fileSizeInMB >1){
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
}
else{
try{
// ArrayList<String> MyFiles = new ArrayList<String>();
FileInputStream fIn = new FileInputStream(sel);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer.append(aDataRow.toString()).append("\n");
}
// aBuffer1 = aBuffer.toString();
myReader.close();
}catch (FileNotFoundException e)
{e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
finish();
}
}
aBuffer.delete(0, aBuffer.length());
// aBuffer1=null;
}
}
);
break;
}
dialog = builder.show();
return dialog;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i= new Intent(this, File_Selecter.class);
startActivity(i);
}
}

how to read the file greater then 1mb

i have create an app in which i am reading the files from phone memory it can read any of the file but when i am reading .vcf file.but when it is smaller than 1 mb ,give correct result,if it is greater than 1 mb,it return nothing.how can i read the data from file.please suggest something.
File_Explore
public class File_Explorer extends Activity {
// Stores names of traversed directories
ArrayList<String> str = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
private Boolean firstLvl = true;
String aDataRow = "";
static StringBuilder aBuffer = new StringBuilder();
String aBuffer1="";
private static final String TAG = "F_PATH";
private Item[] fileList;
private File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
private String chosenFile;
private static final int DIALOG_LOAD_FILE = 0;
static String fileExtension="";
ListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.ic_launcher);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.ic_launcher;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Back", R.drawable.ic_launcher);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablePadding(
fileList[position].icon);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("Back") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
fileExtension
= MimeTypeMap.getFileExtensionFromUrl(sel.toString());
// Toast.makeText(getApplication(), fileExtension, Toast.LENGTH_LONG).show();
try{
// ArrayList<String> MyFiles = new ArrayList<String>();
FileInputStream fIn = new FileInputStream(sel);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer.append(aDataRow.toString()).append("\n");
}
// aBuffer1 = aBuffer.toString();
myReader.close();
}catch (FileNotFoundException e)
{e.printStackTrace();}
catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(getApplicationContext(),aBuffer,Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("name", aBuffer.toString());
setResult(RESULT_OK, returnIntent);
finish();
}
aBuffer.delete(0, aBuffer.length());
// aBuffer1=null;
}
}
);
break;
}
dialog = builder.show();
return dialog;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i= new Intent(this, File_Selecter.class);
startActivity(i);
}
}
If you do not need whole 1MB (capital B by the way) read (which is usually the case), then read only the part you need. And if you do not know where the part you need is (so you cannot seek()), read in smaller chunks unless you find what you need to read from the file.

Android - getting back to menu from filepicker/browsing screen

I found this file picker online, which the developer said that people could use if they wanted to.
Since I thought the code was easy to understand - I decided to use it and change it a bit for my application.
All credit goes to the original developer (https://github.com/mburman/Android-File-Explore)
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
// Checks whether path exists
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.file_icon);
// Convert into file path
File sel = new File(path, fList[i]);
// Set drawables
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.directory_icon;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Up", R.drawable.directory_up);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
private class Item {
public String file;
public int icon;
public Item(String file, Integer icon) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new Builder(this);
if (fileList == null) {
Log.e(TAG, "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case DIALOG_LOAD_FILE:
builder.setTitle("Choose your file");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
removeDialog(DIALOG_LOAD_FILE);
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
}
// File picked
else {
chosenFile = fileList[which].file;
File test = new File(path + "/" + chosenFile);
sendback(test);
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
Sorry, if it's a bit too long. But that's the entire file picker which is in the onCreate().
I open it by using this code:
Bundle b = new Bundle();
b.putInt("tallet", 1);
Intent i = new Intent(getApplicationContext(), FileExplore.class);
i.putExtras(b);
startActivityForResult(i, 0);
The code works perfectly. But when I press "back" (onBackPressed), it gives me blank (black) screen if I say finish(); .
Right now I'm using this code:
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
startActivity(backIntent);
}
Which actually works, but it gives me black screen if I press back once, and then the menu, when I hit the back button again. EDIT: it goes INTO the onBackPressed code on second back-press, not the first.
Here's my onActivityResult code in PhotosActivity (it's a tablayout - photosactivity is just one of the screens):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// Bundle b = getIntent().getExtras();
if (resultCode == -1)
{
Bundle b = data.getBundleExtra("FiletoPhoto");
int knappen = b.getInt("number");
String titlen = b.getString("title");
{
Listofsounds los = new Listofsounds();
String shortname = los.puttextonit(titlen, knappen);
putnameinit(shortname,knappen);
}
}
else if (resultCode == 0)
{
//If I press "back" i've made the resultCode to be 0 in the onBackPressed. What should I do here then?
}
}
What should I do so I could just press it once and get back to the menu?
The issue is that when you use this code:
Intent backIntent = new Intent(FileExplore.this, AndroidTabLayoutActivity.class);
startActivity(backIntent);
You are basically creating and starting a new activity of AndroidTabLayoutActivity which already exists, so now there will be two copies of this activity running simultaneously. However, the original activity will be expecting a result as you've called startActivityForResult(). I think the solution to your problem is probably to do a check if the resultCode you are getting back as a onActivityResult is RESULT_OK or whatever successful resultCode you are setting in setResult(...) in FileExplore.
This is really strange because in all of my apps I don't override onBackPressed and yet, I am able to finish the activity without causing any weird side effects.

Categories

Resources