Android: ParsingXMLFiles only gets the values for the first XML - android

Hi I have designed a File Explorer which I use to show some XML files and depending on the selected one I open one XML or another. Until the moment there is no problem at all and with the help of XMLPullParser I insert the text from the attributes into some ArrayLists. The problem is that IF I go back and I select another XML file these values are the same as the following XML and that happens with the following XMLs. I think that the problem is that the arrayLists don´t get empty once a new instance is called.
Here is how this works:
FileExporer where I show the files and I click on anyone.
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
private String root;
private TextView myPath;
static File file;
static String texto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView)findViewById(R.id.path);
root = Environment.getExternalStorageDirectory().getPath();
getDir(root);
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
if(!file.isHidden() && file.canRead() && (file.getName().endsWith("xml"))){
path.add(file.getPath());
if(file.isDirectory()){
item.add(file.getName() + "/");
}else{
item.add(file.getName());
}
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
file = new File(path.get(position));
if (file.isDirectory())
{
if(file.canRead()){
getDir(path.get(position));
}else{
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK", null).show();
}
}else {
file = new File(path.get(position));
file.getName();
XMLPullParser.Parse(this);
texto = XMLPullParserHandler.getA(0);
}
Parseo();
Intent i = new Intent(MainActivity.this, Correccion.class);
startActivity(i);
MainActivity.this.finish();
}
public void Parseo(){
}
public static String fileName(){
return file.getName();
}
public static String getText(){
return texto;
}
}
XMLPullParser: It says the file that need to be read and calls a new isntance of XMLPullParserHandler.
public class XMLPullParser{
static String Fichero;
public static void Parse(Context context){
try {
List<Puntuacion> puntuacion;
XMLPullParserHandler parser = new XMLPullParserHandler();
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, MainActivity.fileName());
FileInputStream iStream = new FileInputStream(yourFile);
puntuacion = parser.parse(iStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
XMLPullParserHandler: I think that here is the problem, when I create and add text to the ArrayLists: For example in this case in ArrayList a
public class XMLPullParserHandler {
List<Puntuacion> puntuaciones;
private Puntuacion puntuacion;
static List<String> nombres = new ArrayList<String>();
static List<String> a = new ArrayList<String>();
private String text;
public XMLPullParserHandler() {
// puntuaciones.clear();
// puntuaciones.removeAll(puntuaciones);
puntuaciones = new ArrayList<Puntuacion>();
;
}
public List<Puntuacion> getPuntuacion() {
return puntuaciones;
}
public List<Puntuacion> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
try {
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("TEST")) {
// create a new instance of puntuacion
puntuacion = new Puntuacion();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("TEST")) {
puntuaciones.add(puntuacion);
} else if (tagname.equalsIgnoreCase("NUMERO_ACIERTOS")) {
puntuacion.setValor_Transformado((text));
a.add(text);
Log.i("ii", text);
}
break;
default:
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return puntuaciones;
}
public static String getNombre(int posicion){
String[] ListN = new String[nombres.size()];
ListN = nombres.toArray(ListN);
return ListN[posicion];
}
public static String getA(int posicion){
String[] ListA = new String[a.size()];
ListA = a.toArray(ListA);
return ListA[posicion];
}
}
For example if I have in this case a XML with **<NUMERO_ACIERTOS>1</NUMERO_ACIERTOS>** and after this I read another one with **<NUMERO_ACIERTOS>3</NUMERO_ACIERTOS>** in my UI I only see the value **1** because is the first that has been loaded into the arraylist.
thank you for your time and attention.

No me gustan estos:
static List<String> nombres = new ArrayList<String>();
static List<String> a = new ArrayList<String>();
They should not be static, and probably should be private:
private List<String> nombres;
private List<String> a;
I think they should be created new when you start your parse like this:
public List<Puntuacion> parse(InputStream is) {
XmlPullParserFactory factory = null;
XmlPullParser parser = null;
nombres = new ArrayList<String>();
a = new ArrayList<String>();
try {
¡Buena suerte!

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 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 program to convert the SQLite database to excel

I want to change the sqlite database .db file to excel.
But I am not able to find what exactly I have to do. Can anybody please elaborate in a simple way what I have to perform to achieve this task.
By searching on Google, so many links appears, but I am not able to understand the step by step way to do this.
I have followed these links:
1. How to convert excel sheet into database of sqlite in android
2. SQlite database programmatically convert into Excel file format in Android
3. http://opencsv.sourceforge.net/
My solution is to convert the sqlite database into csv in first step then in second step is to convert the csv file to xls and it works fine for me, you will need 2 libraries (opencsv-1.7.jar; poi-3.8-20120326.jar)
public class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean>
{
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Exporting database...");
this.dialog.show();
}
protected Boolean doInBackground(final String... args)
{
File dbFile=getDatabasePath("database_name");
//AABDatabaseManager dbhelper = new AABDatabaseManager(getApplicationContext());
AABDatabaseManager dbhelper = new AABDatabaseManager(DatabaseExampleActivity.this) ;
System.out.println(dbFile); // displays the data base path in your logcat
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "excerDB.csv");
try
{
if (file.createNewFile()){
System.out.println("File is created!");
System.out.println("myfile.csv "+file.getAbsolutePath());
}else{
System.out.println("File already exists.");
}
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
//SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor curCSV=db.getdb().rawQuery("select * from " + db.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
String arrStr[] ={curCSV.getString(0),curCSV.getString(1),curCSV.getString(2)};
/*curCSV.getString(3),curCSV.getString(4)};*/
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
/*String data="";
data=readSavedData();
data= data.replace(",", ";");
writeData(data);*/
return true;
}
catch(SQLException sqlEx)
{
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
return false;
}
catch (IOException e)
{
Log.e("MainActivity", e.getMessage(), e);
return false;
}
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "Export succeed", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "Export failed", Toast.LENGTH_SHORT).show();
}
}}
Export CSV to XLS part
public class CSVToExcelConverter extends AsyncTask<String, Void, Boolean> {
private final ProgressDialog dialog = new ProgressDialog(DatabaseExampleActivity.this);
#Override
protected void onPreExecute()
{this.dialog.setMessage("Exporting to excel...");
this.dialog.show();}
#Override
protected Boolean doInBackground(String... params) {
ArrayList arList=null;
ArrayList al=null;
//File dbFile= new File(getDatabasePath("database_name").toString());
File dbFile=getDatabasePath("database_name");
String yes= dbFile.getAbsolutePath();
String inFilePath = Environment.getExternalStorageDirectory().toString()+"/excerDB.csv";
outFilePath = Environment.getExternalStorageDirectory().toString()+"/test.xls";
String thisLine;
int count=0;
try {
FileInputStream fis = new FileInputStream(inFilePath);
DataInputStream myInput = new DataInputStream(fis);
int i=0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null)
{
al = new ArrayList();
String strar[] = thisLine.split(",");
for(int j=0;j<strar.length;j++)
{
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}} catch (Exception e) {
System.out.println("shit");
}
try
{
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for(int k=0;k<arList.size();k++)
{
ArrayList ardata = (ArrayList)arList.get(k);
HSSFRow row = sheet.createRow((short) 0+k);
for(int p=0;p<ardata.size();p++)
{
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if(data.startsWith("=")){
cell.setCellType(Cell.CELL_TYPE_STRING);
data=data.replaceAll("\"", "");
data=data.replaceAll("=", "");
cell.setCellValue(data);
}else if(data.startsWith("\"")){
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
}else{
data=data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch ( Exception ex ) {
ex.printStackTrace();
} //main method ends
return true;
}
protected void onPostExecute(final Boolean success)
{
if (this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (success)
{
Toast.makeText(DatabaseExampleActivity.this, "file is built!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(DatabaseExampleActivity.this, "file fail to build", Toast.LENGTH_SHORT).show();
}
}
}
I know this question is a little old but it provided me with the answer to the same question. I've cleaned up the code a little and done away with the need to write a csv file altogether by getting my database helper class to return me an ArrayList. Still using Apache POI though.
File folder =new File(Environment.getExternalStorageDirectory()+APP_FILES_PATH);
if(!folder.exists())
{
folder.mkdir();
}
DatabaseHelper dbHelper = DatabaseHelper.getInstance(context);
ArrayList<String[]> exts = dbHelper.getExtinguisherArray(1);
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("extinguishers");
for(int x = 0; x < exts.size(); x++)
{
String[] arr = exts.get(x);
HSSFRow row = sheet.createRow(x);
for(int i = 0; i< arr.length; i++)
{
HSSFCell cell = row.createCell(i);
String data = arr[i];
cell.setCellValue(data);
}
}
FileOutputStream fileOut = new FileOutputStream(Environment.getExternalStorageDirectory()+APP_FILES_PATH+"file.xls");
hwb.write(fileOut);
fileOut.close();
Export Android SqliteDb to CSV format
You need to do these step...
add this jar file opencsv-1.7.jar http://www.java2s.com/Code/Jar/o/Downloadopencsv17jar.htm
And then use this code
public class ExportDatabaseToCSV{
Context context;
public ExportDatabaseToCSV(Context context) {
this.context=context;
}
public void exportDataBaseIntoCSV(){
CredentialDb db = new CredentialDb(context);//here CredentialDb is my database. you can create your db object.
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists())
{
exportDir.mkdirs();
}
File file = new File(exportDir, "csvfilename.csv");
try
{
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
SQLiteDatabase sql_db = db.getReadableDatabase();//here create a method ,and return SQLiteDatabaseObject.getReadableDatabase();
Cursor curCSV = sql_db.rawQuery("SELECT * FROM "+CredentialDb.TABLE_NAME,null);
csvWrite.writeNext(curCSV.getColumnNames());
while(curCSV.moveToNext())
{
//Which column you want to export you can add over here...
String arrStr[] ={curCSV.getString(0),curCSV.getString(1), curCSV.getString(2)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
}
catch(Exception sqlEx)
{
Log.e("Error:", sqlEx.getMessage(), sqlEx);
}
}
}
In addition to #user2324120's answer, and as we're in Android, you can directly add the libs to gradle (and therefore you don't need to download the jars) :
compile 'com.opencsv:opencsv:3.7'
compile 'org.apache.poi:poi:3.14'
I also did it a different way, a way more customisable one (and without useless CSV transition). Here it is, with a few comments :
public static Pair<Boolean, String> exportToXLS(Context context, boolean byAuthor) {
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(context.getString(R.string.sheet_name)); // Good for localization
initSheetColumns(context, workbook, sheet, byAuthor);
addBooksToSheet(sheet, byAuthor);
setColumsWidth(sheet);
OutputStream outputStream = new FileOutputStream(new File(Methods.getDownloadsDirectory(), byAuthor ? context.getString(R.string.mylibrary_by_author_xls) : context.getString(R.string.mylibrary_xls)).getAbsolutePath());
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
return new Pair<>(true, context.getString(R.string.database_saved));
} catch (Exception e) {
e.printStackTrace();
return new Pair<>(false, context.getString(R.string.an_error_has_occured_during_xls_file_creation));
}
}
private static void initSheetColumns(Context context, HSSFWorkbook workbook, HSSFSheet sheet, boolean byAuthor) {
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(byAuthor ? context.getString(R.string.db_author) : context.getString(R.string.db_title));
cell = row.createCell(1);
cell.setCellValue(byAuthor ? context.getString(R.string.db_title) : context.getString(R.string.db_author));
cell = row.createCell(2);
cell.setCellValue(context.getString(R.string.db_publisheddate));
/*
etc.
*/
boldHeaders(workbook, row);
}
private static void boldHeaders(HSSFWorkbook workbook, HSSFRow row) {
HSSFCellStyle style = workbook.createCellStyle();
/* Do your own style
...
*/
for (int i = 0; i < 8; i++) {
row.getCell(i).setCellStyle(style);
}
}
// Allow data personalisation and localisation if needed
private static void addBooksToSheet(HSSFSheet sheet, boolean byAuthor) {
int i = 1;
List<Book> books = Book.listAll(Book.class); // I use Sugar library here, if you're not just make a simple db query to get your objects
Collections.sort(books, byAuthor ? Book.bookAuthorComparator : Book.bookNameComparator);
for (Book book : books) {
HSSFRow row = sheet.createRow(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(byAuthor ? getBookValue(book, true) : book.getTitle());
cell = row.createCell(1);
cell.setCellValue(byAuthor ? book.getTitle() : getBookValue(book, false));
cell = row.createCell(2);
cell.setCellValue(book.getPublishedDate());
/*
etc.
*/
i++;
}
}
private static void setColumsWidth(HSSFSheet sheet) {
for (int i = 0; i < 8; i++) {
sheet.setColumnWidth(i, 255 * getMaxNumCharacters(sheet, i)); // Autosize not working on Android
}
}
// My method to get the max num char, if it can hekp
public static int getMaxNumCharacters(Sheet sheet, int column) {
int max = 0;
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
continue;
}
Cell cell = row.getCell(column);
if (cell != null) {
int nb = cell.getStringCellValue().length();
if (nb > max) {
max = nb;
}
}
}
max = (int) (max * 1.1);
if (max > 255) {
return 255; // max 255 char for width
}
return max;
}
Hope it helps!

android delete item from list [duplicate]

This question already has answers here:
Android expandable list need help to delete item
(2 answers)
Closed 8 years ago.
public class DeleteActivity extends ExpandableListActivity {
private RingtoneAdapter expListAdapter;
int myProgress = 0;
List<String> items = new ArrayList<String>();
final Context myApp = this;
// private static final String DIRECTORY = "/system/media/audio/ringtones/";
private static final String DIRECTORY = "/sdcard/download/";
private MediaPlayer mp = new MediaPlayer();
List<String> Ringtones = new ArrayList<String>();
ArrayAdapter<String> adapter;
TextView tv, empty;
ExpandableListView exlv1;
// ListView lv1;
Boolean hasErrors = false;
int currentPosition = 0;
private static final String LOG_TAG = "MobiIntheMorning";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
refreshList();
Toast.makeText(this, "hello this is delete called", Toast.LENGTH_LONG).show();
Ringtones.remove(DIRECTORY+Ringtones.get(1));//THIS DOSE NOT GIVING ANY AFFECT
refreshList();
Intent i = new Intent(DeleteActivity.this, FindFilesByType.class);
startActivity(i);
}
public void refreshList() {
File ringtones_directory = new File(DIRECTORY);
if (!ringtones_directory.exists()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Directory Not Found");
ad.setMessage("Sorry! The ringtones directory doesn't exist.");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
}
if ( !ringtones_directory.canRead()) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! You don't have permission to list the files in that folder");
ad.setPositiveButton("OK", null);
ad.show();
hasErrors = true;
} else {
Ringtones = FindFiles(false);
if (Ringtones.size() < 1) {
AlertDialog.Builder ad = new AlertDialog.Builder(
DeleteActivity.this);
ad.setTitle("Permissions");
ad.setMessage("Sorry! No ringtones exists in " + DIRECTORY
+ ".");
ad.setPositiveButton("OK", null);
ad.show();
Log.e(LOG_TAG, "No ringtones were found.");
hasErrors = true;
}
}
try {
if ( !hasErrors) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
DeleteActivity.this, android.R.layout.test_list_item,
Ringtones);
ArrayList<String> GrouppList = new ArrayList<String>();
GrouppList.addAll(Ringtones);
ArrayList<ArrayList<Color>> colors = new ArrayList<ArrayList<Color>>();
for (int i = 0; i <= Ringtones.size(); i++) {
ArrayList<Color> color = new ArrayList<Color>();
color = new ArrayList<Color>();
color.add(new Color("", "", true));
colors.add(color);
}
expListAdapter = new RingtoneAdapter(this, GrouppList, colors);
Toast.makeText(this, GlobalVariable.getstrEmail(),
Toast.LENGTH_LONG).show();
Ringtones.remove(0);
// setListAdapter(expListAdapter);
exlv1 = (ExpandableListView) findViewById(R.id.expandableListView1);
this.exlv1.setAdapter(this.expListAdapter);
}
this.exlv1.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int arg0) {
Toast.makeText(DeleteActivity.this, "hello" + arg0,
Toast.LENGTH_LONG).show();
GlobalVariable.SetcurrentPosition(arg0);
GlobalVariable.SetstrEmail(DIRECTORY + Ringtones.get(arg0));
}
});
} catch (Exception e) {
Toast.makeText(this, "Error " + e.toString(), Toast.LENGTH_LONG)
.show();
Log.i(LOG_TAG, e.toString());
}
}
private List<String> FindFiles(Boolean fullPath) {
final List<String> tFileList = new ArrayList<String>();
Resources resources = getResources();
// array of valid audio file extensions
String[] audioTypes = resources.getStringArray(R.array.audio);
FilenameFilter[] filter = new FilenameFilter[audioTypes.length];
int i = 0;
for (final String type : audioTypes) {
filter[i] = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("." + type);
}
};
i++;
}
FileUtils fileUtils = new FileUtils();
File[] allMatchingFiles = fileUtils.listFilesAsArray(
new File(DIRECTORY), filter, -1);
for (File f : allMatchingFiles) {
if (fullPath) {
tFileList.add(f.getAbsolutePath());
} else {
tFileList.add(f.getName());
}
}
return tFileList;
} // find fil
#SuppressWarnings("unchecked")
public List<String> loadArray(String filename) {
try {
FileInputStream fis = new FileInputStream(filename);
GZIPInputStream gzis = new GZIPInputStream(fis);
ObjectInputStream in = new ObjectInputStream(gzis);
List<String> read_field = (List<String>) in.readObject();
in.close();
return read_field;
} catch (Exception e) {
e.getStackTrace();
}
return null;
}
public Collection<File> listFiles(File directory, FilenameFilter[] filter,
int recurse) {
Vector<File> files = new Vector<File>();
File[] entries = directory.listFiles();
if (entries != null) {
for (File entry : entries) {
for (FilenameFilter filefilter : filter) {
if (filter == null
|| filefilter.accept(directory, entry.getName())) {
files.add(entry);
Log.v(LOG_TAG, "Added: " + entry.getName());
}
}
if ((recurse <= -1) || (recurse > 0 && entry.isDirectory()))
files.addAll(listFiles(entry, filter, recurse - 1));
}
}
return files;
}
public class FileUtils {
public void saveArray(String filename, List<String> output_field) {
try {
FileOutputStream fos = new FileOutputStream(filename);
GZIPOutputStream gzos = new GZIPOutputStream(fos);
ObjectOutputStream out = new ObjectOutputStream(gzos);
out.writeObject(output_field);
out.flush();
out.close();
} catch (IOException e) {
e.getStackTrace();
}
}
public File[] listFilesAsArray(File directory, FilenameFilter[] filter,
int recurse) {
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
}
}
I've done some code that code fetches .mp3 files from the sdcard and displays it to me
now i am trying to delete selected item from it using
Ringtones.remove(DIRECTORY+Ringtones.get(1));
that is it should delete my first item from the list but it doesn't works for me
what is wrong i ma doing into this?
I am not able to find any silly mistakes I made here; Ringtones.remove("test.mp3"); and Ringtones.remove(1.mp3); both I've also tried.
Why are you doing
DIRECTORY + Ringtones.get(1)
Ringtones is a List so you want to be doing something like
Ringtones.remove(1);
or
Ringtones.remove(aRintoneString)
what you effectively doing here is getting the first element and adding a other string which gives you a NEW third string that doesn't exist in Ringtones
Hi Call notifyDataSetChanged() on your Adapter after removing the item from the List.
It will refresh your List and you will get updated items in your list.

Categories

Resources