Monday 4 May 2015

Json Parsing

Fetch data from webservice

public class View_data extends Activity {

private ProgressDialog pDialog;
String returnString; // to store the result of MySQL query after decoding
// JSON
TextView RESULT, lattitude, longitude, address, time;
Button View_button;
JSONArray jArray;
String result;
StringBuilder sb;
InputStream is;
List<Item> arrayOfList;
/** Called when the activity is first created. */
String ct_name, lattitude1, longitude1, time1, address1;
Datarow objAdapter;
ListView listview;

@Override
public void onCreate(Bundle savedInstanceState) {

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

listview = (ListView) findViewById(R.id.listView1);
arrayOfList = new ArrayList<Item>();

// TODO Auto-generated method stub
new task().execute();

}

@Override
public void onBackPressed() {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setTitle("Exit")
.setMessage("Do you want to exit?")
.setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// continue with delete
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
})
.setNegativeButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// do nothing
}
}).setIcon(android.R.drawable.ic_dialog_alert).show();
}

class task extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(View_data.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.i("doing", "back");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// http post

try {
HttpClient httpclient = new DefaultHttpClient();


HttpPost httppost = new HttpPost(
"http://10.0.0.2/Projectjsonscript.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());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

is.close();
result = sb.toString();
Log.i("Result", "Json" + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

String name;
try {

jArray = new JSONArray(result);

JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);

Item objItem = new Item();
objItem.setName(json_data.getString("name"));
objItem.setlat(json_data.getString("lattitude"));
objItem.setlongi(json_data.getString("longitude"));
objItem.setdesc(json_data.getString("address"));
objItem.settime(json_data.getString("time"));
arrayOfList.add(objItem);
}

} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Data Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
return null;
}

private void setAdapterToListview() {
// TODO Auto-generated method stub
objAdapter = new Datarow(View_data.this, R.layout.list_item_card,
arrayOfList);
listview.setAdapter(objAdapter);
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
setAdapterToListview();
if (pDialog.isShowing())
pDialog.dismiss();
}
}

}



Php Code:


<?php
mysql_connect("localhost","username","password");
mysql_select_db("DB_NAME");
$sql=mysql_query("select * from TABLE");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));// this will print the output in json
mysql_close();
?>



No comments:

Post a Comment