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;
}

}