Sunday, 17 July 2016

Google Autocomplete Places api Example


Hi here i'm giving you simple example about autocomplete, if you want you can try other from referring google api site. Just follow few steps. Hope this help you to understand and do your work easily

Step 1.
In you Activity you need to use edit text as text changed listener, then call places api


        et_Search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

                    placesTask = new PlacesTask();
                    String[] toPass = new String[2];
                    toPass[0] = s.toString();
                    placesTask.execute(toPass);

            }
        });

Step 2.
 here is calling for google places api

// Fetches all places from GooglePlaces AutoComplete Web Service
    private class PlacesTask extends AsyncTask<String, Void, String> {

        private String val = "";
        @Override
        protected String doInBackground(String... place) {
            // For storing data from web service
            String data = "";

            // Obtain browser key from https://code.google.com/apis/console
            String key = "key="+getResources().getString(R.string.google_server_key);

            String input="";

            try {
                input = "input=" + URLEncoder.encode(place[0], "utf-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            String parameters = input+"&"+key + "&components=country:in";
            // Output format +gpsTracker.getLatitude() + "," + gpsTracker.getLongitude() + "&radius=20000
            String output = "json";

            // Building the url to the web service
            String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;

            try{
                // Fetching the data from we service
                data = Webservices.ApiCallGet(url);
            }catch(Exception e){
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            // Creating ParserTask
            parserTask = new ParserTask();

            String[] strData = new String[2];
            strData[0] = result;
            // Starting Parsing the JSON string returned by Web Service
            parserTask.execute(strData);
        }
    }

Step 3. Getting Result

    /** A class to parse the Google Places in JSON format */
    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

        JSONObject jObject;

        @Override
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;

            PlaceJSONParser placeJsonParser = new PlaceJSONParser();


            try{
                jObject = new JSONObject(jsonData[0]);

                // Getting the parsed data as a List construct
                places = placeJsonParser.parse(jObject);

            }catch(Exception e){
                Log.d("Exception",e.toString());
            }
            return places;
        }

        @Override
        protected void onPostExecute(List<HashMap<String, String>> result) {

            String[] from = new String[] { "description"};
            int[] to = new int[] { android.R.id.text1 };
                AutoCompleteAdapter adapter = new AutoCompleteAdapter(getBaseContext(), result);

                // Setting the adapter
                if(adapter != null && result != null )
                    lv_SearchList.setAdapter(adapter);

        }
    }

    // Fetches  latitude & longitude from place id
    private class LatLongTask extends AsyncTask<Void, Void, String> {

        private HashMap<String, String> placeMap;
        private ProgressDialog dialog;

        public LatLongTask(HashMap<String, String> placeMap){
            this.placeMap = placeMap;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = ProgressDialog.show(SearchActivity.this, "", "Please Wait...",
                    true, false);
        }

        @Override
        protected String doInBackground(Void... place) {
            // For storing data from web service
            String data = "";

            // Obtain browser key from https://code.google.com/apis/console
            String key = "key="+getResources().getString(R.string.google_server_key);

            String input="";

            try {
                input = "placeid=" + URLEncoder.encode(placeMap.get("place_id"), "utf-8");
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }

            // Building the parameters to the web service
            String parameters = input+"&"+key ;

            // Output format
            String output = "json";

            // Building the url to the web service
            String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;

            try{
                // Fetching the data from we service
                data = Webservices.ApiCallGet(url);
            }catch(Exception e){
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if(dialog!= null && dialog.isShowing()){
                dialog.dismiss();
            }

            try {
                JSONObject jResult = new JSONObject(result);
                if(jResult.getString("status").equals("OK")) {
                    JSONObject jsonObject = jResult.getJSONObject("result");
                    JSONObject jGeometry = jsonObject.getJSONObject("geometry");
                    JSONObject jLocation = jGeometry.getJSONObject("location");
                    placeMap.put("lat", ""+jLocation.getString("lat"));
                    placeMap.put("lng", ""+jLocation.getString("lng"));
                    ArrayList<HashMap<String, String>> mapArrayList = new ArrayList<HashMap<String, String>>();
                    mapArrayList.add(placeMap);
                    Intent intent = new Intent();
                    intent.putExtra("result",  mapArrayList);
                    if (getParent() == null) {
                        setResult(Activity.RESULT_OK, intent);
                    } else {
                        getParent().setResult(Activity.RESULT_OK, intent);
                    }
                    finish();
                }else{
                    Utils.toastmessage(SearchActivity.this, "Please try again later.");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }


Step 4. create this class


public class PlaceJSONParser {

    /** Receives a JSONObject and returns a list */
    public List<HashMap<String,String>> parse(JSONObject jObject){

        JSONArray jPlaces = null;
        try {
            /** Retrieves all the elements in the 'places' array */
            jPlaces = jObject.getJSONArray("predictions");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        /** Invoking getPlaces with the array of json object
         * where each json object represent a place
         */
        return getPlaces(jPlaces);
    }

    private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
        int placesCount = jPlaces.length();
        List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> place = null;

        /** Taking each place, parses and adds to list object */
        for(int i=0; i<placesCount;i++){
            try {
                /** Call getPlace with place JSON object to parse the place */
                place = getPlace((JSONObject)jPlaces.get(i));
                placesList.add(place);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return placesList;
    }

    /** Parsing the Place JSON object */
    private HashMap<String, String> getPlace(JSONObject jPlace){

        HashMap<String, String> place = new HashMap<String, String>();

        String id="";
        String reference="";
        String description="";
        String place_id = "";

        try {

            description = jPlace.getString("description");
            id = jPlace.getString("id");
            reference = jPlace.getString("reference");
            place_id = jPlace.getString("place_id");

            place.put("description", description);
            place.put("_id",id);
            place.put("reference",reference);
            place.put("place_id", place_id);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return place;
    }


}

Saturday, 7 May 2016

Android apis Calling through Retrofit

Hi guys,

Today i'll show you how to use RetroFit for calling any apis.

Follow some belew step and get it done in easy way.

Step 1.

Compile these  libraries from gradle

    compile 'com.squareup.okhttp:okhttp:2.4.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.2.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Step 2.

Create Interface for calling apis like below

public interface Api {

    // Added server url here, and pass reference of model class, model class you can generate by GSON or manually.

    @POST("/*******/loginapi")
    Call<LoginModal> loginapi(@Body JsonObject data);
}

Step 3.

  Third step to write code on replacement of AsyncTask, calling api

   private void LoginService(JsonObject jsonPostParameters) {
        //While the app fetched data we are displaying a progress dialog

        final ProgressDialog loading = ProgressDialog.show(activity, "", "Please wait...", false, false);

        OkHttpClient okHttpClient1 = new com.squareup.okhttp.OkHttpClient();
        okHttpClient1.setReadTimeout(Common.api_timeinterval, TimeUnit.SECONDS);
        okHttpClient1.setConnectTimeout(Common.api_timeinterval, TimeUnit.SECONDS);

// Pass server base url, i:e www.yoursiteurl.com
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient1)
                .build();

        Api serviceApi = retrofit.create(Api.class);
        // Call<Register> updateUser(@Query("name") String name, @Query("password") String password,@Query("email")String email,@Query("Country") String Country  ,@Query("latitude") String latitude ,@Query("longitude") String longiTude  , @Query("device_token") String device_token );

        serviceApi.loginapi(jsonPostParameters).enqueue(new Callback<LoginModal>() {
            @Override
            public void onResponse(Response<LoginModal> response, Retrofit retrofit) {
                LoginModal loginmodal = response.body();
                loading.dismiss();

                if (loginmodal.getResponse().getResult() == 1) {

// Here you get reponse from model class
 
                } else {
                    Common.showDialogActionLess("Login unsuccessfull !", loginmodal.getResponse().getErrorMSG(),
                            activity);
                }

            }

            @Override
            public void onFailure(Throwable e) {
                loading.dismiss();
                if (e instanceof HttpRetryException) {
                    HttpRetryException response = (HttpRetryException) e;
                }

                Toast.makeText(activity, "Please try again later.", Toast.LENGTH_LONG).show();
                finish();

            }
        });

    }


Step 4.

If you want then take reference from model class :

public class LoginModal {
 
    private ResponseEntity Response;

    public void setResponse(ResponseEntity Response) {
        this.Response = Response;
    }

    public ResponseEntity getResponse() {
        return Response;
    }

    public static class ResponseEntity {
        private int result;
        private String resultText;
        private String errorMSG;
        private int user_id;
 
        public void setResult(int result) {
            this.result = result;
        }

        public void setResultText(String resultText) {
            this.resultText = resultText;
        }

        public void setErrorMSG(String errorMSG) {
            this.errorMSG = errorMSG;
        }

        public void setUser_id(int user_id) {
            this.user_id = user_id;
        }

        public int getResult() {
            return result;
        }

        public String getResultText() {
            return resultText;
        }

        public String getErrorMSG() {
            return errorMSG;
        }
    }
}


Step 5.

Atlast create json or anyformat you want to send to server and call api method.


                    JsonObject jsonObject = new JsonObject();
                    try {
                        jsonObject.addProperty("username", "abc");
                        jsonObject.addProperty("password", "xyz");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    LoginService(jsonObject);



That's all this is the easy and frequent way to call apis from RetroFit.Hopefully somebody will help from this. :)

Saturday, 27 February 2016

XMPP Sample for android

Hi guys,
I have made one sample for xmpp. Its Extensible Messaging and Presence Protocol(XMPP)  is a  communication protocol for messge-oriented middleware based on XML(Extensible Markup Language).

You need to follow few steps and you get it done in very simple way.

Step 1. If you are try in locally then you have to install wamp or lamp or xampp server. After this start the server apache and mysql. Now you have import openfire database in mysql.

Step 2. Install openfire in your system.If you are trying in local  otherwise you can install openfire in your server.

Step 3. Go to below link of github to download my sample for xmpp.

https://github.com/saveendhiman/XMPPSample_Studio

https://github.com/saveendhiman/XMPPSample-Eclipse

If you want to download apk then you can visit direct in play store link

https://play.google.com/store/apps/details?id=com.cool.xmppsample

Also checkout the video from here,

https://www.youtube.com/watch?v=OrL9mepFLQU

Step 4. Enter any id for your xmpp user and you should enter your correct server name and host name from your openfire server.Now enter your opposite user id and then press in online or in android icon.
Chat screen opened.

★★Features have a look at our app Provided you★★

Everything is dynamic. You have to enter ip address of your server where openfire is installed.

Features summary:
- Free!
- Run an XMPP Server
- Use the built-in certificate or use your own for SSL/TLS
- Set users
- Add a Dynamic DNS Updater using the local or public IP of your device
- Enable modules: One to one  chat, database, notification and user is online till you want(background

service).


★★Features★★

* One to one communication.
* Emojis.
* Database handling.
* Notification handling.
* Background service you user is online till you want.
* Typing status.
* Online users
* Duration of online users.
* Avatar from roster.

and many more features provided by us.




Thursday, 26 February 2015

Parse Notification in android

Step 1. Create account in parse and get application id and client id.

Step. Copy parse lib in your libs folder

Step 3.Create class

Application.java

public class Application extends android.app.Application {

public Application() {
}

@Override
public void onCreate() {
super.onCreate();

// Initialize the Parse SDK.
Parse.initialize(this, "ThKJesxP8ZCB5VGziCHeOEWaJjy406MRQ96stgCy",
"RGiIsDzDx3N4FH6NmgIF4z8DT7uzwQJphi79kDNF");

// Specify an Activity to handle all pushes by default.
PushService.setDefaultPushCallback(this, Home_Activity.class);
}
}


Step 4. Call these methods in your main activity

try {

PushService.subscribe(this, "Giants", Home_Activity.class);
PushService.setDefaultPushCallback(this, Home_Activity.class);
ParseAnalytics.trackAppOpened(getIntent());
} catch (Exception e) {
// TODO: handle exception
}


Step 5. Declaration in mainfest file

    <!-- Parse -->
   
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission
        android:name="com.******.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.******.permission.C2D_MESSAGE" />

// Call application class in your first activity

// android:name="com.*****.Application"


At last receiver need to declare in manifest

      <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <service android:name="com.parse.PushService" />

        <receiver android:name="com.parse.ParseBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="com.parse.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />

                <category android:name="com.*****" />
            </intent-



Thats all hopefully somebody help this topic thanks....

Sunday, 15 February 2015

Track calls in android

Step 1. Create one receiver to receive your call and detect,

MyPhoneReceiver.class

public class MyPhoneReceiver extends BroadcastReceiver {

private static final String AUDIO_RECORDER_FILE_EXT_AMR = ".amr";

public static final String AUDIO_RECORDER_FOLDER = "CallRecords";

private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.AMR_NB };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_AMR };
Context context;

public void onReceive(Context context, Intent intent) {

if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
} else if (intent.getAction().equals(
"android.intent.action.PHONE_STATE")) {
handleCalls(context);

} else if (intent.getAction().equals(
"android.intent.action.NEW_OUTGOING_CALL")) {
handleOutgoingCalls(context, intent);
}
}

void sysAlert(String title, String msg, Context context) {
AlertDialog alert = new AlertDialog.Builder(context).setTitle(title)
.setMessage(msg)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.setCanceledOnTouchOutside(false);
alert.show();
}

public void onDestroy() {

telephony.listen(null, PhoneStateListener.LISTEN_NONE);
}

TelephonyManager telephony;

MyPhoneStateListener phoneListener;

void handleOutgoingCalls(Context context, Intent intent) {

String number = intent
.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

try {
if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_RINGING)) {
Log.e("testing", "outgoing call Recording ringing");

} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE)
.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.e("testing", "outgoing call Recording OffHook");
try {
startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}

} else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE)
.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Log.e("testing", "outgoing  call Recording idle");
try {
stopRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}

}
} catch (Exception e) {
e.printStackTrace();
}

}

void handleCalls(Context context) {
if (phoneListener == null) {
phoneListener = new MyPhoneStateListener(context);
telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener,
PhoneStateListener.LISTEN_CALL_STATE);

}
}

public class MyPhoneStateListener extends PhoneStateListener {

Context context;

MyPhoneStateListener(Context context) {
this.context = context;
}

boolean ring = false;
boolean callReceived = false;

public void onCallStateChanged(int state, String incomingNumber) {
Log.e("Testing", "" + state + ", " + incomingNumber);
switch (state) {

case TelephonyManager.CALL_STATE_RINGING:
ring = true;
// Database db = new Database(context);
// db.insertRecord(incomingNumber, "", Call_details.typeCall);
// db.close();
context.sendBroadcast(new Intent("onNewCall"));
Log.e("testing", "Incoming call Recording ringing");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
callReceived = true;
Log.e("testing", "Incoming call Recording OffHook");
// phoneRinging = true;
// phoneRinging = false;
try {
startRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
break;
case TelephonyManager.CALL_STATE_IDLE:
Log.e("testing", "Incoming call Recording idle");
try {
stopRecording();
} catch (IllegalStateException e) {
e.printStackTrace();
}
if (ring == true && callReceived == false) {
Toast.makeText(context,
"It was A MISSED CALL from : " + incomingNumber,
Toast.LENGTH_LONG).show();
}

break;
}

}
}

private String getFilename() {

String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath, AUDIO_RECORDER_FOLDER);

if (!file.exists()) {
file.mkdirs();
}

return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}

private void startRecording() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);

try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private void stopRecording() {
// if (null != recorder) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
// }
}

private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
@Override
public void onError(MediaRecorder mr, int what, int extra) {
}
};

private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
@Override
public void onInfo(MediaRecorder mr, int what, int extra) {
}
};

}


--------------------------------------------------------------------------------------------------------------------
Step 2: 

Main class,

MainActivity.class

public class MainActivity extends Activity {

Context context;
Activity act;
ListView lvcall;
public static final String typeCall = "2";
public static final String typeOutgoingCall = "3";

BroadcastReceiver onNewCall = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {

}
};
BroadcastReceiver onOutgoingCall = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {

}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
act = MainActivity.this;
registerReceiver(onNewCall, new IntentFilter("onNewCall"));
registerReceiver(onOutgoingCall, new IntentFilter("onOutgoingCall"));

lvcall = (ListView) findViewById(R.id.lvcall);
callno_record = (TextView)findViewById(R.id.callno_record);
calldetails(typeCall, typeOutgoingCall);
}

@Override
protected void onDestroy() {
super.onDestroy();
try {
unregisterReceiver(onNewCall);
unregisterReceiver(onOutgoingCall);
} catch (Exception e) {
e.printStackTrace();
Log.e("test", "crash in call details");
}

}
void calldetails(String type, String type1) {
Database db = new Database(act);
ArrayList<HashMap<String, String>> al = db.getRecord(type);

db.close();
for (int i = 0; i < al.size(); i++) {
HashMap<String, String> hm = al.get(i);
String name = getName(act.getContentResolver(),
hm.get(phoneNo));
// hm.put("name", hm.get(phoneNo) + " " + name);
hm.put("name", hm.get(phoneNo));
}
if (al.size() > 0) {
lvcall.setVisibility(View.VISIBLE);
SimpleAdapter adapter = null;

if (type.equals(typeCall)) {

adapter = new SimpleAdapter(act, al,
R.layout.call_details_view,
new String[] { "name", time }, new int[] {
R.id.txtPhoneNo, R.id.txtTime });

} else if (type1.equals(typeOutgoingCall)) {

adapter = new SimpleAdapter(act, al,
R.layout.call_details_view,
new String[] { "name", time }, new int[] {
R.id.txtPhoneNo, R.id.txtTime });
}
lvcall.setAdapter(adapter);
callno_record.setVisibility(View.GONE);
} else {
lvcall.setAdapter(null);
lvcall.setVisibility(View.GONE);
}

}

public String getName(ContentResolver cr, String phoneNo) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);

while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumber = phoneNumber.trim().replaceAll(" ", "");
if (phoneNumber.equals(phoneNo))
return name;
}
phones.close();
return "UnKnown";
}

}

------------------------------------------------------------------------------------------------------------------------

Step 3.:
Allow  permissions in your manifest file,

this is your uses permission:
  <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.READ_USER_DICTIONARY" />

and receiver is here,

 <receiver android:name="com.test.MyPhoneReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.PHONE_STATE" />
            <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
        </intent-filter>
    </receiver>

--------------------------------------------------------------------------------------------
thats all, hope this is useful for somebody.. thanks

Thursday, 6 November 2014

Retrieve current location by gps as well as interent

hey follows few steps to get proper and accurate current location. This way provided you current location both by interent as well as gps.
Step 1.

Put this class in your code.

 GetCurLocation.java

public class GetCurLocation implements LocationListener,
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener {

public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;

SetOnLocationFoundListner OLF;

public interface SetOnLocationFoundListner {
    public void onLocationFound(Location location, boolean getLocRegularly,
            GoogleMap gmap);
}

public void RemoveUpdates() {
    try {
        if (mLocationClient != null)
            mLocationClient.removeLocationUpdates(this);
        if (locationmanager != null)
            locationmanager.removeUpdates(LocUpByLocMgr);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

/*
 * radius should be in meters
 */
public GetCurLocation(Activity activity, int interval,
        boolean getLocRegularly, GoogleMap gmap,
        SetOnLocationFoundListner OLF, float Radius) {
    this.OLF = OLF;
    this.gmap = gmap;
    this.context = activity;
    this.getLocRegularly = getLocRegularly;
    this.interval = interval;
    this.Radius = Radius;
    if (servicesConnected()) {
        mLocationClient = new LocationClient(context, this, this);
        mLocationClient.connect();
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(interval);
        mLocationRequest
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setFastestInterval(interval);
    }

    locationmanager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    Criteria cr = new Criteria();
    String provider = locationmanager.getBestProvider(cr, true);
    locationmanager.requestLocationUpdates(provider, interval, 0,
            LocUpByLocMgr);
}

private boolean servicesConnected() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(context);
    if (ConnectionResult.SUCCESS == resultCode) {
        return true;
    } else {
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
                (Activity) context, 0);
        if (dialog != null) {
        }
        return false;
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {

}

@Override
public void onConnected(Bundle connectionHint) {
    try {
        Location location = mLocationClient.getLastLocation();
        Log.e("testing",
                location.getLatitude() + "," + location.getLongitude()
                        + "," + location.getAccuracy());
        if (location.getAccuracy() < Radius) {
            OLF.onLocationFound(location, getLocRegularly, gmap);
            locationmanager.removeUpdates(LocUpByLocMgr);
        } else
            mLocationClient.requestLocationUpdates(mLocationRequest, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onDisconnected() {
}

@Override
public void onLocationChanged(Location location) {
    try {
        if (location.getAccuracy() > Radius) {
            Log.e("testing LC", location.getAccuracy()
                    + " Its Not Accurate");
        } else {
            Log.e("testing LC", location.getAccuracy() + " Its Accurate");
            try {
                OLF.onLocationFound(location, getLocRegularly, gmap);
                if (!getLocRegularly) {
                    mLocationClient.removeLocationUpdates(this);
                    locationmanager.removeUpdates(LocUpByLocMgr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChanged(Location location) {

        try {
            if (location.getAccuracy() > Radius) {
                Log.e("testing LM", location.getAccuracy()
                        + " Its Not Accurate");
            } else {
                Log.e("testing LM", location.getAccuracy()
                        + " Its Accurate");

                try {
                    OLF.onLocationFound(location, getLocRegularly, gmap);
                    if (!getLocRegularly) {
                        mLocationClient
                                .removeLocationUpdates(GetCurLocation.this);
                        locationmanager.removeUpdates(LocUpByLocMgr);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};

}

Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.

GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
                2000); 

Step 3. make permission

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

thats all. thanks

Sunday, 19 October 2014

JSON Parsing

Step 1.

JSONParser.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

InputStream is = null;
JSONObject jObj = null;
String json = "";

// constructor
public JSONParser() {
}

public String getJSONFromUrl(String url) {

// Making HTTP request
try {

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("response", "" + httpResponse);

HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}


}


Sept 2.

MainHome.java

import java.util.HashMap;
import java.util.LinkedList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {

ListView lvdata;
LinkedList<HashMap<String, String>> aldata = new LinkedList<HashMap<String, String>>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();

new getData().execute();
}

void init() {
lvdata = (ListView) findViewById(R.id.lvdata);

}

private class getData extends AsyncTask<Void, Void, String> {
Dialog dialog;
String url;

@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected String doInBackground(Void... params) {
url = "Enter your url";

JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
try {
JSONObject jobject = new JSONObject(json);

int success = jobject.getInt("success");

for (int i = 0; i < jobject.length() - 1; i++) {
JSONObject jobj = jobject
.getJSONObject(Integer.toString(i));
if (success == 1) {
HashMap<String, String> hm = new HashMap<String, String>();

hm.put("p_name", jobj.getString("p_name"));
hm.put("p_title", jobj.getString("p_title"));
aldata.add(hm);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;

}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
if (dialog.isShowing())
dialog.dismiss();
Custom_Adapter adapter = new Custom_Adapter(
(Activity) MainActivity.this, aldata);
lvdata.setAdapter(adapter);
}
}

}


3. Custom Adapter

Custom_Adapter.java

import java.util.HashMap;
import java.util.LinkedList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class Custom_Adapter extends ArrayAdapter<HashMap<String, String>> {

private final Activity context;
private final LinkedList<HashMap<String, String>> allData;

public Custom_Adapter(Activity context,
LinkedList<HashMap<String, String>> list) {
super(context, R.layout.custom_list, list);
this.context = context;

this.allData = list;
}

static class ViewHolder {

TextView tvname, tvinfo;

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
view = null;
if (view == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.custom_list, null);
final ViewHolder viewHolder = new ViewHolder();
initAll(view, viewHolder);
view.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) view.getTag();
fillAll(holder, position);
return view;

}

public void initAll(View view, ViewHolder viewHolder) {

viewHolder.tvname = (TextView) view.findViewById(R.id.tvname);

viewHolder.tvinfo = (TextView) view.findViewById(R.id.tvinfo);

}

public void fillAll(final ViewHolder holder, final int position) {

holder.tvname.setText(allData.get(position).get("p_name"));
holder.tvinfo.setText(allData.get(position).get("p_title"));

}

}