Getting JSON file from localhost using ServiceHandler and AsyncTask - android

I have added a questions.json file to www folder and I'm trying to retrieve it.
problem is the response always returns null I'm guessing the exception is at httpClient.execute(httpGet); , not sure though
#SuppressLint("NewApi")
public class QuestionListFragment extends android.app.ListFragment
{
private ProgressDialog pDialog;
// url to make request
private static String url = "http://localhost/questions.json";
// JSON Node names
private static final String TAG_QUESTIONS = "Questions";
private static final String TAG_ID = "Question_Id";
private static final String TAG_BODY = "QuestionBody";
private static final String TAG_TITLE = "QuestionTitle";
private static final String TAG_NAME = "Asker_Name";
private static final String TAG_TIME = "Created At";
private static final String TAG_ANSWERS = "Answers";
private static final String TAG_ANSWER = "answer";
private static final String TAG_A_NAME = "Name";
private static final String TAG_RATING = "Rating";
// questions JSONArray
JSONArray questions = null;
ListView lv;
Context c;
JSONObject obj ;
ArrayList<HashMap<String, String>> questionsList = new ArrayList<HashMap<String, String>>();
#Override
public View onCreateView( LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState )
{
View view = inflater.inflate(ask.code.R.layout.questions_list_frag, container, false);
new GetQuestions().execute();
return view;
}
private class GetQuestions extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_QUESTIONS);
// looping through All Questions
for(int i = 0; i < questions.length(); i++){
JSONObject c = questions.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String body = c.getString(TAG_BODY);
String name = c.getString(TAG_NAME);
String time = c.getString(TAG_TIME);
JSONObject answers = c.getJSONObject(TAG_ANSWERS);
String answer = answers.getString(TAG_ANSWER);
String a_name = answers.getString(TAG_A_NAME);
String a_rating = answers.getString(TAG_RATING);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_TITLE, title);
map.put(TAG_BODY, body);
// adding HashList to ArrayList
questionsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(),
questionsList,
ask.code.R.layout.question_item,
new String[] {
TAG_NAME,
TAG_TITLE,
TAG_TIME},
new int[] {
ask.code.R.id.asker_name,
ask.code.R.id.question_title,
ask.code.R.id.question_rating});
setListAdapter(adapter);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
// TODO Auto-generated method stub
}
ServiceHandler
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
questions.json
{
"Questions": [
{
"CreatedAt": "2013-07-31T09: 57: 34.618Z",
"Asker_Name": "Cloyd",
"QuestionTitle": "temporadoloremquevoluptatemestquisquamundevoluptatemsuntearum\nsitfugaducimusnequeomnisin\npariaturminusdebitisquaeratrerumnamvelitveritatisrem",
"QuestionBody": "voluptatemtemporadignissimosanimivelitdelectusconsequaturcumquedeserunt\nillumaperiamquisminimaeumremveniam\nutnumquamdoloremconsequaturvoluptatemofficiaveniam\nutarchitectoiddelenitiuteiuscumpossimus\ndolorumprovidentmollitianullarerum\n\r\tquiainarchitectodebitislaboreerror\nvoluptatibussitquaeratdoloreassumendadoloremdoloresconsectetur\nsedetevenietsaepeconsequaturvelarchitecto\n\r\tdolorumvoluptatemquaevoluptatebeatae\ndoloremqueutofficiisquibusdamiustopariaturiureautdolorem\nidquialiquideosvelet",
"Question_Id": 0,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1997-08-05T20: 13: 37.888Z",
"Asker_Name": "Alexander",
"QuestionTitle": "fugaetnequequoettemporibus\natvoluptatumessesit\nnullaadipisciquaeducimus",
"QuestionBody": "quiainciduntetquoserror\ncumqueetautsitidexcepturiaccusantiumpariaturconsequatur\nlaudantiummaioressedillomagniexplicabo\nindolorprovidentvoluptasearumdelenitidelectusmollitia\n\r\tsapienteinnemo\nexpeditaautinnon\nprovidentabveniamut\n\r\tenimducimussuntrerumnamsed\nsaepepraesentiumaliquamverolaborumdeseruntidex\nautsedvelittemporibusexplicaboveniamvoluptatemin\nisteetutnobisprovidentasperiores\nexpeditaitaqueullam",
"Question_Id": 1,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1990-02-16T06: 37: 46.327Z",
"Asker_Name": "Kade",
"QuestionTitle": "nisidelectusasperioresveletidtempore\nrationeautautet\neaquenisiestrerumodioasperiorescupiditate",
"QuestionBody": "exrepellendusliberoeosautemetdictaautemsed\nabconsequaturetsitvoluptatemassumendavelitsint\nautconsequaturveniamodioquodoloremdolorem\neligendirerumexplicaboquiquiadolorem\n\r\tminusvoluptatemnamvelcupiditateaperiamsedrerumearum\nautrepudiandaeeavelsitreprehenderiteterrorfugiat\nsedeaquidemveritatisiure\n\r\tdoloremqueidsuntatquiacorruptimolestiaeexpeditavoluptate\nnontemporevelitestrepellendus\nessequaeinsit\nporronihilfacereautnecessitatibusquosunt\natlaborumatemporaullam",
"Question_Id": 2,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1987-02-28T20: 39: 36.422Z",
"Asker_Name": "Madaline",
"QuestionTitle": "omnisnesciuntexcepturieligendirerumquam\netmolestiasfugiatremvoluptasvelitautet\nsedoccaecatidelectuseoset",
"QuestionBody": "inciduntquosbeataevoluptasidcommodideseruntexvero\netitaquemollitialaborumnemosedvoluptatibusperferendisdoloremque\nestsuscipitnonveniamutquaeaperiam\nveroetquiaautillo\nasperioressimiliquetempora\n\r\tvoluptatemaccusantiumconsequunturetconsequaturrepellataut\naspernaturnesciunteavoluptasnatusmaxime\nmaioresatconsequaturnequereiciendis\nadipiscienimrationeipsummagnamveniamsed\n\r\treiciendisutundequi\naperiamcorporisnesciuntid\nculpaetreprehenderittemporibusofficiaplaceataccusantiumcum\nquassitmaioresdelectusesse\nconsequaturtotamdolor",
"Question_Id": 3,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1991-11-22T12: 50: 21.965Z",
"Asker_Name": "Lizzie",
"QuestionTitle": "quiaremnatus\nnatusofficiisquamomnisquifuga\nquiasitavoluptatem",
"QuestionBody": "quisvoluptasquilaborumsednostrumfugaea\nipsumquaeratveritatis\nporrouterrorex\nauteiusexplicabononfugaadutvoluptatumnihil\nabnoninarchitectocommodiminusquasanimi\n\r\tenimdebitisbeataemollitiadoloresiureiustoquia\ncommodiquiapossimusatemporibus\nidutnobisvoluptatumfugaaccusamusharum\netdictaquiamollitiaaccusamuspossimusvoluptatibusautalias\nautemdoloremnamaliquam\n\r\tsitdeseruntautestexcepturiquasi\nquibusdamevenietexcepturiducimusquosdicta\nearumsitenimautquisquamaliquam\nmagnamnesciuntinciduntvelitarchitectoomnis\nomnisminimaerrorfuga",
"Question_Id": 4,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "1987-05-09T15: 46: 08.048Z",
"Asker_Name": "Colleen",
"QuestionTitle": "rerumetaccusamussedabdolorenonest\nestperspiciatisquisedsintmolestiaeautcorporisomnis\nperferendisvelenim",
"QuestionBody": "iustomolestiasrerummollitiafacilisatquecumque\neumquaeatqueaspernaturadoloresestomnis\ndolornihilexcepturinecessitatibus\n\r\tidveniamevenietquifugiat\nreprehenderiterrornumquamautetquiquiarerum\ndolorummaximequasicorporismodiin\neosnostrumutsapientedoloremque\nquaeratconsequunturveniamperferendisautnisidoloresnonest\n\r\tquisuscipitadconsequaturrepellatvoluptatemmollitia\nquidemverocum\nmodidelenitivoluptasadipisciodio",
"Question_Id": 5,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
},
{
"CreatedAt": "2002-05-04T05: 31: 45.704Z",
"Asker_Name": "Carlotta",
"QuestionTitle": "impeditquodillumconsequunturlabore\nsitundeblanditiisitaqueiustoutcorporisut\ndeseruntquasquam",
"QuestionBody": "illumevenietdolor\ndoloribusdistinctiorerumvoluptatumquibusdamest\ndoloremquevoluptassitautemeos\nexcepturiquieasuntverodictaatque\n\r\tisteullamut\nanimivoluptasautdoloresoccaecatiuttenetur\neaimpeditautaquispossimusperspiciatisestaccusantium\nutconsequaturminimabeataemolestiae\ndoloresdolorethic\n\r\tquisquamquidempariaturassumendalaborumveritatisquasdolore\ncommodiquaedebitisipsafugitcorporissitharumquam\nvoluptasbeataeeaetetutaperiam\naiurenihilnamnonaut\ndoloresprovidenthicetveroautmagnimaximelabore",
"Question_Id": 6,
"Answers": {
"Answer": "temporakdjd",
"Name": "saleem",
"Rating": "10"
}
}
]
}

You are trying to connect to the server by specifying localhost as the address of the system hosting the service. The Android emulator runs inside a Virtual Machine (QEMU). Hence, localhost would be the emulator's own loop back address, and not that of the system.
So, you can either go to CommandPrompt in your Windows to get the IP address of your system or just use http://10.0.2.2:8080/... instead of using localhost.
private static String url = "http://10.0.2.2:8080/questions.json";

if you are using emulator then you have to write 10.0.2.2 in place of localhost.
if you are using your device then you have to connect to same network and have to replace localhost with your computer ip address.
i hope this will help

public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
StringBuilder result = new StringBuilder();
try {
//URL urlObj = new URL(url);
URL urlObj = new URL(url.replace(" ","%20"));
urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}

this might help:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
HttpURLConnection urlConnection;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
StringBuilder result = new StringBuilder();
try {
//URL urlObj = new URL(url);
URL urlObj = new URL(url.replace(" ","%20"));
urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
}

Related

Android Json unicode parsin

my sql server collation is utf8 unicode
my php works fine
my android project is working fine with normal characters but in case of arabic char it display error "Error parsing json" line 233 in the activity listed below
I've tried my sql and php on other project its works but here I dont know whats the error json must be utf8 by defult
public class DealsListActivity extends Activity {
private String id;
// Progress Dialog
private ProgressDialog pDialog;
// creating JSON Parser object
JSONParser jParser = new JSONParser();
private static String url = "http://xxxxxxxxxxxx.get_all_deals_by_id.php";
// JSON Node names
private static final String TAG_DEALS = "deals";
private static final String TAG_ID = "id";
private static final String TAG_DEALNAME = "dealName";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_RESTID = "restID";
private static final String TAG_RESTNAME = "restName";
private static final String TAG_RESTTYPE = "restType";
private static final String TAG_LAT = "restLat";
private static final String TAG_LNG = "restLng";
private static final String TAG_SUCCESS = "success";
private JSONObject json;
JSONArray restaurantDealsData = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> restaurantDealsList = new ArrayList<HashMap<String, String>>();
ListView myList;
private String[] dealID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deals_list);
id = getIntent().getStringExtra("id");
myList = (ListView) findViewById(R.id. restDealListView);
new LoadDeals().execute();
}
/**
* Background Async Task to Load all deals by making
* HTTP Request
* */
class LoadDeals extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DealsListActivity.this);
pDialog.setMessage("Loading Restaurant Deals. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
Log.v("id", id);
params.add(new BasicNameValuePair("id", id));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
// check log cat for JSON string from URL
Log.v("restaurantDealsJSON: ", json.toString());
// return json as string to using in the user interface
return json.toString();
}
#Override
protected void onPostExecute(final String jsonStr) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
/**
* Updating parsed JSON data into listview
* */
try {
json = new JSONObject(jsonStr);
} catch (JSONException e1) {
// print error message to log
e1.printStackTrace();
error("There are no Deals");
}
try {
// Checking for SUCCES TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// restaurant found
// Getting Array of restaurant
restaurantDealsData = json.getJSONArray(TAG_DEALS);
displayDeals(restaurantDealsData.toString());
} else {
error("There is no Deals available!");
}
} catch (JSONException e) {
error("There has been an error please try again!");
e.printStackTrace();
}
}
});
}
}
public void error(String error) {
// Log.v("ERROR", "2");
AlertDialog.Builder builder = new AlertDialog.Builder(
DealsListActivity.this);
// Log.v("ERROR", "3");
builder.setTitle("Error");
builder.setMessage(error);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Log.v("TEST", "1");
Intent i = new Intent(getApplicationContext(),
TabsViewPagerFragmentActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void displayDeals(String result) {
JSONArray restaurantDealsData = null;
try {
restaurantDealsList.clear();
restaurantDealsData = new JSONArray(result);
dealID = new String[restaurantDealsData.length()];
// looping through all technical data
for (int i = 0; i < restaurantDealsData.length(); i++) {
JSONObject td = restaurantDealsData.getJSONObject(i);
// Storing each json item in variable
String id = td.getString(TAG_ID);
dealID[i] = id;
String name = td.getString(TAG_DEALNAME);
String price = td.getString(TAG_PRICE);
String description = td.getString(TAG_DESCRIPTION);
String restaurantID = td.getString(TAG_RESTID);
String restaurantName = td.getString(TAG_RESTNAME);
String restaurantType = td.getString(TAG_RESTTYPE);
String lat = td.getString(TAG_LAT);
String lng = td.getString(TAG_LNG);
Log.v("lat", lat);
Log.v("lng", lng);
// Creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_DEALNAME, name);
map.put(TAG_PRICE, price);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_RESTID, restaurantID);
map.put(TAG_RESTNAME, restaurantName);
map.put(TAG_RESTTYPE, restaurantType);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
// adding HashMap to ArrayList
restaurantDealsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
error("Error parsing json");
}
// add to list view
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
restaurantDealsList, R.layout.deals_list_item, new String[] {
TAG_DEALNAME, TAG_RESTNAME, TAG_RESTTYPE }, new int[] {
R.id.dealName, R.id.restaurantName, R.id.type });
// updating listview
myList.setAdapter(adapter);
//handling user click list item
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//start the next activity - Restaurant Details
Intent i = new Intent(getApplicationContext(), DealDetails.class);
i.putExtra("ID", dealID[arg2]);
startActivity(i);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
}
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;
}
}
You should read the input stream using the charset UTF-8 like this:
replace
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
by
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8));
I use this to decode json with japanese inside.

Show data from world weather online api

I am developing weather application by using world weather online API
for android.How i show data in application? data is showing in logcat.Following is my code.
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// adding contact to contact list
dataList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
}
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
First of all, this format will refer to the V1 free version. World Weather Online has released v2, which is superior. I was in the process of updating and saw this question sitting out there so I'll answer based off of what I had that did work.
You are on the right track to use the AsyncTask, here is my call to AsyncTask. You should know I use my "DataPoint" class to simply contain the data from WWO that I need to use. Based on your question, you can show the data that I will put in the DataPoint object in anyway you see fit on the screen, since at the end of the queryWeatherService(), you will end up with a parsed set of data.
//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{
// This method will retrieve the data from the weather service
DataPoint newDataPoint = new DataPoint();
if (!waiting)
{
try{
newDataPoint = new WeatherServiceClass().execute(
String.valueOf(getlatitude()), //Not shown here: pass in some String of a float value of of your lat coordinate.
String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
.get();
} catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
return newDataPoint;
// Documentation:
// https://developer.worldweatheronline.com/page/documentation
}
The WeatherServiceClass that extends the AsyncTask
public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
private String latitude;
private String longitude;
public WeatherServiceClass() {
}
#Override
protected DataPoint doInBackground(String... params) {
DataPoint dp = new DataPoint();
JSONWeatherParser jparser = new JSONWeatherParser();
latitude = params[0];
longitude = params[1];
String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
try {
dp = jparser.getWeather(data);
} catch (JSONException e) {
e.printStackTrace();
}
return dp;
//Reference:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
}
}
Here is the WeatherHttpClient class:
public class WeatherHttpClient {
private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";
public String getWeatherData(String latitude, String longitude){
HttpURLConnection con = null;
InputStream is=null;
try{
con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//Reading the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line=br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close();} catch(Throwable t){}
try { con.disconnect();} catch(Throwable t){}
}
return null;
}
Finally, here is my JSONWeatherParser:
public class JSONWeatherParser {
public JSONWeatherParser() {
}
public DataPoint getWeather(String data) throws JSONException {
DataPoint dp = new DataPoint();
Weather weather = new Weather(); //This is just a class that has a bunch of strings in it for the weather info.
JSONObject jObj = new JSONObject(data);
//Parsing JSON data
JSONObject dObj = jObj.getJSONObject("data");
JSONArray cArr = dObj.getJSONArray("current_condition");
JSONObject JSONCurrent = cArr.getJSONObject(0);
weather.setCurrent_temp(getString("temp_F",JSONCurrent));
weather.setHour(getString("observation_time",JSONCurrent));
JSONArray jArr = dObj.getJSONArray("weather");
JSONObject JSONWeather = jArr.getJSONObject(0);
JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
JSONObject JSONIcon = jArrIcon.getJSONObject(0);
weather.setDate(getString("date",JSONWeather));
weather.setPrecipmm(getString("precipMM",JSONWeather));
weather.setTempMaxc(getString("tempMaxC",JSONWeather));
weather.setTempMaxf(getString("tempMaxF",JSONWeather));
weather.setTempMinf(getString("tempMinF",JSONWeather));
weather.setTempMinc(getString("tempMinC",JSONWeather));
weather.setWeatherCode(getString("weatherCode",JSONWeather));
weather.setWeatherIconURL(getString("value",JSONIcon));
weather.setWinddir16point(getString("winddir16Point",JSONWeather));
weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
// For details of these operations and how each works go here:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
return dp;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
}

Create progress dialog in TimerTask

I need to create a Progress Dialog on this Class. I am trying to make it to show, while all method is done. Is it possible ? Maybe somebody more experianced has faced this problem ? Is it possible to do that in this Class, or i need to do it when im calling this method from other activity ??:
public class Data_synch extends TimerTask {
private Context mContext;
String FormsString;
DatabaseDataHandler db;
static String realLink;
String url = "/android/sync";
User user;
ProgressDialog pd;
protected static final int DIALOG_OK= 0;
ProgressDialog timeBar;
public Data_synch(String realLin, Context context, User user) {
mContext = context;
this.user = user;
// realLink = ((Link_holder)
// mContext.getApplicationContext()).getLink();
realLink = realLin;
url = realLink + url;
// pd = ProgressDialog.show(mContext, "", "Uploading photos", false);
}
#Override
public void run() {
new HttpAsyncTask().execute(url);
// /* sync from sever */
new SyncFromServer(realLink, true, false, false, false,false, user, mContext);
new SyncFromServer(realLink, false, true, false, false,false, user, mContext);
new SyncFromServer(realLink, false, false, true, false, false,user, mContext);
new SyncFromServer(realLink, false, false, false, true, false,user, mContext);
new SyncFromServer(realLink, false, false, false, false, true,user, mContext);
try {
new SyncPhotos(realLink, user, mContext);
} catch (final Exception e) {
System.out.println("SAKIU RAJONAS");
e.printStackTrace();
}
}
public String POST(String x) {
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
// System.out.println("x == " + x);
nameValuePairs
.add(new BasicNameValuePair("email", user.getEmail()));
nameValuePairs.add(new BasicNameValuePair("password", user
.getPassword()));
nameValuePairs.add(new BasicNameValuePair("prefix", user
.getPrefix()));
nameValuePairs.add(new BasicNameValuePair("sync_data", x));
// System.out.println(nameValuePairs);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse httpResponse = httpclient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
} else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", "FAIL");
}
return result;
}
public static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
// System.out.println("result is " + result);
inputStream.close();
return result;
}
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
JSONObject json;
final String is_synch = "1";
String synch;
String damn;
JSONArray JsonObjectsArray = new JSONArray();
public String getdamn() {
return damn;
}
protected String doInBackground(String... urls) {
String log = "nothing";
db = new DatabaseDataHandler(mContext);
List<Data> datas = db.getAllData();
int nr_of_data = 0;
for (Data cn : datas) {
log = cn.getJson();
// synch = cn.getSynch();
// System.out.println(synch);
// if(synch = "0")
// System.out.println(synch);
// if(synch == "0"){
// cn.setSynch("1");
try {
json = new JSONObject(log);
add_JsonObject_to_JSONArray(createJsonObjectString(json, cn));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nr_of_data++;
}
db.close();
System.out
.println("WAWAWYWAWAWAWYWAWAWAWYWAWAWAWYWAWAWAWYWAWAWAWYWA");
damn = JsonObjectsArray.toString();
return POST(damn);
}
// private JSONArray PostJsonArray(JSONArray x){
// JsonObjectsArray = ;
//
// return x;
// }
//
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
System.out.println(result);
}
private JSONArray add_JsonObject_to_JSONArray(JSONObject jsonobject) {
JsonObjectsArray.put(jsonobject);
return JsonObjectsArray;
}
private JSONObject createJsonObjectString(JSONObject jsonobject, Data cn)
throws JSONException {
String comment = "";
jsonobject.put("comment", comment);
// System.out.println("xxxx : "+ jsonobject);
return jsonobject;
}
}
}

How to eliminate the empty strings inside the object in android json parsing

Hi friends i like to parse the json from url and also like to elimate the null values field and only show the object which has value if anyone known syntax for that means please guide me thanks in advance.
JSON Structure
{
"daftar_rs": [
{
"Name": "exe1",
"URL": "http://samir-mangroliya.blogspot.in/p/android-json-parsing-tutorial.html"
},
{
"Name": "exe2",
"URL": "https://code.google.com/p/json-io/"
},
{
"Name": "exe3",
"URL": ""
},
{
"Name": "exe4",
"URL": "http://stackoverflow.com/questions/10964203/android-removing-jsonobject"
},
{
"Name": "exe5",
"URL": ""
},
{
"Name": "exe6",
"URL": ""
}
],
"success": 1
}
MainActivity
public class MainActivity extends Activity {
ListView lv;
List<String> titleCollection = new ArrayList<String>();
List<String> urlCollection = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String linkUrl = urlCollection.get(arg2);
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
});
}
public void loadContents()
{
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,titleCollection);
lv.setAdapter(adapter);
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://192.168.1.167/vinandrophp/vinex.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
loadContents();
}
}
}
JsonParser.java
public class JsonParser {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
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(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Just check it inside your code.
String linkUrl = urlCollection.get(arg2);
if (linkUrl== null || linkUrl.equals("")){
// null
}
else{
// not null so put to extras and start intent
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
try below code
for (int i = 0; i < dataJsonArr.length(); i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String Name = c.getString("Name");
String Url = c.getString("URL")
if(!TextUtils.isEmpty(Name) && !TextUtil.isEmpty(Url))
{
titleCollection.add(Name);
urlCollection.add(Url));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection + ", URL: " + urlCollection);
}
try below code:-
if(c.getString("URL").equals("") || c.isNULL("URL"))
{
// do nothing
}
else
{
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
Change for loop as
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String name = c.getString("Name");
String url = c.getString("URL");
if(name != null && !(name.equals(""))
&& url != null && !(url.equals(""){
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
Try replace keys and values with regular expression if the key is empty in the JsonParser class.
json=json.replaceAll("\\n",""); //you should do not have any new lines after commas
json=json.replaceAll(",\\W*\"\\w+\":\\W?(\"\"|null)","");

how to parse this json data ? and store it directly in database and then display it in listview [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
//This my__json__data
json ////This is main json object
{
"cityMasterEntity":
--This is array
[
{
"CityId": 1,
"CityName": "Ahmedabad",
"CreatedDate": "\/Date(1373091319697+0530)\/",
"IsActive": true,
"StateId": 6,
"StateName": "Gujarat\u000d\u000a",
"UpdatedDate": null
},
{
"CityId": 3,
"CityName": "Rajkot",
"CreatedDate": "\/Date(1373091319697+0530)\/",
"IsActive": true,
"StateId": 6,
"StateName": "Gujarat\u000d\u000a",
"UpdatedDate": null
},
{
"CityId": 2,
"CityName": "Surat",
"CreatedDate": "\/Date(1373091319697+0530)\/",
"IsActive": true,
"StateId": 6,
"StateName": "Gujarat\u000d\u000a",
"UpdatedDate": null
}`enter code here`
]
}
{ // json object node
"cityMasterEntity":[ // json array
{ // json object node
"CityId": 1
To parse
JSONObject jb = new JSONObject("yourString");
JSONArray city = jb.getJSONArray("cityMasterEntity");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 =(JSONObject) city.getJSONObject(i);
int id = jb1.getInt("CityId");
String name = jb1.getString("CityName");
...// similarl for name and others
}
To store it in database you can use sqlite. To display you ca use a listview.
Edit:
class TheTask extends AsyncTask<Void,Void,String>
{
#Override
protected String doInBackground(Void... arg0) {
String _response= null;
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://www.clubrummy.in/MobileWCF/RummyService/GetMasterDetail");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i(".......",_response);
}catch(Exception e)
{
}
return _response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result!=null)
{
try
{
JSONObject jb = new JSONObject(result);
JSONArray city = jb.getJSONArray("cityMasterEntity");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 =(JSONObject) city.getJSONObject(i);
int id = jb1.getInt("CityId");
String name = jb1.getString("CityName");
Log.i("Name is",""+name);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Edit 2:
In fact you can parse json store data in database in doInbackground itself. Update ui in onPostExecute
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... arg0) {
String _response= null;
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://www.clubrummy.in/MobileWCF/RummyService/GetMasterDetail");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i(".......",_response);
if(_response!=null)
{
JSONObject jb = new JSONObject(_response);
JSONArray city = jb.getJSONArray("cityMasterEntity");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 =(JSONObject) city.getJSONObject(i);
int id = jb1.getInt("CityId");
String name = jb1.getString("CityName");
Log.i("Name is",""+name);
}
}
}catch(Exception e)
{
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
Also if loading data from database takes time use loaders.

Categories

Resources