Sunday, 9 June 2013

Bitmap to File in Android

File f = File(context.getCacheDir(), filename);
f.createNewFile();

Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();


FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);

Friday, 19 April 2013

How Run Other App using intent in android


Intent i = new Intent(); PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage("app package name"); i.addCategory(Intent.CATEGORY_LAUNCHER); startActivity(i)

Wednesday, 13 March 2013

UnZip file in Android

With the help of this function we can unzip file with in any given folder in sdcard :

public static boolean UnZipFolder(String zipFileString, String outPathString)throws Exception {
            android.util.Log.v("XZip", "UnZipFolder(String, String)");
            java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new         java.io.FileInputStream(zipFileString));
            java.util.zip.ZipEntry zipEntry;
            String szName = "";
            while ((zipEntry = inZip.getNextEntry()) != null) {
              szName = zipEntry.getName();
              if (zipEntry.isDirectory()) {
                szName = szName.substring(0, szName.length() - 1);
                java.io.File folder = new java.io.File(outPathString + java.io.File.separator + szName);
                folder.mkdirs();
              } else {
                try{
                java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName);
                file.createNewFile();
                java.io.FileOutputStream out = new java.io.FileOutputStream(file);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = inZip.read(buffer)) != -1) {
                  out.write(buffer, 0, len);
                  out.flush();
                }
                out.close();
                }catch(Exception e){
                  Log.d("UI","unzip error!");
                }
              }
            }   
            inZip.close();
            return true;
          }

Tuesday, 5 February 2013

How to use external database in android

Here in code for use external database in android project. 
1) first put your .db file(database file ) in assets folder
2) then use below code for copy database into project package.
package com.mobidhan.databasecopy;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DataBaseCopy extends SQLiteOpenHelper{
private static String database_n;//database name
private static String database_p ;//database path
private static final int DATABASE_VERSION = 2;
private static String DatabaseName;
private SQLiteDatabase dataBase;
private final Context dbContext;
//DB_NAME is name of database which is in assets folder
//path is our package name
public DataBaseCopy(Context context,String DB_NAME,String PATH) {
super(context, DB_NAME, null, DATABASE_VERSION);
DatabaseName=DB_NAME;
database_p="/data/data/"+PATH+"/databases/";
this.dbContext = context;
database_n = DatabaseName;
// checking database and open it if exists
if (checkDataBase()) {
openDataBase();
} else
{
try {
this.getReadableDatabase();
copyDataBase();
this.close();
openDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
Toast.makeText(context, "database is created", Toast.LENGTH_LONG).show();
}
}
private void copyDataBase() throws IOException{
InputStream myInput = dbContext.getAssets().open(database_n);
String outFileName = database_p + database_n;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String dbPath = database_p + database_n;
dataBase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
boolean exist = false;
try {
String dbPath = database_p + database_n;
checkDB = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
Log.v("santosh", "database error");
}
if (checkDB != null) {
Log.v("santosh", "database exist");
exist = true;
checkDB.close();
}
return exist;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}


Monday, 4 February 2013

Contact Picker in android

Contact Picker one of the impotent utility which we are using many of app. with the help of this we can pick contact from our phone contact list and show/use them into our app.

1) xml layout for Contact Picker

                      <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" >

                            <EditText
                                android:id="@+id/editText1"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:ems="10"
                                android:hint="Select Contact" >

                                <requestFocus />
                            </EditText>

                            <Button
                                android:id="@+id/button1"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:text="Pick " />
                        </LinearLayout>

2) Activity java Code:-

public class Scheduler extends Activity implements OnClickListener {
private Button b1;
private EditText contact;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(this);
contact=(EditText)findViewById(R.id.editText1);

}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0==b1)
{
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);
}

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri ur=data.getData();
Cursor c=managedQuery(ur, null, null, null, null);
if(c.moveToFirst())
{
String s=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contact.setText(s);
}
}
}

}


Time Picker in Android

Here we see that how we use Time Picker Dialog to pick time and show in textview :-

2) XML Layout for TimePicker


                     <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" >

                            <EditText
                                android:id="@+id/editText3"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:ems="10"
                                android:hint="Select Time" />

                            <Button
                                android:id="@+id/button3"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:text="Pick" />
                        </LinearLayout>


2) Java Code For Time Picker
      public class Scheduler extends Activity implements OnClickListener {
private int hour;
private int minute;
static final int Time_DIALOG_ID = 125;
private Button b3;
private EditText time;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(this);
contact=(EditText)findViewById(R.id.editText1);
date=(EditText)findViewById(R.id.editText2);
time=(EditText)findViewById(R.id.editText3);
final Calendar c = Calendar.getInstance();
        hour=c.get(Calendar.HOUR);
                minute=c.get(Calendar.MINUTE);
}
@Override
public void onClick(View arg0) {
if(arg0==b3)
{
showDialog(Time_DIALOG_ID);
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_DIALOG_ID:
return new TimePickerDialog(this, timepickerlistner,hour, minute,true);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timepickerlistner =new OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
hour = arg1;
minute = arg2;
time.setText(new StringBuilder().append(hour)
.append(":").append(minute).append(" "));
}
};
}



Date Picker in Android

In This Section we Know the how to use Date Picker Dialog in android to pick date and show in textview:

1) Layout for  Date Picker Activity

                     <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" >

                            <EditText
                                android:id="@+id/editText2"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:ems="10"
                                android:hint="Select Date" />

                            <Button
                                android:id="@+id/button2"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:text="Pick" />
                        </LinearLayout>

2) Java Activity Code :
        public class Scheduler extends Activity implements OnClickListener {
private int year;
private int month;
private int day;
static final int DATE_DIALOG_ID = 123;
private Button b1;
private EditText date;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(this);
date=(EditText)findViewById(R.id.editText2);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
        }
@Override
public void onClick(View arg0) {
if(arg0==b1)
{
showDialog(DATE_DIALOG_ID);
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, datePickerListener,
year, month,day);
}
return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {

public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
date.setText(new StringBuilder().append(month + 1)
.append("/").append(day).append("/").append(year).append(" "));
                         }
};
    }


Saturday, 2 February 2013

How To use button In android

How To use Buttons Event
In this Section we see that how we use android Button widget in android application and how we hendal Button event.
Step 1: First create A new Project. Then in our activity layout Put a button  from widget controls. then our layout look like bellow code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ButtonActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="29dp"
        android:text="Button" />

</RelativeLayout>

Setp 2: Now in java Code

import android.os.Bundle;
import android.app.Activity;
public class ButtonActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button);
}
}


Create Object of Button and assing with button which is created in layout
Button b=(Button)findViewById(R.id.button1);
Now Set Click Event on Button Object

b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//write code which you want to do on click event
}
});

Wednesday, 10 October 2012

Read File by extension from memory in android


private static void searchFolderRecursive1(File folder) {
    if (folder != null) {
        if (folder.listFiles() != null) {
            for (File file : folder.listFiles()) {
                if (file.isFile()) {
                    if(file.getName().contains("file extension")){
                        Log.v("ooo", "path__="+file.getName());
                    }
                } else {
                    searchFolderRecursive1(file);
                }
            }
        }
    }
}

Friday, 5 October 2012

Play Audio fron url or Server in android

try {
                MediaPlayer player = new MediaPlayer();
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.setDataSource("server mp3 link" );
                player.prepare();
                            player.start();

            } catch (Exception e) {
                // TODO: handle exception
            }

Thursday, 4 October 2012

What is push massage Service in Android (Cloud to device messaging )

Most mobile apps require data from the Internet. One approach for updating its data is that the apps periodically polls a server for new data (Polling). If no new data is available this approach uses unnecessary network bandwidth and consumes the battery of the mobile phone.
An alternative approach is that the server contacts the mobile app once new data is available (Push). If the data does not change constantly, Push is the preferred solution. 

As of Android 2.2 it is possible to push information to an Android app. This service is called Cloud to Device messaging or short C2DM.
In a C2DM you have three involved parties. The application server which wants to push messages to the Android device, Googles C2DM servers and the Android app. The program on the application server can be written in any programming language, e.g. Java, PHP, Python, etc.
When the application server needs to push a message to the Android application, it sends the message via an HTTP POST to Google’s C2DM servers.
The C2DM servers route the message to the device. If the device is not online, the message will be delivered once the device is available. Once the message is received, an Broadcast Intent is created. The mobile app has registered an Intent Receiver for this Broadcast. The app is started and processes the message via the defined Intent Receiver.
C2DM messages are limited in size to 1024 bytes and are intended to inform the device about new data not to transfer it. The typical workflow is that Googles C2DM servers notify the Android app that new data is available. Afterwards the Android app fetches the data from a different server.

Tuesday, 2 October 2012

Display Text on User Define Path on android canvas

Path circle = new Path();
circle.addCircle(centerX, centerY, radius, Direction.CW);
// set the color and font size
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(30);
paint.setAntiAlias(true);
// draw the text along the circle
canvas.drawTextOnPath(QUOTE, circle, 0, 30, paint);

Convert milliseconds to HH:MM:SS String in java


  1. long timeMillis = ...;  
  2. long time = timeMillis / 1000;  
  3. String seconds = Integer.toString((int)(time % 60));  
  4. String minutes = Integer.toString((int)((time % 3600) / 60));  
  5. String hours = Integer.toString((int)(time / 3600));  
  6. for (int i = 0; i < 2; i++) {  
  7. if (seconds.length() < 2) {  
  8. seconds = "0" + seconds;  
  9. }  
  10. if (minutes.length() < 2) {  
  11. minutes = "0" + minutes;  
  12. }  
  13. if (hours.length() < 2) {  
  14. hours = "0" + hours;  
  15. }  
  16. } 

Saturday, 29 September 2012

Way to communicate with server in java

Many ways to communicate with a server

Socket class
• Lets you do general-purpose network programming
– Same as with desktop Java programming

HttpURLConnection
• Simplifies connections to HTTP servers
– Same as with desktop Java programming

HttpClient
• Simplest way to download entire content of a URL
– Not standard in Java SE, but standard in Android

JSONObject
• Simplifies creation and parsing of JSON data
– Not standard in Java SE, but standard in Android

Thursday, 27 September 2012

Diffrent input-type value in EditText Android

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Friday, 21 September 2012

Android Dialog Box with item select

final CharSequence[] items = {"Add Note", "Add Anniversary", "Add Event","View All"};
        AlertDialog.Builder builder = new
        AlertDialog.Builder(MyCalendar.this);
        builder.setTitle("Add Details");
        //builder.setIcon(R.drawable.calendarmonth);
        builder.setItems(items, new    DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item)
        {
         if(item==0)
         {
             Intent in=new Intent(MyCalendar.this, AddNote.class);
                startActivity(in);
         }
         else if(item==1)
         {
             Intent in=new Intent(MyCalendar.this, AddAnnivarsory.class);
                startActivity(in);
         }
         else if(item==2)
         {
             Intent in=new Intent(MyCalendar.this, AddEvent.class);
                startActivity(in);
         }
         else if(item==3)
         {
             Intent in=new Intent(MyCalendar.this, ViewAll.class);
                startActivity(in);
         }
        }
        });
        AlertDialog alert = builder.create();
        alert.show();

Friday, 14 September 2012

Open Android Market App using url in Android

Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setData(Uri.parse("market://search?q=pname:MyApp")); 
startActivity(intent);

Wednesday, 12 September 2012

Upload Image from Android to Server using PHP

Android Activity for upload image on Server:--
package com.santosh.geo_map_social_app;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class MainActivity extends Activity {

 InputStream is;

 @Override

 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.activity_main);
  new  AddTask().execute();
 }
 class AddTask extends AsyncTask<Void,Void, Void> {

  private ProgressDialog dialog;
  protected void onPreExecute() {
   dialog = new ProgressDialog(MainActivity.this);
   dialog.setMessage("Retrieving data ...");
   dialog.setIndeterminate(true);
   dialog.setCancelable(false);
   dialog.show();
  }

  protected Void doInBackground(Void... unused) {
   Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
   ByteArrayOutputStream bao = new ByteArrayOutputStream();
   bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
   byte [] ba = bao.toByteArray();
   String ba1=Base64.encodeBytes(ba);
   ArrayList<NameValuePair> nameValuePairs = new
     ArrayList<NameValuePair>();
   nameValuePairs.add(new BasicNameValuePair("image",ba1));
   try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new
      HttpPost("http://192.168.1.10:80/GK/ImageUpload.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
   }catch(Exception e){
    Log.e("log_tag", "Error in http connection "+e.toString());
   }
   return(null);
  }

  protected void onProgressUpdate(Void... unused) {
   // grid_main.setAdapter(imgadp);
  }

  protected void onPostExecute(Void unused) {
   dialog.dismiss();

  }
 }


}

Thursday, 6 September 2012

Find Your CURRENT Location In Android

package com.santosh.map;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class FindMyLocation extends Activity implements LocationListener{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocationManager locationmanger=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Criteria c=new Criteria();
        c.setAccuracy(Criteria.ACCURACY_FINE);
        c.setAltitudeRequired(false);
        c.setBearingRequired(false);
        c.setCostAllowed(true);
        c.setPowerRequirement(Criteria.POWER_LOW);
        String provider=locationmanger.getBestProvider(c, true);
        Location location=locationmanger.getLastKnownLocation(provider);
      
        locationmanger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                0, 0, this);
      
    }


    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            System.out.println("Lat:"+location.getLatitude());
            System.out.println("Lat:"+location.getLongitude());
            System.out.println("Lat:"+location.getAccuracy());
            System.out.println("Lat:"+location.getAltitude());
            System.out.println("Lat:"+location.getBearing());
            System.out.println("Lat:"+location.getProvider());
            System.out.println("Lat:"+location.getSpeed());
            System.out.println("Lat:"+location.getTime());
             }

        Toast.makeText(FindMyLocation.this, "onLocationChanged", 1).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(FindMyLocation.this, "onProviderDisabled", 1).show();
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(FindMyLocation.this, "onProviderEnabled", 1).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        Toast.makeText(FindMyLocation.this, "onStatusChanged", 1).show();
    }
 
   
   
}

Wednesday, 5 September 2012

Delect Incoming Call in Android

public class PhoneCallReceiver extends BroadcastReceiver {
 Context context = null;
 private static final String TAG = "Phone call";
 private ITelephony telephonyService;

 @Override
 public void onReceive(Context context, Intent intent) {
  Log.v(TAG, "Receving....");
  TelephonyManager telephony = (TelephonyManager) 
  context.getSystemService(Context.TELEPHONY_SERVICE);  
  try {
   Class c = Class.forName(telephony.getClass().getName());
   Method m = c.getDeclaredMethod("getITelephony");
   m.setAccessible(true);
   telephonyService = (ITelephony) m.invoke(telephony);
   telephonyService.silenceRinger();
   telephonyService.endCall();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 
 
//////////////////////////////////////
 
interface ITelephony {

   
    boolean endCall();

  
    void answerRingingCall();

   
    void silenceRinger();

  }
 
/////////////////////////////////////////////
 
   android:name="android.permission.MODIFY_PHONE_STATE" />
     android:name="android.permission.CALL_PHONE" />
     android:name="android.permission.READ_PHONE_STATE" />