Android Programming – setContentView()


setContentView() is a very important function when it comes to programming with Android.

One has to understand its use completely to work with Android UserInterface.

Basically what this function does is display the Layout created thorugh XML or the Dynamically created layout view in the Screen.

 

Syntax –

For an XML Layout –

setContentView(R.layout.showexcer);

where showexcer.xml is your xml file.

For Dynamically created Java View/Layout

View v1=new View(this);
setContentView(v1);

Similarly a dynamically created layout can be dispalyed using setContentView();

  • setContentView is amethod of Activity class. So to call you the class should be a subclass of Activity class.

Android Database Table export to CSV – Part 3


I tried out the method mentioned here. Soon I found out that this was not the thing that I needed .

I needed the table level data which had the transactional information and not database level data.

So CSV was a good option.

In Android phones you can view the csv file in an excel format using ThinkFree Office tools. Similarly in PC using MSOffice Excel.

The code structure is similar to the export to DB as used in the previous post, the difference is that we use a thrid-party Java CSV library called OPENCSV.

/*******************************************************************************
********************************************************************************
Export Database into CSV Class
********************************************************************************
*******************************************************************************/
    class ExportDatabaseCSVTask extends AsyncTask<String, Void, Boolean> 
    {
        private final ProgressDialog dialog = new ProgressDialog(ctx);

        // can use UI thread here
        @Override
        protected void onPreExecute() 
        {
            this.dialog.setMessage("Exporting database...");
            this.dialog.show();
        }   

        // automatically done on worker thread (separate from UI thread)
        protected Boolean doInBackground(final String... args) 
        {
            File dbFile=getDatabasePath("excerDB.db");
            DbClass DBob = new DbClass(MainActivity.this);
            File exportDir = new File(Environment.getExternalStorageDirectory(), "");        
            if (!exportDir.exists()) 
            {
                exportDir.mkdirs();
            }
            File file = new File(exportDir, "excerDB.csv");
            try 
            {
                file.createNewFile();                
                CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
                SQLiteDatabase db = DBob.getReadableDatabase();
                Cursor curCSV = db.rawQuery("SELECT * FROM ExcerTable",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();
                return true;
            }
            catch(SQLException sqlEx)
            {
                Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
                return false;                
            }
            catch (IOException e) 
            {
                Log.e("MainActivity", e.getMessage(), e);
                return false;
            }
        }
        // can use UI thread here
        @Override
        protected void onPostExecute(final Boolean success) 
        {
            if (this.dialog.isShowing()) 
            {
                this.dialog.dismiss();
            }
            if (success) 
            {
                Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
            } 
            else 
            {
                Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
            }
        }
    }

 

This is used with a button Listener as follows –

Context ctx = MainActivity.this;
//Create a Button listener for the CSV Export
Button impCSVBtn = (Button) findViewById(R.id.imp_csv_id);
impCSVBtn.setOnClickListener(new OnClickListener() {

    public void onClick(View view)
    {

  try
  {
      new ExportDatabaseCSVTask().execute("");
  }
  catch(Exception ex)
  {
      Log.e("Error in MainActivity",ex.toString());
  }
    }
});

This solved the export data problem for my app.

 

References :

http://stackoverflow.com ( No specific question but after reading the responses for similar questions I came up with this ).

 

Related Reading :

Android Database Table export to CSV – Part 1

Android Database Table export to CSV – Part 2

Android Database Table export to CSV – Part 2


Copy the Android database into DB File –

  • This is the easier of the two methods. I put a search in Google and found many queries and resolution for this.
  • Basically what we do here is the SQLite Database creates .db file. this db file is copied as it is as a backup. We can use external SQLite readers in our PC to access the data.
  • Code :

We create an class that extends AsyncTask so that export is handled in a thread.

/*******************************************************************************
********************************************************************************
Export Database into file Class
********************************************************************************
*******************************************************************************/    
    class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> 
    {
        private final ProgressDialog dialog = new ProgressDialog(ctx);

        // can use UI thread here
        @Override
        protected void onPreExecute() 
        {
            this.dialog.setMessage("Exporting database...");
            this.dialog.show();
        }   

        // automatically done on worker thread (separate from UI thread)
        protected Boolean doInBackground(final String... args) 
        {
            File dbFile = new File(Environment.getDataDirectory() + 
                    "/data/org.test.xyz/databases/excerDB.db");
            File exportDir = new File(Environment.getExternalStorageDirectory(), "");        
            if (!exportDir.exists()) 
            {
                exportDir.mkdirs();
            }
            File file = new File(exportDir, dbFile.getName());
            try 
            {
                file.createNewFile();
                this.copyFile(dbFile, file);
                return true;
            } 
            catch (IOException e) 
            {
                Log.e("mypck", e.getMessage(), e);
                return false;
            }
        }
        // can use UI thread here
        @Override
        protected void onPostExecute(final Boolean success) 
        {
            if (this.dialog.isShowing()) 
            {
                this.dialog.dismiss();
            }
            if (success) 
            {
                Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
            } 
            else 
            {
                Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
            }
        }
        void copyFile(File src, File dst) throws IOException 
        {
            FileChannel inChannel = new FileInputStream(src).getChannel();
            FileChannel outChannel = new FileOutputStream(dst).getChannel();
            try 
            {
                inChannel.transferTo(0, inChannel.size(), outChannel);
            } 
            finally 
            {
                if (inChannel != null)
                    inChannel.close();
                if (outChannel != null)
                    outChannel.close();
            }
        }
    }

This function is called in the OnClick Button event

Context ctx = MainActivity.this; 
//Create a Button Listener for Export database
Button impDBBtn = (Button) findViewById(R.id.imp_db_id);
impDBBtn.setOnClickListener(new OnClickListener() {
    public void onClick(View view)
    {

  try
  {
      new ExportDatabaseFileTask().execute("");
  }
  catch(Exception ex)
  {
      Log.e("Error in MainActivity",ex.toString());
  }
    }            
});
//Export Database into file Class

This is a very easy way of creating the backup of your App Data. But the diadvantage is that we need external database viewer to read the data.

If the data needs to be viewed then we need to use CSV Format which can be easily opened through Microsoft Excel.

References

StackOverFlow