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"));

}

}

XML Parsing by DOM Parser



Simple Xml Parsing with DOM Parser

1. Sept :- XML Parser.

we use this for xml parsing

XMLParser.java

    public class XMLParser {

public String getXmlFromUrl(String url, Context context) {
String xml = null;

try {
DefaultHttpClient httpClient = new DefaultHttpClient();

HttpParams params = httpClient.getParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
new Integer(1 * 60 * 1000));
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(
1 * 60 * 1000));
HttpConnectionParams.setTcpNoDelay(params, true);
httpClient.setParams(params);

HttpPost httpPost = new HttpPost(url);

BasicHttpResponse httpResponse = (BasicHttpResponse) httpClient
.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = URLDecoder.decode(EntityUtils.toString(httpEntity),
HTTP.UTF_8);

} catch (ConnectTimeoutException e) {
xml = "timeout";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

// return XML
return xml;
}

public String innerXml(Node node) {
String str = "";
try {

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
"yes");
transformer
.transform(new DOMSource(node), new StreamResult(buffer));
str = buffer.toString();

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

return str;
}

public Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {

DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);

} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}

return doc;
}

public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}

public String getValue(Element item, String str) {
NodeList n = (item).getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}


2. Make one class for xml parsing
public class MainActivity extends Activity {

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



}

class aTask extends AsyncTask<Void, Void, Void> {
int succ = 0;
ArrayList<HashMap<String, String>> alDData = new ArrayList<HashMap<String, String>>();

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

@Override
protected Void doInBackground(Void... params) {
try {

String url = "http://";

XMLParser xp = new XMLParser();
String response = xp.getXmlFromUrl(url, MainActivity.this);

Document doc = xp.getDomElement(response);
NodeList nl = doc.getElementsByTagName("response");
for (int i = 0; i < nl.getLength(); i++) {
Element element = (Element) nl.item(i);
if (xp.getValue(element, "success").equals("1")) {
succ = 1;

      HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat",
xp.getValue(element, "lat"));
hm.put("lng",
xp.getValue(element, "lng"));

hm.put("sImage", CompleteFilePath);
alDData.add(hm);
}
} else
succ = 0;

Log.d("testing", response);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (succ == 1 && alDData.size() > 0) {
llNoDriver.setVisibility(View.GONE);
Log.e("testing", "> " + alDData);
ListAdapter adapter = new ListAdapter(activity,
alDData);
lvList.setAdapter(adapter);
} else {
lvList.setAdapter(null);
}
}

}


3. Your adapter

CustomAdapter.java

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

ArrayList<HashMap<String, String>> alData;
HashMap<String, String> hm;
Activity activity;

public CustomAdapter(Context context,
ArrayList<HashMap<String, String>> alData) {
super(context, R.layout.custom_list, alData);
this.alData = alData;
this.activity = (Activity) context;
}

static class myHolder {
TextView tvname, tvinfo;

}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
try {

if (view == null) {
view = activity.getLayoutInflater().inflate(
R.layout.custom_list, null, false);
myHolder mh = new myHolder();
mh.tvname = (TextView) view.findViewById(R.id.tvname);
mh.tvinfo = (TextView) view.findViewById(R.id.tvinfo);

view.setTag(mh);
}
} catch (Exception e) {
// TODO: handle exception
}
return view;

}
}


This is Simple way for xml parsing.. thanks

How we can check our hardware in android

1. Check out Hardware details with simple tutorial :-

package system_detail;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import com.example.spynew.R;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class hardware_detail_tab extends Activity {
TextView CPU;
TextView MEMORY;
TextView DISPLAY;
String display_info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hardware_detail_tab);
CPU=(TextView)findViewById(R.id.cpu);
CPU.setText(ReadCPUinfo());
MEMORY=(TextView)findViewById(R.id.memory);
MEMORY.setText(getTotalRAM());
DISPLAY=(TextView)findViewById(R.id.display);
}

private String ReadCPUinfo()
{
 ProcessBuilder cmd;
 String result="";

 try{
  String[] args = {"/system/bin/cat", "/proc/cpuinfo"};
  cmd = new ProcessBuilder(args);

  Process process = cmd.start();
  InputStream in = process.getInputStream();
  byte[] re = new byte[1024];
  while(in.read(re) != -1){
   System.out.println(new String(re));
   result = result + new String(re);
  }
  in.close();
 } catch(IOException ex){
  ex.printStackTrace();
 }
 return result;
}
public static String getTotalRAM() {
   RandomAccessFile reader = null;
   String load = null;
   try {
       reader = new RandomAccessFile("/proc/meminfo", "r");
       load = reader.readLine();
   } catch (IOException ex) {
       ex.printStackTrace();
   } finally {
       // Streams.close(reader);
   }
   return load;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}