It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to create a project in which I need my application to read locally store pdf, doc, xls files.
I don't have any idea on how to do it. I want to show all that locally stored files in my webview. Is there any library to render this files or any other way to do it? If any one can guide me on it than it will be my pleasure.
package com.cdn.file;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class FileExplorerActivity extends Activity {
/** Called when the activity is first created. */
private Button buttonList, buttonBack;
// 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 static final String TAG = "F_PATH";
private List<Item> fileList;
private Item item;
private File path = new File(Environment.getExternalStorageDirectory() + "");
private String chosenFile = "";
ListView listViewDir;
ListAdapter adapter;
ListFile listFileAdaptor;
int value = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewDir = (ListView) findViewById(R.id.listViewDir);
buttonBack = (Button) findViewById(R.id.buttonBack);
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonList = (Button) findViewById(R.id.buttonList);
buttonList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isSdPresent()) {
Toast.makeText(FileExplorerActivity.this, "Un Mounted",
Toast.LENGTH_SHORT).show();
loadFileList();
listFileAdaptor = new ListFile(FileExplorerActivity.this,
fileList);
listViewDir.setAdapter(listFileAdaptor);
}
else {
Toast.makeText(FileExplorerActivity.this, "Mounted",
Toast.LENGTH_SHORT).show();
}
}
});
listViewDir.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// if (value == 0) {
chosenFile = fileList.get(position).getFile();
/*} else {
chosenFile = backList.get(position).getFile();
value =0;
}*/
File sel = new File(path + "/" + chosenFile);
Log.v("Prashant111 ==", sel.toString());
Log.v("Prashant222 ==", "" + sel.toURI());
if (sel.isDirectory()) {
// Adds chosen directory to list
str.add(chosenFile);
path = new File(sel + "");
loadFileList();
listFileAdaptor = new ListFile(FileExplorerActivity.this,
fileList);
listViewDir.setAdapter(listFileAdaptor);
// Log.d(TAG, path.getAbsolutePath());
Log.d("Prashant333 ==", "" + path.toURI());
Log.d("Prashant444 ==", "" + path.toString());
}
// Checks if 'up' was clicked
// File picked
else {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(chosenFile));
intent.putExtra(Intent.ACTION_VIEW, uri);
Intent chooser = Intent.createChooser(intent, "Prashant");
startActivity(chooser);
}
}
});
}
public static boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
private class Item {
public String file;
public int icon;
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
}
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 ArrayList<FileExplorerActivity.Item>();
for (int i = 0; i < fList.length; i++) {
item = new Item();
item.setIcon(R.drawable.file_icon);
item.setFile(fList[i]);
// fileList.add(item);
// Convert into file path
File sel = new File(path, fList[i]);
Log.v("sel ====", sel.toString());
String name = sel.getName();
// Set drawables
if (sel.isDirectory()) {
item.setFile(name);
item.setIcon(R.drawable.directory_icon);
fileList.add(item);
} else {
if (name.endsWith(".mp4") || name.endsWith(".3gp")) {
Log.v("aaaaaaaaaaa", name);
item.setFile(name);
item.setIcon(R.drawable.icon);
fileList.add(item);
} else {
fileList.remove(item);
}
}
}
} else {
Log.e(TAG, "path does not exist");
}
}
class ViewHolder {
TextView textViewName;
ImageView view;
}
class ListFile extends BaseAdapter {
List<Item> fileList;
private LayoutInflater inflator;
Context context;
ListFile(Context context, List<Item> fileList) {
this.fileList = fileList;
this.context = context;
inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return fileList.size();
}
#Override
public Object getItem(int position) {
return fileList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
if (getItemViewType(position) == 0) {
convertView = inflator.inflate(R.layout.file_list, null);
}
holder = new ViewHolder();
holder.textViewName = (TextView) convertView
.findViewById(R.id.textView1);
holder.view = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(holder);
// Set the display text
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewName.setText(fileList.get(position).getFile());
holder.view.setImageResource((fileList.get(position).getIcon()));
return convertView;
}
}
}
Try using this code. I am taking video files but you can specify the type of files that you want.
Related
I don't understand why my recyclerview is only showing the last row of my database although I initialised it with 150 datas.
I searched a lot in the internet and even here on SO, but not one of the solutions is working. Can you help me to figure out why my recyclerView is only showing the last row of the database? Thanks in advance to all of you.
May be you can help me. Here is my code:
package com.example.frontaddress.matedesignc;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Customer_Activity extends AppCompatActivity {
private List<String> StateListArray =new ArrayList<String>();
private List<String> StateList =new ArrayList<String>();
private List<String> CityListArray ;
private List<String> CityList ;
private Spinner dropdown_state;
private Spinner dropdown_city;
private DBHandler DB = new DBHandler(this);
private static final String BUSINESSNAME = "bussiness_name";
private static final String MOBILE = "mobile";
private static final String ADDRESS = "address";
private static final String ID = "id";
private Toolbar toolbar;
private Customer_list_Adapter adapter;
private RecyclerView recyclerView_Customer;
//ProgressDialog pDialog = new ProgressDialog(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GetStateList(); }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sub, menu);
return true; }
public void CustomerDetails(String state,String city) throws IOException {
try {
List<customer_search_information> data = null;
data = new ArrayList<>();
customer_search_information current = new customer_search_information();
Cursor RST_CSTInfo = DB.getRows("customer", "id,bussiness_name,mobile,address", " state='" + state + "' AND city='" + city + "'");
while (!RST_CSTInfo.isAfterLast()) {
current.bussiness_name = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(BUSINESSNAME));
current.state = state;
current.city = city;
current.address = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ADDRESS));
String Mob = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(MOBILE));
current.mobile_no = Mob;
current.e_mail = "mail.isigntech#gmail.com";
current.id = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ID));
// displayExceptionMessage(current.id+current.bussiness_name+current.state+current.city+current.address+current.mobile+current.email);
data.add(current);
RST_CSTInfo.moveToNext();
}
recyclerView_Customer = (RecyclerView) findViewById(R.id.drawerListCustomer);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setLayoutManager(new LinearLayoutManager(this));
adapter = new Customer_list_Adapter(this, data);
recyclerView_Customer.setAdapter(adapter);
}catch (Exception e){ displayExceptionMessage(e.toString());}
}
private void GetStateList()
{ Cursor Customer= DB.getRows("customer","state", " 1 GROUP BY state");
while(!Customer.isAfterLast()){
String state=Customer.getString(Customer.getColumnIndex("state"));
StateList.add(state);
StateListArray.add(state);
Customer.moveToNext();
}
dropdown_state = (Spinner)findViewById(R.id.SpnSrch_State);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, StateListArray);
dropdown_state.setAdapter(adapter);
dropdown_state.setPrompt("Choose State ");
dropdown_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
dropdown_city=(Spinner) findViewById(R.id.SpnSrch_State);
Cursor RstCity= DB.getRows("customer","city", "state='"+state+"' GROUP BY city");
CityListArray =new ArrayList<String>();
CityList =new ArrayList<String>();
while(!RstCity.isAfterLast()){
String city=RstCity.getString(RstCity.getColumnIndex("city"));
CityList.add(city);
CityListArray.add(city);
RstCity.moveToNext();
}
dropdown_city = (Spinner)findViewById(R.id.SpnSrch_City);
ArrayAdapter<String> cityadapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, CityListArray);
dropdown_city.setAdapter(cityadapter);
dropdown_city.setPrompt("Choose City ");
dropdown_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
item = dropdown_city.getSelectedItemPosition();
String city =CityListArray.get(item);
try {
CustomerDetails(state,city);
} catch (Exception e) {
displayExceptionMessage(e.toString());
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select State.");
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select City.");
}
});
}
public void displayExceptionMessage(String msg) {
//TextView Txterror=(TextView) findViewById(R.id.txterror);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#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;
}
if (id == android.R.id.home) {
// NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItementer code hereSelected(item);
}
}
Here is my custom list adapter code:
package com.example.frontaddress.matedesignc;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
/**
* Created by frontaddress on 10/08/17.
*/
public class Customer_list_Adapter extends RecyclerView.Adapter<Customer_list_Adapter.CustomerViewHolder> {
private LayoutInflater inflater;
private Context contexts;
List<customer_search_information> Cst_data = Collections.emptyList();
public Customer_list_Adapter(Context context, List<customer_search_information> data) {
inflater = LayoutInflater.from(context);
this.Cst_data = data;
// Toast.makeText(contexts, data.size(), Toast.LENGTH_LONG).show();
this.contexts = context;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.content_search_staff, parent, false);
CustomerViewHolder holder = new CustomerViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomerViewHolder holder, int position) {
try {
customer_search_information current = Cst_data.get(position);
Integer Pos=position;
holder.TxtBisinessName.setText(current.bussiness_name);
holder.TxtAddress.setText(current.address);
holder.Statecity.setText(current.state + "-" + current.city);
holder.Txt_Mobile.setText(current.mobile_no.toString());
holder.TxtEmail.setText(current.e_mail);
}catch (Exception e)
{
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return Cst_data.size();
}
class CustomerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView TxtBisinessName;
TextView TxtAddress;
TextView Txt_Mobile;
TextView Statecity;
TextView TxtEmail;
ImageView ImgPhoneCall,ImgMailTo;
public CustomerViewHolder(View itemView) {
super(itemView);
TxtBisinessName = (TextView) itemView.findViewById(R.id.Txtbusiness_name);
Txt_Mobile = (TextView) itemView.findViewById(R.id.TxtMobile);
Statecity = (TextView) itemView.findViewById(R.id.Txtstatecity);
TxtAddress = (TextView) itemView.findViewById(R.id.Txtaddress);
TxtEmail=(TextView) itemView.findViewById(R.id.TxtEmail);
ImgPhoneCall = (ImageView) itemView.findViewById(R.id.ImgCallPhone);
ImgMailTo= (ImageView) itemView.findViewById(R.id.Imgmail);
ImgPhoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String MOBILE = current.mobile_no;
try {
if (ActivityCompat.checkSelfPermission(contexts,Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(contexts, "Call Permission Not Granted ", Toast.LENGTH_LONG).show();
return;
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:+91" + MOBILE));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contexts.startActivity(callIntent);
}
catch (Exception e){
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
/* TxtProfile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = data.get(getPosition());
String SID = current.id;
Intent intent = new Intent(contexts, StudentProfileActivity.class);
intent.putExtra("id", SID);
contexts.startActivity(intent);
}
});*/
ImgMailTo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String EMAIL = current.e_mail;
String BName = current.bussiness_name;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, EMAIL);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi,"+BName);
final PackageManager pm = contexts.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
contexts.startActivity(emailIntent);
}
catch (Exception e){ }
}
});
}
#Override
public void onClick(View v) {
int ID=v.getId();
customer_search_information current=Cst_data.get(getPosition());
String SID=current.id;
// Toast.makeText(contexts,"Item Clicked Profile: "+ v.getId(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(contexts, StudentProfileActivity.class);
// intent.putExtra("id", SID);
// contexts.startActivity(intent);
}
}
}
I think the problem is here , instead of
while(!RST_CSTInfo.isAfterLast()){
...
..
RST_CSTInfo.moveToNext();
}
try this ....
do(RST_CSTInfo.movetofirst()){
// your logic
}while(cursor.movetonext())
I am trying to figure out a way to use this example in a fragment:
http://sampleprogramz.com/android/browse.php
I have changed the OnCreate method to the OnCreateView method and have tried to correct any of the errors that Android Studio flags but I can't seem to get it working.
Here is the code:
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import static android.app.Activity.RESULT_OK;
public class FilePicker extends ListFragment {
public final static String EXTRA_FILE_PATH = "file_path";
public final static String EXTRA_SHOW_HIDDEN_FILES = "show_hidden_files";
public final static String EXTRA_ACCEPTED_FILE_EXTENSIONS = "accepted_file_extensions";
private final static String DEFAULT_INITIAL_DIRECTORY = "/";
protected File Directory;
protected ArrayList<File> Files;
protected FilePickerListAdapter Adapter;
protected boolean ShowHiddenFiles = false;
protected String[] acceptedFileExtensions;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View emptyView = inflater.inflate(R.layout.empty_view, container, false);
((ViewGroup) getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
// Set initial directory
Directory = new File(DEFAULT_INITIAL_DIRECTORY);
// Initialize the ArrayList
Files = new ArrayList<File>();
// Set the ListAdapter
Adapter = new FilePickerListAdapter(getActivity(), Files);
setListAdapter(Adapter);
// Initialize the extensions array to allow any file extensions
acceptedFileExtensions = new String[] {".rc"};
// Get intent extras
if(getActivity().getIntent().hasExtra(EXTRA_FILE_PATH))
Directory = new File(getActivity().getIntent().getStringExtra(EXTRA_FILE_PATH));
if(getActivity().getIntent().hasExtra(EXTRA_SHOW_HIDDEN_FILES))
ShowHiddenFiles = getActivity().getIntent().getBooleanExtra(EXTRA_SHOW_HIDDEN_FILES, false);
if(getActivity().getIntent().hasExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS)) {
ArrayList<String> collection =
getActivity().getIntent().getStringArrayListExtra(EXTRA_ACCEPTED_FILE_EXTENSIONS);
acceptedFileExtensions = (String[])
collection.toArray(new String[collection.size()]);
}
return emptyView;
}
#Override
public void onResume() {
refreshFilesList();
super.onResume();
}
protected void refreshFilesList() {
Files.clear();
ExtensionFilenameFilter filter =
new ExtensionFilenameFilter(acceptedFileExtensions);
File[] files = Directory.listFiles(filter);
if(files != null && files.length > 0) {
for(File f : files) {
if(f.isHidden() && !ShowHiddenFiles) {
continue;
}
Files.add(f);
}
Collections.sort(Files, new FileComparator());
}
Adapter.notifyDataSetChanged();
}
public void onListItemClick(ListView l, View v, int position, long id) {
File newFile = (File)l.getItemAtPosition(position);
if(newFile.isFile()) {
Intent extra = new Intent();
extra.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
getActivity().setResult(RESULT_OK, extra);
getActivity().finish();
}
else {
Directory = newFile;
refreshFilesList();
}
super.onListItemClick(l, v, position, id);
}
private class FilePickerListAdapter extends ArrayAdapter<File> {
private List<File> mObjects;
public FilePickerListAdapter(Context context, List<File> objects) {
super(context, R.layout.list_item, android.R.id.text1, objects);
mObjects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item, parent, false);
}
else
row = convertView;
File object = mObjects.get(position);
ImageView imageView = (ImageView)row.findViewById(R.id.file_picker_image);
TextView textView = (TextView)row.findViewById(R.id.file_picker_text);
textView.setSingleLine(true);
textView.setText(object.getName());
if(object.isFile())
imageView.setImageResource(R.drawable.sound);
else
imageView.setImageResource(R.drawable.folder);
return row;
}
}
private class FileComparator implements Comparator<File> {
public int compare(File f1, File f2) {
if(f1 == f2)
return 0;
if(f1.isDirectory() && f2.isFile())
// Show directories above files
return -1;
if(f1.isFile() && f2.isDirectory())
// Show files below directories
return 1;
// Sort the directories alphabetically
return f1.getName().compareToIgnoreCase(f2.getName());
}
}
private class ExtensionFilenameFilter implements FilenameFilter {
private String[] Extensions;
public ExtensionFilenameFilter(String[] extensions) {
super();
Extensions = extensions;
}
public boolean accept(File dir, String filename) {
if(new File(dir, filename).isDirectory()) {
// Accept all directory names
return true;
}
if(Extensions != null && Extensions.length > 0) {
for(int i = 0; i < Extensions.length; i++) {
if(filename.endsWith(Extensions[i])) {
// The filename ends with the extension
return true;
}
}
// The filename did not match any of the extensions
return false;
}
// No extensions has been set. Accept all file extensions.
return true;
}
}
}
Thanks.
I was able to get it working by inflating a new xml layout for the filepicker fragment,
I replaced:
View emptyView = inflater.inflate(R.layout.empty_view, container, false);
((ViewGroup) getListView().getParent()).addView(emptyView);
getListView().setEmptyView(emptyView);
// Set initial directory
Directory = new File(DEFAULT_INITIAL_DIRECTORY);
// Initialize the ArrayList
Files = new ArrayList<File>();
// Set the ListAdapter
Adapter = new FilePickerListAdapter(getActivity(), Files);
setListAdapter(Adapter);
With:
View viewlist = inflater.inflate(R.layout.file_picker, container, false);
lv = (ListView) viewlist.findViewById(R.id.filebrowselist);
// Set initial directory
Directory = new File(String.valueOf(DEFAULT_INITIAL_DIRECTORY));
// Initialize the ArrayList
Files = new ArrayList<File>();
// Set the ListAdapter
Adapter = new FilePickerListAdapter(getActivity(), Files);
lv.setAdapter(Adapter);
Question :- This code is working well for picking up the file but i want to hide system folders when I am running this code it also show me all android folder starting with "." I tried some things which you can already see in comments in my code..
FileChooser.java
package com.sarita.scheduler;
import java.io.File;
import java.sql.Date;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ListView;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fill(currentDir);
}
private void fill(File f)
{
String rootDriectory = Environment.getExternalStorageDirectory().getName(); ;
/* String chkFileName = f.getName().toString();
String chkSystemFolder =String.valueOf(chkFileName.charAt(0));
*/
File[]dirs = f.listFiles();
/*if (chkSystemFolder != "."){*/
this.setTitle("Current Dir: "+f.getName());
List<Item>dir = new ArrayList<Item>();
List<Item>fls = new ArrayList<Item>();
try{
for(File ff: dirs)
{
Date lastModDate = new Date(ff.lastModified());
DateFormat formater = DateFormat.getDateTimeInstance();
String date_modify = formater.format(lastModDate);
if(ff.isDirectory()){
File[] fbuf = ff.listFiles();
int buf = 0;
if(fbuf != null){
buf = fbuf.length;
}
else buf = 0;
String num_item = String.valueOf(buf);
if(buf == 0) num_item = num_item + " item";
else num_item = num_item + " items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(),num_item,date_modify,ff.getAbsolutePath(),"directory_icon"));
}
else
{
fls.add(new Item(ff.getName(),ff.length() + " Byte", date_modify, ff.getAbsolutePath(),"file_icon"));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase(rootDriectory))
dir.add(0,new Item("..","Parent Directory","",f.getParent(),"directory_up"));
adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_explorer,dir);
this.setListAdapter(adapter);
/*}*/
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon")||o.getImage().equalsIgnoreCase("directory_up")){
currentDir = new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o);
}
}
private void onFileClick(Item o)
{
//Toast.makeText(this, "Folder Clicked: "+ currentDir, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("GetPath",currentDir.toString());
intent.putExtra("GetFileName",o.getName());
setResult(RESULT_OK, intent);
finish();
}
}
FileArrayAdapter.java
package com.sarita.scheduler;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FileArrayAdapter extends ArrayAdapter<Item>{
private Context c;
private int id;
private List<Item>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Item o = items.get(position);
String chkFileName = o.getName().toString();
String chkSystemFolder =String.valueOf(chkFileName.charAt(0));
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
//convertView = ( RelativeLayout ) inflater.inflate( resource, null );
if (chkSystemFolder != ".")
{
if (o != null)
{
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if (chkSystemFolder != "."){
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
if(t3!=null)
t3.setText(o.getDate());
}
}
}
return v;
}
}
Add the following as the first line in the for loop of your fill() method:
if(ff.isHidden()) continue;
The File#isHidden() returns true if the file or folder it represents is hidden; i.e. if its filename starts with '.'. The continue statement inside a loop causes the current iteration of the loop to be skipped. So, this code basically says "If this file/folder is hidden, just go to the next one."
I read the article about "Making ListView Scrolling Smooth" on android.developer.com but there is one thing I don't understand : where to put or get the value of "position" because my eclipse says :"Cannot refer to a non-final variable position inside an inner class defined in a different method".
I put this code in my adapter class in the getView method.
package com.example.filemanager;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Formatter.BigDecimalLayoutForm;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DateSorter;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ItemAdapter extends ArrayAdapter<Item> {
private final Context context;
private final ArrayList<Item> values;
public int position;
public ItemAdapter(Context context, ArrayList<Item> values) {
super(context, R.layout.item, values);
this.context = context;
this.values = values;
}
#Override
public Item getItem(int position) {
// TODO Auto-generated method stub
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.item, parent, false);
TextView title = (TextView) rowView.findViewById(R.id.title);
TextView info = (TextView) rowView.findViewById(R.id.info);
ImageView icon = (ImageView) rowView.findViewById(R.id.icon);
ImageView menu = (ImageView) rowView.findViewById(R.id.menu);
title.setText(values.get(position).getName());
info.setText(sizeString(position) + " " + dateString(position) + " "
+ rightsString(position));
if (values.get(position).isisDir()) {
icon.setImageResource(R.drawable.dir);
} else if (!values.get(position).isisDir()) {
if (values.get(position).getPath().endsWith(".jpg")
|| values.get(position).getPath().endsWith(".png")) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 50;
options.inDensity = 100;
options.inScreenDensity = 1;
Bitmap myBitmap = BitmapFactory.decodeFile(values.get(position).getPath(), options);
icon.setImageBitmap(myBitmap);
}else{
icon.setImageResource(R.drawable.file);
}
}
menu.setImageResource(R.drawable.menu);
ViewHolder holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.menu = (ImageView) convertView.findViewById(R.id.menu);
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.info = (TextView) convertView.findViewById(R.id.info);
holder.progress = (ProgressBar) convertView.findViewById(R.id.progressSpinner);
convertView.setTag(holder);
// Using an AsyncTask to load the slow images in a background thread
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
//return mFakeImageLoader.getImage();
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == position) {
// If this item hasn't been recycled already, hide the
// progress and set and show the image
v.progress.setVisibility(View.GONE);
v.icon.setVisibility(View.VISIBLE);
v.icon.setImageBitmap(result);
}
}
}.execute(holder);
return rowView;
}
private String rightsString(int position) {
String temp = "";
if (values.get(position).isReadable()) {
temp += "r";
} else {
temp += "-";
}
if (values.get(position).isWritable()) {
temp += "w";
} else {
temp += "-";
}
if (values.get(position).isExecutable()) {
temp += "x";
} else {
temp += "-";
}
return temp;
}
private String dateString(int position) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
return df.format(values.get(position).getDate());
}
private String sizeString(int position) {
long bytes = values.get(position).getSize();
double kb = bytes / 1024.0;
double mb = kb / 1024.0;
double gb = mb / 1024.0;
if (gb >= 1) {
return gb + " GB";
}
if (mb >= 1) {
return mb + " MB";
}
if (kb >= 1) {
return kb + " KB";
} else {
return bytes + " bytes";
}
}
static class ViewHolder {
ImageView icon, menu;
TextView title, info;
ProgressBar progress;
int position;
}
}
Okay, so you need to understand a little bit about outer,inner and anonymous classes,etc. What's going on is that you are creating an anonymous class with the declaration of
new AsyncTask()....
and any variables inside of that class need to be final or not referencing the parent class.
So, what you need to do is this:
final int finalPosition = position;
// Using an AsyncTask to load the slow images in a background thread
new AsyncTask() {
private ViewHolder v;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == finalPosition) {
// If this item hasn't been recycled already, hide the
// progress and set and show the image
v.progress.setVisibility(View.GONE);
v.icon.setVisibility(View.VISIBLE);
v.icon.setImageBitmap(result);
}
}
}.execute(holder);
Reference
I have developed a Contacts application. It does everything that a normal contacts application should does. There is always a chance of improvement. I had noticed in Android Emulator that loading for contact images starts when user has settled, he has scrolled the contact list to the area where there are chances are good that he would get contact he is searching for. So, I tried to implement the same thing on my app copy. I have implemented it. Its running very very slow. As I presume, I believe that application is running the thread multiple time even if it has retrieved the image which leads to big lagging. I am aware of the ASync task but just out of curiosity and to check whether it can be done, I don't wish to implement it here. Here is the source code for MainActivity.
package com.example.contact;
import java.io.InputStream;
import java.util.ArrayList;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
}));
}
};
}
}
Code for MyAdapter,
package com.example.contact;
import java.util.ArrayList;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<String> {
private Context context;
private ListView listview;
private ArrayList<String> ids;
private LayoutInflater infl;
private String displayname;
private String maindetail;
private SimplifiedContact contact;
private Drawable drawable;
public MyAdapter(Context context, int ResourceId, ArrayList<String> list)
{
super(context, ResourceId, list);
this.context = context;
ids = list;
infl = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
drawable = context.getResources().getDrawable(R.drawable.person);
}
static class ViewHolder
{
public ImageView image;
public TextView display_name;
public TextView main_detail;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
contact = new SimplifiedContact(context, Long.valueOf(ids.get(position)));
if(row == null)
{
row = infl.inflate(R.layout.single_cell, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.display_name =(TextView) row.findViewById(R.id.disp_name);
viewHolder.main_detail = (TextView) row.findViewById(R.id.main_detail);
viewHolder.image = (ImageView)row.findViewById(R.id.contact_iamge);
row.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) row.getTag();
holder.display_name.setText(contact.getDisplayName());
holder.main_detail.setText(contact.getMainDetail());
holder.image.setBackgroundDrawable(drawable);
return row;
}
}
I wish to know, how this lag can be reduced. Thanks in advance.
Why don't you try to take that Thread instance that you are making in runOnUiThread and put It in a field, initializing It in the onCreate. I think that you are creating several thread instaces with no use.
public class MainActivity extends ListActivity {
ListView listview;
private boolean mPaused;
private MyAdapter mAdapter;
private View view;
private boolean running = false;
final private ArrayList<String> con_ids = new ArrayList<String>();
private Context context;
Thread uiThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = getListView();
context = this;
Cursor c = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.Contacts.DISPLAY_NAME+" ASC");
if(c!=null)
{
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
con_ids.add(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
}
}
uiThread = new Thread(new Runnable() {
int totalChild = listview.getChildCount();
int first = listview.getFirstVisiblePosition() - listview.getHeaderViewsCount();
int toRetrieve = want-first;
int id;
long con_id;
Bitmap thumbnail;
final ListView list = listview;
#Override
public void run() {
// TODO Auto-generated method stub
while(running)
{
if(!(toRetrieve<0||toRetrieve>=totalChild))
{
id = want+toRetrieve;
con_id = Long.valueOf(con_ids.get(id));
Uri ContactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, con_id);
InputStream stream = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), ContactUri);
thumbnail = BitmapFactory.decodeStream(stream);
if(thumbnail == null)
{
toRetrieve++;
continue;
}
else
{
View view = list.getChildAt(toRetrieve);
if(view == null)
{
toRetrieve++;
continue;
}
else
{
ImageView iamge = (ImageView) view.findViewById(R.id.contact_iamge);
iamge.setImageBitmap(thumbnail);
}
toRetrieve++;
}
}
else
{
running = false;
}
}
}
});
mAdapter = new MyAdapter(this, android.R.layout.simple_list_item_1, con_ids);
listview.setAdapter(mAdapter);
listview.setOnScrollListener(makeScrollListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
private AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
running = false;
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
String log = "";
Log.d(log, "Scroll First Item" + i);
Log.d(log, ""+ listview.getChildCount());
final int want = i;
running = true;
runOnUiThread(uiThread);
}
};
}
}