Friday, 1 June 2012

How to add a background horizontally in vertical linear layout?

There are some contexts in which we have to make such a layout in which the horizontal background is needed on verical layouts, then in this case Frame Layout will come into your help. Just we have to do one thing , to put the given vertical layout in the FrameLayout with an image view added in it.
Let me show you in this example :- 

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        
        <FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        
        <ImageView  android:layout_width="match_parent"
        android:layout_height="20dp"
        android:layout_gravity="bottom"
        android:layout_marginBottom="55dp"
        android:layout_marginLeft="60dp"
        android:background="#D8D8D8"/>

<LinearLayout>

//Your code here for the development of vertical layout on which you want to apply the horizontal background as shown in the figure.

</LinearLayout>
</FrameLayout>
</LinearLayout>

Wednesday, 2 May 2012

Audio Recording in Android


There are many times when we people have to integrate audio recording feature in our application.
It is very easy to implement Just we have to make an Audio Recorder class and call it from our activity as:-



public class AudioRecorderHelper {

MediaRecorder mRecorder = new MediaRecorder();
String path;


public AudioRecorderHelper(String path){

this.path = savePath(path);

}

private String savePath(String path){

if(!path.startsWith("/")){

path = "/" + path;

}

if(!path.contains(".")){
path+= ".3gp";

}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}

public void start() throws IOException{

String state = android.os.Environment.getExternalStorageState();
   if(!state.equals(android.os.Environment.MEDIA_MOUNTED))  {
       throw new IOException("SD Card is not mounted.  It is " + state + ".");
   }

   // make sure the directory we plan to store the recording in exists
   File directory = new File(path).getParentFile();
   if (!directory.exists() && !directory.mkdirs()) {
     throw new IOException("Path to file could not be created.");
   }

   mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
   mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
   mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
   mRecorder.setOutputFile(path);
   mRecorder.prepare();
   mRecorder.start();
}


public void stop() throws IOException {
   mRecorder.stop();
   mRecorder.release();
 }
}



Call this class and use its start and stop functions on your demand whenever you want.
Try it. The code is complete.


Monday, 30 April 2012

How to show the data saved in the database in a List View

There comes many aspects where we cant to show the database data in a List View. So here is the easiest way to get it out.

For this case we have to use SimpleCursor Adapter as :-

public class GetList extends Activity {

DBadapter db;
ListView lv;
@Override
public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.data_list);

db = new DBadapter(this);
getData();

}

public void getData(){


try {
db.open();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

lv = (ListView)findViewById(R.id.dbList);
List<String> items = new ArrayList<String>();
Cursor c = db.getAllData();
    c.moveToFirst(); 
    
    ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row_for_db, c, new String[]{"_id", "userName", "Password"}, new int[]{R.id.ID,R.id.name,R.id.Password} );
    lv.setAdapter(adapter);
    
}  


where getAllData() is a function in DBAdapter class and it is as follows :-

public Cursor getAllData(){
 
return db.query(TABLE_NAME, new String[] {_id,userName,Password}, null, null, null, null, null);
}


This is how you can get the data from a database in a List View.

How to Download a File in Android and show its progress in the Progress Dialog

We can implement this in a number of ways and one of the way is using the AsyncTask and show the download progress.
The method is as follows:-

Just make a button and on its onclick event call the below function as :- startDownload();




private void startDownload() {
String url = "WRITE YOUR URL THAT YOU WANT TO DOWNLOAD";
new DownloadFileAsync().execute(url);
}


@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
myProgressDialog = new ProgressDialog(this);
myProgressDialog.setMessage("Downloading the file..");
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setCancelable(false);
myProgressDialog.show();
return myProgressDialog;
default:
return null;
}
}

class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
int count;

try {

URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/yourfilename.extension");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;

}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
myProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}


After running this activity you can check your file in the specified location above.

Make sure to give the following permissions in your Manifest File for the proper functioning of the Downloading Activity. i.e :-


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

This is all done about downloading a file and showing its progress.


Friday, 27 April 2012

How to show the image stored in the sdcard on the Imageview

Many a times there is a requirement when we want to show the image on the imageview that is currently stored on the sdcard.

Step 1:- First out get the actual path of the image stored on sd card.for e.g -

 /mnt/sdcard/peng.jpg


Step 2 :- Make the use of the File class of java and then use the File reference to show the image on the Imageview. for e.g

File imageFile = new File("/mnt/sdcard/peng.jpg");


Step 3  :- Now use this refrence to show the image with the help Bitmap.


Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());


Imageview myView = (Imageview)findViewById(R.id.main);


myView.setImageBitmap(myBitmap);




That's all. It will show the particular image that is stored on the sdcard on the Imageview.

How to get the Real Path of the Image Stored in sdcard

Generally the on Activity Result gives us the path in the form :-

Uri  imagePath = data.getData();
Content://media/external/images/media/1


To get the Real Path of the image or any other thing located in sdcard use this function.

Call this function with your URI path i.e of the type - Content://media/external/images/media/1



public String getRealPathFromURI(Uri contentURI){


String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentURI, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
       
}




Now it will give you the real path i.e :-
/mnt/sdcard/peng.jpg


which is generally required.