sliding pane error display - android

I'm trying to emplement a file explorer with sliding pane interface. But when i scroll the grid view i have my genymotion device display like (http://www.mediafire.com/?kui3x2l7u6ykgx3)
and this is when the app first start (http://www.mediafire.com/?45cg12uk5wadiui)
could any one tell me where shouls i look up or how to fix this?
The images are in the link, sorry for this because i don't have enough reputation to attract image in my post.
and here is my code
this is the fragment which content the gridview
public class ContentFragment extends Fragment{
public static ArrayList<FileItem> listFileItem = new ArrayList<FileItem>();
public static FileGridAdapter fileGridAdapter = null;
public static int clickTimes = 0;
ArrayList<String> str = new ArrayList<String>();
private Boolean firstLvl = true;
private File path = new File(Environment.getExternalStorageDirectory() + "");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
loadFiles();
View rootView = inflater.inflate(R.layout.fragment_content, container, false);
fileGridAdapter = new FileGridAdapter(getActivity(), android.R.layout.activity_list_item, listFileItem);
GridView gridView = (GridView) rootView.findViewById(R.id.fileGridView);
gridView.setAdapter(fileGridAdapter);
gridView.setOnItemClickListener( new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
FileItem fileItem = fileGridAdapter.getItem(arg2);
if(fileItem.fileIcon == "folder") {
if(fileItem.fileName == "up") {
path = new File(path.toString().substring(0,
path.toString().lastIndexOf("/")));
if(path.toString() == (new File(Environment.getExternalStorageDirectory() + "")).toString())
firstLvl = true;
} else {
File selectedFolder = new File(path + "/" + fileItem.fileName);
path = new File(selectedFolder + "");
firstLvl = false;
}
loadFiles();
fileGridAdapter.notifyDataSetChanged();
} else {
FileGridItem fileGridItem = (FileGridItem) arg1;
fileGridItem.checkBox.setChecked(true);
}
}
});
return rootView;
}
private void loadFiles() {
listFileItem.clear();
try {
path.mkdirs();
} catch (SecurityException e) {
}
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);
listFileItem = new ArrayList<FileItem>();
for (int i = 0; i < fList.length; i++) {
listFileItem.add(new FileItem(fList[i], path.getPath()));
}
if (!firstLvl) {
listFileItem.add(new FileItem("up", path.getPath()));
}
} else {
}
}
}

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.

How to pass Data from Gridview Item to Android?

I have a Gridview in my App...
The Gridview shows all the available files in a particular folder, lets say 'Sample Folder'...
What I am trying is to pass the ACTION_VIEW Intent on item click but I am not able to set its Data and Type...
Most of the files are either image or videos...
Here's the code for Activity -
public class Downloaded extends AppCompatActivity {
// Declare variables
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
GridView grid;
GridViewAdapter adapter;
File file;
TextView empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Check for SD Card
if (!Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Toast.makeText(Downloaded.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 + "Sample");
file.mkdirs();
}
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);
empty = (TextView) findViewById(R.id.empty);
empty.setText("You haven't saved any Pic yet...!");
grid.setEmptyView(empty);
// Pass String arrays to LazyAdapter Class
adapter = new GridViewAdapter(Downloaded.this, FilePathStrings, FileNameStrings);
// Set the LazyAdapter to the GridView
grid.setAdapter(adapter);
// Capture gridview item click
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
//Don't Know what to Do Here :(
File n = new File(Environment.getExternalStorageDirectory()+ File.separator + "Sample/" + FileNameStrings);
i.setDataAndType(Uri.fromFile(n), "*/*");
startActivity(Intent.createChooser(i, "Choose an App"));
}
});
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
}
And here's the Adapter -
public class GridViewAdapter extends BaseAdapter {
// Declare variables
private Activity activity;
String[] filepath;
String[] filename;
Context mContext;
private static LayoutInflater inflater = null;
public GridViewAdapter( Context c ) {
mContext = c ;
}
public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
activity = a;
this.filepath = fpath;
filename = fname;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return this.filepath.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.gridview_item, null);
// Locate the ImageView in gridview_item.xml
ImageView img = (ImageView) vi.findViewById(R.id.image);
// Set file name to the TextView followed by the position
TextView txt = (TextView) vi.findViewById(R.id.name);
// Decode the filepath with BitmapFactory followed by the position
// Set the decoded bitmap into ImageView
Glide.with(activity)
.load(filepath[position])
.into(img);
txt.setText(filename[position]);
return vi;
}
}
Any help would be appreciated... :)
Try like this
Intent i = new Intent(android.content.Intent.ACTION_VIEW);
// No need to set both Type & Data. if you set one itself enough
File n = new File(Environment.getExternalStorageDirectory()+ File.separator + "Sample/" + FileNameStrings);
i.setType(MimeTypeMap.getFileExtensionFromUrl(n.getAbsolutePath()));
startActivity(Intent.createChooser(i, "Choose an App"));
Updated
Try this for open file
MimeTypeMap myMime = MimeTypeMap.getSingleton();
Intent newIntent = new Intent(Intent.ACTION_VIEW);
String mimeType = myMime.getMimeTypeFromExtension(fileExt(file).substring(1));
newIntent.setDataAndType(Uri.fromFile(file),mimeType);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No handler for this type of file.", Toast.LENGTH_LONG).show();
}
private String fileExt(String url) {
if (url.indexOf("?") > -1) {
url = url.substring(0, url.indexOf("?"));
}
if (url.lastIndexOf(".") == -1) {
return null;
} else {
String ext = url.substring(url.lastIndexOf(".") + 1);
if (ext.indexOf("%") > -1) {
ext = ext.substring(0, ext.indexOf("%"));
}
if (ext.indexOf("/") > -1) {
ext = ext.substring(0, ext.indexOf("/"));
}
return ext.toLowerCase();
}
}

Android - Listview .remove() function is not working as expected

I have a listview that is able to delete a specific image via onLongClick, but it isn't working so far. When testing, the dialog appears If i want to delete or not, i press Yes/Ok and the toast appears saying Item deleted, however the item is still there.
UPDATED ( I got the remove and delete function working thanks to user1140237)
UPDATED MAIN ACTIVITY
private String[] FilePathStrings;
private String[] FileNameStrings;
private File[] listFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yearbook);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"/CapturyGallery");
// 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.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"/CapturyGallery");
// Create a new folder if no folder named CapturyGallery exist
file.mkdirs();
}
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 image file
FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
FileNameStrings[i] = listFile[i].getName();
}
}
Arrays.sort(listFile);
final ListAdapter listAdapter = new CustomAdapter(Yearbook.this, FilePathStrings, FileNameStrings);
ListView lv = (ListView) findViewById(R.id.ListingView);
lv.setAdapter(listAdapter);
final ArrayList<String> list = new ArrayList(Arrays.asList(FilePathStrings));
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//Deletes item
AlertDialog.Builder adb=new AlertDialog.Builder(Yearbook.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + FileNameStrings[position]);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File file = new File(list.get(positionToRemove));
if (file.delete()) {
list.remove(position);
((CustomAdapter) listAdapter).updateMyData(FilePathStrings, FileNameStrings);
Toast.makeText(getApplicationContext(), FileNameStrings[position] + " deleted", Toast.LENGTH_LONG).show();
}
}
});
adb.show();
return true;
}
});
}
CUSTOMADAPTER
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private String[] filepath;
private String[] filename;
private static LayoutInflater inflater = null;
public CustomAdapter(Activity a, String[] fpath, String[] fname) {
activity = a;
filepath = fpath;
filename = fname;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void updateMyData(String[] fpath, String[] fname) {
filepath = fpath;
filename = fname;
notifyDataSetChanged();
}
#Override
public int getCount() {
return filepath.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
class MyViewHolder {
ImageView myImage;
TextView timestamp;
TextView myName;
TextView myHeader;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.PicView);
timestamp = (TextView) v.findViewById(R.id.timestamp);
myName = (TextView) v.findViewById(R.id.myName);
myHeader = (TextView) v.findViewById(R.id.textSeparator);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
MyViewHolder holder = null;
if (vi == null) {
vi = inflater.inflate(R.layout.custom_row, null);
holder = new MyViewHolder(vi);
vi.setTag(holder);
} else {
holder = (MyViewHolder) vi.getTag();
}
Bitmap bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(filepath[position]),100,100);
holder.myImage.setImageBitmap(bmp);
//PicImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.myImage.setPadding(8, 8, 8, 8);
//Set Title
holder.myName.setText(filename[position]);
ExifInterface intf = null;
try {
intf = new ExifInterface(filepath[position]);
} catch(IOException e) {
e.printStackTrace();
}
if(intf != null) {
String dateString = intf.getAttribute(ExifInterface.TAG_DATETIME);
holder.timestamp.setText("Date Taken: " + dateString.toString());
}
return vi;
}
And so my last problem is, whenever i remove something from my listview it crashed. However, the file was indeed removed. Im not sure what is the error because i tested it on my mobile phone
You need to update list data in your custom adapter too. after removing than call notifydatasetchanged
Keep below method in you customadapter to udpate list data & after that call it in longpress
public void updateMyData(String[] fpath, String[] fname) {
filepath = fpath;
filename = fname;
notifyDataSetChanged();
}
You need to call this from longPress
list.remove(position);
((CustomAdapter )listAdapter).updateMyData( FilePathStrings, FileNameStrings); /// here in your case you need to define both array global sorry not time to clean up your code
Toast.makeText(getApplicationContext(), FileNameStrings[position] +" deleted",Toast.LENGTH_LONG).show();
UPDATED
To remove file from the mentioned dir & updating listview you need to delete file from that location first and than you need to update listview
File file = new File(list.get(position));
if (file.delete()) {// this will required permission in Manifest for Write_EXTERNAL_STORATE
// if file is deleted from SD CARD
list.remove(position);
((CustomAdapter )listAdapter).updateMyData( FilePathStrings, FileNameStrings); /// here in your case you need to define both array global sorry not time to clean up your code
Toast.makeText(getApplicationContext(), FileNameStrings[position] + " deleted", Toast.LENGTH_LONG).show();
}
*CustomAdapter *
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> filepath;
private ArrayList<String> filename;
private JSONArray jListData;
private int size = 0;
public CustomAdapter(Activity a, JSONArray jListData) {
activity = a;
this.jListData = jListData;
if (filepath != null)
size = jListData.length();
}
public void updateMyData(JSONArray jListData) {
this.jListData = jListData;
size = jListData.length();
notifyDataSetChanged();
}
#Override
public int getCount() {
return size;
}
public JSONObject getItem(int position) {
try {
return (JSONObject) jListData.get(position);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public long getItemId(int position) {
return position;
}
class MyViewHolder {
ImageView myImage;
TextView timestamp;
TextView myName;
TextView myHeader;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.PicView);
timestamp = (TextView) v.findViewById(R.id.timestamp);
myName = (TextView) v.findViewById(R.id.myName);
myHeader = (TextView) v.findViewById(R.id.textSeparator);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
MyViewHolder holder = null;
try {
if (vi == null) {
vi = LayoutInflater.from(activity).inflate(R.layout.custom_row, parent, false);
holder = new MyViewHolder(vi);
vi.setTag(holder);
} else {
holder = (MyViewHolder) vi.getTag();
}
JSONObject rowObject = this.jListData.getJSONObject(position);
Bitmap bmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(rowObject.optString("filename")), 100, 100);
holder.myImage.setImageBitmap(bmp);
//PicImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.myImage.setPadding(8, 8, 8, 8);
//Set Title
holder.myName.setText(rowObject.optString("filename"));
ExifInterface intf = null;
try {
intf = new ExifInterface(rowObject.optString("filepath"));
} catch (IOException e) {
e.printStackTrace();
}
if (intf != null) {
String dateString = intf.getAttribute(ExifInterface.TAG_DATETIME);
holder.timestamp.setText("Date Taken: " + dateString.toString());
}
} catch (JSONException e) {
}
return vi;
}
}
ACTIVITY
private JSONArray jArrayFileData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yearbook);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
// 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.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/CapturyGallery");
// Create a new folder if no folder named CapturyGallery exist
file.mkdirs();
}
jArrayFileData = new JSONArray();
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++) {
JSONObject jObject = new JSONObject();
//Get the path image file
// FilePathStrings[i] = listFile[i].getAbsolutePath();
// Get the name image file
// FileNameStrings[i] = listFile[i].getName();
jObject.put("filepath", listFile[i].getAbsolutePath());
jObject.put("filename", listFile[i].getName());
jArrayFileData.put(jObject);
}
}
// Arrays.sort(listFile);
final ListAdapter listAdapter = new CustomAdapter(Yearbook.this, jArrayFileData);
ListView lv = (ListView) findViewById(R.id.ListingView);
lv.setAdapter(listAdapter);
// final ArrayList<String> list = new ArrayList(Arrays.asList(FilePathStrings));
lv.setOnItemClickListener(this);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
//Deletes item
AlertDialog.Builder adb = new AlertDialog.Builder(Yearbook.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + FileNameStrings[position]);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File file = new File(list.get(positionToRemove));
if (file.delete()) {
Toast.makeText(getApplicationContext(), jArrayFileData.getJSONObject(position).optString("filename") + " deleted", Toast.LENGTH_LONG).show();
jArrayFileData.remove(position);
// list.remove(position);
((CustomAdapter) listAdapter).updateMyData(jArrayFileData);
}
} catch (JSONException e) {
}
}
});
adb.show();
return true;
}
});
}
Use Arraylist<String> for fpath and fname in your code: Then to delete data from your listview.
Use this:
fpath.remove(index_toDelete);
fpath.remove(index_toDelete);
customAdapter.notifyDataSetChanged();

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.

Categories

Resources