Parsing JSON by Gson - android

I have JSON. Actually I present my POJO class to yours because my JSON like it and I want put JSON to in it.
I've seen videos from YouTube and Googling but they have parsed all info JSON to their class. Not part of attribute JSON.
public class Earthquake {
List<Property> properties;
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
}
And:
public class Property {
private String mMagnitude;
private String mLocation;
private long mDate;
public Property(String mMagnitude, String mLocation, long mDate) {
this.mMagnitude = mMagnitude;
this.mLocation = mLocation;
this.mDate = mDate;
}
public String getmMagnitude() {
return mMagnitude;
}
public String getmLocation() {
return mLocation;
}
public long getmDate() {
return mDate;
}
}
this is json online api.in my practice I want put some information that there are in the "features" list and "properties" object into my Earthquake pojo class.as you can see there is a list of Property attribute. I just need "mag", "place", "time" of Property attribute.
I want parse this JSON by JSON.How can I do it?
I used this way for parsing:
List<Earthquake> earthquakes = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(earthQuakeJSON);
JSONArray earthquakeArray = baseJsonResponse.optJSONArray("features");
for (int i = 0; i < earthquakeArray.length(); i++) {
JSONObject currentEarthquake = earthquakeArray.optJSONObject(i);
JSONObject properties = currentEarthquake.optJSONObject("properties");
String magnitude = properties.getString("mag");
String location = properties.getString("place");
long time = properties.getLong("time");
Earthquake earthquake = new Earthquake(magnitude, location, time);
earthquakes.add(earthquake);
}
But how can I do by Gson?

Based upon the json data I believe you are using the EarthQuake and Properties in a wrong way
You don't need EarthQuake object with getter and setter for list of Properties
You can just rename the Properties class to Earthquake which would be our actual list to be parsed.
public class Property {
#SerializedName("mag")
private String mMagnitude;
#SerializedName("place")
private String mLocation;
#SerializedName("time")
private long mDate;
public Property(String mMagnitude, String mLocation, long mDate) {
this.mMagnitude = mMagnitude;
this.mLocation = mLocation;
this.mDate = mDate;
}
public String getmMagnitude() {
return mMagnitude;
}
public String getmLocation() {
return mLocation;
}
public long getmDate() {
return mDate;
}
}
Finally to parse the json use this...
Gson gson = new Gson();
Type listOfEarthQuake= new TypeToken<List<Earthquake>>() {}.getType();
return gson.fromJson(earthQuakeString,listOfEarthQuake);

i tried your code but doesnt work :
i made some change if it can help you :
Earthquake
import java.util.ArrayList;
public class Earthquake {
ArrayList<Property> properties= new ArrayList<Property>();
public Earthquake(long t , long m , String p){
Property pr = new Property(m ,p, t);
properties.add(pr);
}
}
Property
public class Property {
private long mMagnitude;
private String mLocation;
private long mDate;
public Property(long mMagnitude, String mLocation, long mDate) {
this.mMagnitude = mMagnitude;
this.mLocation = mLocation;
this.mDate = mDate;
}
}
Main
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
public class MainProp {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
List<Earthquake> earthquakes = new ArrayList<Earthquake>();
List<Earthquake> fromjson = new ArrayList<Earthquake>();
JSONParser jsp = new JSONParser();
String url ="https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmagnitude=6";
JSONObject obj = jsp.makeHttpRequest(url, "GET");
JSONArray earthquakeArray = obj.getJSONArray("features");//baseJsonResponse.optJSONArray("features");
for (int i = 0; i < earthquakeArray.length(); i++) {
JSONObject currentEarthquake = earthquakeArray.optJSONObject(i);
JSONObject properties = currentEarthquake.optJSONObject("properties");
Iterator<?> keys = properties.keys();
long time =0;
String location ="";
long magnitude =0;
Earthquake earthquake = null;
while( keys.hasNext() ) {
String key = (String)keys.next();
if("time".equals(key))
time = properties.getLong("time");
if("place".equals(key))
location = properties.getString("place");
if("mag".equals(key))
magnitude = properties.getLong("mag");
if(!"".equals(location) && time !=0 && magnitude != 0){
earthquake = new Earthquake(time,magnitude,location);
earthquakes.add(earthquake);
}
}
Gson gson = new Gson();
String json = gson.toJson(earthquake);
System.out.println(json);
Earthquake fromjsonItem = gson.fromJson(json, Earthquake.class);
fromjson.add(fromjsonItem);
}
}
}
Parser DefaultHttpClient is now deprecated :(
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.JSONException;
import org.json.JSONObject;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
}
Result

Related

JSON Parsed Data not showing in ListFragment

I have used a MYSQL Database and connected it to my Android App using PHP. I added a sample row in the table and the PHP Script is returning JSON. I have tried my best in parsing the JSON and displaying it in a list. But it does not seem to be working. Able to run the App - But does not display content - Only shows the Dialog. It seems to work in Case of an Activity - What changes should be made to make it work for a Fragment. Here is my LogCat when I open up the fragment - http://prntscr.com/3f6k0a .
package com.example.socbeta;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class events extends ListFragment {
private ProgressDialog pDialog;
private static final String READ_EVENTS_URL ="http://socapptest.comoj.com/socbeta/events.php";
//JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_EventName = "EventName";
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "ID";
private static final String TAG_DATE = "Date";
private static final String TAG_MESSAGE = "message";
private JSONArray mEvents = null;
private ArrayList<HashMap<String, String>> mEventList;
public events(){}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.events, container, false);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadEvents().execute();
}
public void updateJSONdata() {
mEventList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_EVENTS_URL);
try {
mEvents = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mEvents.length(); i++) {
JSONObject c = mEvents.getJSONObject(i);
String EventName = c.getString(TAG_EventName);
String content = c.getString(TAG_MESSAGE);
String Date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EventName, EventName);
map.put(TAG_MESSAGE, content);
map.put(TAG_DATE, Date);
mEventList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(getActivity(), mEventList,
R.layout.list_item,
new String[] { TAG_EventName, TAG_MESSAGE,TAG_DATE },
new int[] { R.id.eventname, R.id.message,R.id.date });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
});
}
public class LoadEvents extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
EDIT :
Got my code to work. The Problem was with the JSON Structure. I did not Navigate properly and this gave me a "No Value for message" Error. For others who might be having same issues - Remember that when you have { in your JSON , you use JSONArray and when you have [ you use JSONObject. You need to navigate module wise through your JSON.
try this code
pass json string to this method . it will work
public JSONObject getJSONfromURL(String url)
{
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget= new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}

Android Reverse Geocoding no text displays in TextView

My current objective is to parse the Google Map API to return information about certain coordinates.
The main issue I am having is that I cannot get anything to display when I run the program. The code given below will run without any errors stopping the program, but will simply come up with a blank TextView. I am not very familiar with JSON parsing (this being the first program I've ever worked on with it) and I was wondering what was missing that was preventing the returned information to display on a TextView.
Is there a specific way to get the text to appear when parsing through JSON? I appreciate all the help.
My MainActivity.java class:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.widget.TextView;
public class MainActivity extends Activity {
// URL to make the request to
private static String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.1031,-75.1522&sensor=true";
// JSON Node names
private static final String TAG_LOCATION = "results";
private static final String TAG_CITY = "long_name";
// The JSON Array
JSONArray location = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Location
location = json.getJSONArray(TAG_LOCATION);
// looping through each part of location
for(int i = 0; i < location.length(); i++){
JSONObject c = location.getJSONObject(i);
// Storing each JSON item in a variable
String city = c.getString(TAG_CITY);
// For whichever one works
System.out.println(city);
TextView textView = (TextView) findViewById(R.id.textView1);
textView.setText("City: " + city);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
My JSONParser.java class:
package com.example.finalproject;
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.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
long_name key is in JSONObject which is in address_components JSONArray instead of JSONObject which is in results JSONArray so you should need to first get JSONArray from c JSONObject as:
for(int i = 0; i < location.length(); i++){
JSONObject c = location.getJSONObject(i);
// get address_components JSONArray from c
JSONArray add_array=c.getJSONArray("address_components");
for(int j = 0; j < add_array.length(); j++){
JSONObject obj_add = add_array.getJSONObject(i);
// Storing each JSON item in a variable
String city = c.getString(TAG_CITY);
//your code here....
}
}
and also use AsyncTask for getting data from weservice instead of doing network operations on Main UI Thread.
Here's some example code for using the Android/Google location API
http://developer.android.com/google/play-services/location.html
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
private void reverseGeocode()
{
AsyncTask< LatLng, Integer, List< Address > > task
= new AsyncTask< LatLng, Integer, List< Address > >()
{
#Override
protected List< Address > doInBackground( LatLng... params )
{
LatLng latLng = params[0];
Geocoder geoCoder = new Geocoder(getActivity().getApplicationContext() );
List< Address > matches = null;
try
{
matches = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
}
catch ( IOException e )
{
e.printStackTrace();
}
return matches;
}
#Override
protected void onPostExecute( List< Address > result )
{
if ( result != null && result.size() > 0 )
{
if ( D ) Log.v( TAG, "onPostExecute result size=" + result.size() );
Address bestMatch = (result.isEmpty() ? null : result.get(0));
//showGeocodedAddress( bestMatch );
}
}
};
task.execute( latLng );
}

Unable to save values into sql server database. no error in my code

i have an application that should save values in a sql server database but when i check in my database no data is saved and my code does not show error.please review my code and correct errors accordingly. thank you
feedback.java
package com.IwayAfrica.feedback;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.util.Log;
import android.os.AsyncTask;
import android.content.DialogInterface;
import android.app.AlertDialog;
public class feedback extends Activity
{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputcomment;
RadioGroup sorted;
RadioGroup ambiance;
RadioGroup rooms;
RadioGroup food;
RadioGroup reception;
Button buttonsave;
int success = 0;
String sort = "";
String room = "";
String foods = "";
String amb = "";
String rec = "";
private static String url_register_user = "http://http://localhost/IwayAfrica%20Feedback/processs.php";
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback);
inputcomment = (EditText) findViewById(R.id.comment);
Button buttonsave = (Button) findViewById(R.id.btnsave);
final RadioGroup sorted = (RadioGroup)findViewById(R.id.sorted);
final RadioButton yes1 = (RadioButton)findViewById(R.id.yes1);
final RadioButton no1 = (RadioButton)findViewById(R.id.no1);
final RadioButton par = (RadioButton)findViewById(R.id.par);
final RadioGroup ambiance = (RadioGroup)findViewById(R.id.ambiance);
final RadioButton fast = (RadioButton)findViewById(R.id.fast);
final RadioButton fasten = (RadioButton)findViewById(R.id.fasten);
final RadioButton slow = (RadioButton)findViewById(R.id.slow);
final RadioGroup rooms = (RadioGroup)findViewById(R.id.rooms);
final RadioButton reyes = (RadioButton)findViewById(R.id.reyes);
final RadioButton reno = (RadioButton)findViewById(R.id.reno);
final RadioButton remaybe = (RadioButton)findViewById(R.id.remaybe);
final RadioGroup food = (RadioGroup)findViewById(R.id.food);
final RadioButton fdbest = (RadioButton)findViewById(R.id.fdbest);
final RadioButton fdgood = (RadioButton)findViewById(R.id.fdgood);
final RadioButton fdfair = (RadioButton)findViewById(R.id.fdfair);
final RadioButton fdpoor = (RadioButton)findViewById(R.id.fdpoor);
final RadioGroup reception = (RadioGroup)findViewById(R.id.reception);
final RadioButton rsbest = (RadioButton)findViewById(R.id.rsbest);
final RadioButton rsgood = (RadioButton)findViewById(R.id.rsgood);
final RadioButton rsfair = (RadioButton)findViewById(R.id.rsfair);
final RadioButton rspoor = (RadioButton)findViewById(R.id.rspoor);
Button send = (Button) findViewById(R.id.btnsave);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String comment = inputcomment.getText().toString();
if (sorted.getCheckedRadioButtonId() == yes1.getId())
{
sort = "100";
}
else if (sorted.getCheckedRadioButtonId() == par.getId())
{
sort = "60";
}
else if (sorted.getCheckedRadioButtonId() == no1.getId())
{
sort = "30";
}
if (ambiance.getCheckedRadioButtonId() == fast.getId())
{
amb = "100";
}
else if (ambiance.getCheckedRadioButtonId() == fasten.getId())
{
amb = "60";
}
else if (ambiance.getCheckedRadioButtonId() == slow.getId())
{
amb = "30";
}
if (rooms.getCheckedRadioButtonId() == reyes.getId())
{
room = "100";
}
else if (rooms.getCheckedRadioButtonId() == remaybe.getId())
{
room = "60";
}
else if (rooms.getCheckedRadioButtonId() == reno.getId())
{
room = "30";
}
if (food.getCheckedRadioButtonId() == fdbest.getId())
{
foods = "100";
}
else if (food.getCheckedRadioButtonId() == fdgood.getId())
{
foods = "75";
}
else if (food.getCheckedRadioButtonId() == fdfair.getId())
{
foods = "50";
}
else if (food.getCheckedRadioButtonId() == fdpoor.getId())
{
foods = "25";
}
if (reception.getCheckedRadioButtonId() == rsbest.getId())
{
rec = "100";
}
else if (reception.getCheckedRadioButtonId() == rsgood.getId())
{
rec = "75";
}
else if (reception.getCheckedRadioButtonId() == rsfair.getId())
{
rec = "50";
}
else if (reception.getCheckedRadioButtonId() == rspoor.getId())
{
rec = "25";
}
new RegisterNewUser().execute();
}
});
}
public void gotomain(View v){
Intent intent = new Intent(this, main.class);
startActivity(intent);
}
class RegisterNewUser extends AsyncTask<String, String, String>{
protected String doInBackground(String... args) {
String comment = inputcomment.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("comment", comment));
params.add(new BasicNameValuePair("sort", sort));
params.add(new BasicNameValuePair("amb", amb));
params.add(new BasicNameValuePair("room", room));
params.add(new BasicNameValuePair("rec", rec));
params.add(new BasicNameValuePair("foods", foods));
JSONObject json = jsonParser.makeHttpRequest(url_register_user,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), main.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
}
JSONParser.java
package com.IwayAfrica.feedback;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
processs.php
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['sort']) && isset($_POST['amb']) && isset($_POST['room']) && isset($_POST['foods']) && isset($_POST['rec']) && isset($_POST['comment'])) {
$problem=$_POST['sort'];
$time=$_POST['amb'];
$reccomend=$_POST['room'];
$rate1=$_POST['foods'];
$rate2=$_POST['rec'];
$improve=$_POST['comment'];
// include db connect class
require_once __DIR__ . '/connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO feedback (problem,time,reccomend,rate1,rate2,improve) VALUES('$problem','$time','$reccomend','$rate1','$rate2','$improve')";
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "feedback successfull.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
A couple things come to mind:
1) Check your connect.php file. I would bet that the either the name, password or user of your database is wrong.
2) Check that the table column names and the table name are spelled correctly.
3) Encode the error in your result array so you can read what it is.
$problem=$_POST['sort'];
$time=$_POST['amb'];
$reccomend=$_POST['room'];
$rate1=$_POST['foods'];
$rate2=$_POST['rec'];
$improve=$_POST['comment'];
why you not declare $problem = $_POST['problem'];
for me your file so confusing.
then you must try that php file was success. Try to execute from your browser. if not success,that is something wrong with your php.
for radio button,try this http://nsafaat.wordpress.com/2011/07/27/form-master-entry-data-ke-mysql-server-berbasis-android/.
it's work for me.

JSON parsing error - not parse in google API 4.1 jelly bean

i am working on an app using json parsing...in this parsing is done by json of the given url.
As i run my project on emulator having target = "Google APIs (Google Inc.) - API level 10"
then it runs properly and shows needed results from the target url.
but when run my project on emulator having target = "Google APIs (Google Inc.) - API level 16"
then it shows error and it never parse the given url data and get force close.
i want to make app which run on every API level.
please help...
here's my code:
json parser class:
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.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
static String req = "POST";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url, String method) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
if(method == req) {
HttpPost httpC = new HttpPost(url);
httpResponse = httpClient.execute(httpC);
}else {
HttpGet httpC = new HttpGet(url);
httpResponse = httpClient.execute(httpC);
}
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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Another class using json parser class snd fetch data:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class showData extends ListActivity{
public static String url = "http://something/something/";
public static final String TAG_A = "a";
public static final String TAG_B = "b";
public static final String TAG_C = "c";
public static final String TAG_D = "d";
public static final String TAG_E = "e";
public static final String TAG_F = "f";
public static final String GET = "get";
JSONArray Data1 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
EditText editext_text = (EditText) findViewById(R.id.et);
String urlnew = url + editext_text.getText().toString();
Log.d("url", urlnew);
JSONParser jParser = new JSONParser();
// getting JSON string from URL
area1 = jParser.getJSONFromUrl(urlnew, GET);
Log.d("Json String", area1.toString());
try {
for(int i = 0; i < area1.length(); i++){
JSONObject c = area1.getJSONObject(i);
// Storing each json item in variable
String a = c.getString(TAG_A);
String b = c.getString(TAG_B);
String c = c.getString(TAG_C);
String d = c.getString(TAG_D);
String e = c.getString(TAG_E);
HashMap<String,String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_A, a);
map.put(TAG_B, b);
map.put(TAG_C, c);
map.put(TAG_D, d);
map.put(TAG_E, e);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item_area,
new String[] { TAG_B, TAG_A, TAG_C, TAG_D, TAG_E }, new int[] {
R.id.b, R.id.a, R.id.c, R.id.d, R.id.e });
setListAdapter(adapter);
}
}
You are getting a NetworkOnMainThreadException because as the name is self-explaining, you are doing network request on UI Thread that will make your application laggy and create an horrible experience.
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or
higher. Applications targeting earlier SDK versions are allowed to do
networking on their main event loop threads, but it's heavily
discouraged. See the document Designing for Responsiveness.
You should use Threads or AsyncTask, do you need some explanations on how to use them?
private class NetworkTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//DO YOUR STUFF
}
#Override
protected void onPostExecute(String result) {
//Update UI
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
This is Network On Main Thread Exception, You have to use Thread for network connection, because the main thread is UI thread will not give any response for Network connection. Use separate thread for network connection

JSON parser app dying

Here's the main activity:
package com.example.elecimp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
private static EditText jsonView;
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
jsonView = (EditText) findViewById (R.id.editText1);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
jsonView.setText(TAG_NAME);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and here's my JSONParser.java class used to parse the JSON from JSON url source:
package com.example.elecimp;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have already declared the needed permission in my app that is
and everyother stuff seems fine, BUT THE APP CRASHES !??
HERE you will find the LOGCAT >> winacro.com/AndroidLOGCAT/jsonParser.txt
You are calling getJSONFromUrl from the onCreate() which means you are trying to perform network operation in UI thread. On Android >= 3.x this will throw NetworkOnMainThreadException. Use AsyncTask or separate thread to execute getJSONFromUrl

Categories

Resources