Here is my JSON link, and how it looks:
{
"to": "CAD",
"rate": 1.0223997600000001,
"from": "USD",
"v": 5.1119988000000003
}
I tried this syntax:
JSONObject o = new JSONObject(sourceString);
String from = o.getString("from");
but it didn't work.
You can create a class
public class Abc {
String to;
String rate;
String from;
String v;
}
and then can use below code for parsing
JsonObject obj= gson.fromJson(DATA,Abc.class);
Where DATA will be your gson string.
Are you running it on simulator?
Or if you are ruuning it on device then off and on your internet connection,it will work.
hello Check this Code it give you result in log(error)
protected void getJSONFromURL(String string) {
// TODO Auto-generated method stub
string = "http://rate-exchange.appspot.com/currency?from=USD&to=CAD&q=5";
String is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet Get = new HttpGet(string);
HttpResponse responce = httpclient.execute(Get);
HttpEntity entity = responce.getEntity();
is = EntityUtils.toString(entity, "UTF-8");
Log.e("responce-->", "" + is.toString());
if (!is.toString().equalsIgnoreCase("")) {
JSONObject ob = new JSONObject(is.toString());
String to = ob.getString("to");
Log.e("to", "" + to);
String from = ob.getString("from");
Log.e("from", "" + from);
double rate = ob.getDouble("rate");
Log.e("rate", "" + rate);
double v = ob.getDouble("v");
Log.e("v", "" + v);
}
} catch (Exception e) {
// TODO: handle exception
Log.d("call http :", e.getMessage().toString());
is = null;
}
}
if you are yseing above 3.0 OS then also include this code;
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT>8){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Your Result is over here:
03-19 11:23:22.745: E/responce-->(811): {"to": "CAD", "rate": 1.0220998400000001, "from": "USD", "v": 5.1104992000000005}
03-19 11:23:22.745: E/to(811): CAD
03-19 11:23:22.776: E/from(811): USD
03-19 11:23:22.776: E/rate(811): 1.02209984
03-19 11:23:22.791: E/v(811): 5.1104992000000005
Related
I am trying to post some data form android app to Laravel rest api. The data is converted and posted as jsonArray.
The code works fine in HttpRequester (Firefox extension) but throws 500 Internal Server Error when posted from Android.
Android
public static int check(String token) throws IOException
{
int flag;
String response=Constants.EMPTY_STRING;
URL mUrl=null;
HttpURLConnection mConnection=null;
String message="";
JSONObject myObject1 = new JSONObject();
JSONObject myObject2 = new JSONObject();
JSONObject myObject3 = new JSONObject();
JSONArray myArray = new JSONArray();
JSONObject mySentObject = new JSONObject();
try {
myObject1.put("id","01");
myObject1.put("name","Ali Jibran");
myObject1.put("date","2016-04-01");
myArray.put(myObject1);
myObject2.put("id","02");
myObject2.put("name","Imran Raja");
myObject2.put("date","2016-05-03");
myArray.put(myObject2);
myObject3.put("id","03");
myObject3.put("name","M.Quddus Raja");
myObject3.put("date","2015-06-01");
myArray.put(myObject3);
//mySentObject.put("data",myArray.toString());
//message = mySentObject.toString();
message = myArray.toString();
} catch (JSONException e) {
e.printStackTrace();
}
//String mQuery = Constants.APP_TOKEN_KEY
// + Constants.EQUALS + token + Constants.AMPERSAND + "posted=" + message;
String mQuery = "posted=" + message;
Log.d(Constants.APP_TAG,"================== Checking =================" );
Log.d(Constants.APP_TAG, "check -> Query is : " + mQuery);
mUrl = new URL(Constants.APP_URL + "info?" + mQuery);
mConnection = (HttpURLConnection) mUrl.openConnection();
mConnection.setDoInput(true);
mConnection.setDoOutput(true);
//mConnection.setFixedLengthStreamingMode(message.getBytes().length);
mConnection.setConnectTimeout(5000);
mConnection.setInstanceFollowRedirects(false);
mConnection.setRequestMethod(Constants.POST);
mConnection.setRequestProperty("Content-type", "application/json");
mConnection.setRequestProperty("charset", "utf-8");
//Write Post Data
DataOutputStream wr = new DataOutputStream(mConnection.getOutputStream());
wr.writeUTF(message.getBytes().toString());
wr.flush();
wr.close();
flag = mConnection.getResponseCode();
if (flag != 200) {
Log.d(Constants.APP_TAG,"Failure " + flag + " " + mConnection.getResponseMessage());
}
if (flag == 200){
response = readData(mConnection);
try
{
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("reply"))
Log.d(Constants.APP_TAG,"Reply received -> " + jsonObject.getString("reply"));
if(jsonObject.has("newmercs"))
Log.d(Constants.APP_TAG,"Data received -> " + jsonObject.getString("newmercs"));
if(jsonObject.has("count"))
Log.d(Constants.APP_TAG,"Count received -> " + jsonObject.getString("count"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
return flag;
}
Laravel 5.0
Route::post('info',function(){
//$newmercs = json_decode(Input::get('posted'),true);
$newmercs = json_decode(Input::get('posted'));
$reply = "";
$count = 0;
foreach ($newmercs as $newmerc){
$count++;
}
if ($count > 0){
$reply = 'Success';
}else {
$reply = 'Failure';
}
return response()->json(compact('newmercs','reply','count'));
});
This is what i should get (HttpRequester also returns the same)
{
"newmercs":
[
{
"date": "2016-04-01",
"id": "01",
"name": "Ali Jibran"
},
{
"date": "2016-05-03",
"id": "02",
"name": "Imran Raja"
},
{
"date": "2015-06-01",
"id": "03",
"name": "M.Quddus Raja"
}
],
"reply": "Success",
"count": 3
}
You can use Retrofit Lib to communicate with your API, it's so much easier.
Retrofit doc : http://square.github.io/retrofit/
Have a great day
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)","");
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();
}
}
Currently I'm working with the Google Books API.
I write a simple request:
public static String request(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
client.getConnectionManager().getSchemeRegistry().register(
new Scheme("SSLSocketFactory", SSLSocketFactory.getSocketFactory(), 443));
HttpGet method = new HttpGet(url);
String data = null;
try
{
BasicHttpResponse response = (BasicHttpResponse) client.execute(method);
data = EntityUtils.toString(response.getEntity());
}
catch (Exception e)
{
System.out.println("IOException in HTTPSRequest.request: " + e.toString());
}
return data;
}
and after that i except a JSonArray:
static final String baseURL = "https://www.googleapis.com/books/v1/volumes?key=" + APIKey + "&q=";
public static String getURL(String searchstring)
{
return baseURL + searchstring;
}
public static JSONObject getJSONObjectFromString(String jsonString)
{
JSONParser parser = new JSONParser();
JSONObject object = null;
try
{
object = (JSONObject) parser.parse(jsonString);
}
catch (Exception e)
{
System.out.println("ParseException in GoogleBooksHelper.getJSONObjectFromString");
}
return object;
}
public static JSONArray getItemsAsJSONArray(String jsonString)
{
JSONObject object = getJSONObjectFromString(jsonString);
JSONArray items = (JSONArray) object.get("items");
return items;
}
But now the Problem, every Time i start a request i get the following:
{"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured"
}
],
"code": 403,
"message": "Access Not Configured"
}
}
But I have no Idea why. In the Api Console I enable the Book api, I have generated a new Api Key with the Project Name.
OK, the Problem for this problem was that i have use the wrong api key, i had it for browser and android, i just copy the key after i test it in the browser. stupid from my side
I have an error while trying to parse json. Can you help me please? I read the json url, but it gives me an exception when I'm trying to parse the json.
The code:
public String lecturaJsonTusPerlas() {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.tvnotas.com.mx/rss/feed/tvn-horoscopo.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
return result;
} catch (Exception e) {
Log.d("DEFEKAS","EXCEPCION");
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
To read json:
JSONArray jsonArray2 = new JSONArray(lecturaJsonTusPerlas);
for (int i = 0; i < jsonArray2.length(); i++) {
JSONObject jsonObject = jsonArray2.getJSONObject(i);
String atr1 = null;
boolean var1 = jsonObject.getBoolean(atr1);
String atr2 = null;
int var2 = jsonObject.getInt(atr2);
String atr4 = null;
String var3 = jsonObject.getString(atr4);
}
I thing that the url is json because when I'm trying to extract with a google chrome extension I dont have any problem.
What you get is a JSONObject
JSONObject jb = new JSONObject(lecturaJsonTusPerlas());
Your json looks like below from the link you have used
{ // jsonobject node
"#attributes": {
"version": "2.0"
},
"channel": {
"title": "TV Notas",
"link": "http://www.tvnotas.com.mx",
"description": "TV Notas - Horoscopos",
"pubDate": "Mon, 23 Sep 2013 2:30:12 -0500",
"generator": "http://www.tvnotas.com.mx",
"language": "es",
"item": [ // json array of item's
{
"title": "Acuario",
"link": "http://usa.tvnotas.com.mx/horoscopo/1-acuario/",
"pubDate": "Mon, 23 Sep 2013 02:30:12 -0500",
"category": "Horoscopo",
"guid": "http://www.tvnotas.com.mx/horoscopo/1-acuario/",
"description": "Si has sido soberbio con tus compañeros de trabajo o empleados, con familiares o amigos y no les has perdonado sus malos momentos, ahora se te presentará la oportunidad de estrechar lazos.",
"enclosure": {
"#attributes": {
"url": "http://www.tvnotas.com.mx/advf/imagenes/2013/01/50fdbd604f653_150x118.jpg",
"length": "3587",
"type": "image/jpeg"
}
},
"elemento": "Aire",
"planeta": "Urano",
"signo_compatible": "Cáncer",
"signo_enemigo": "El excéntrico",
"numero": "25",
"arquetipo": "El Loco Sabio",
"arcangel": "Sakmakrel",
"color": "Verde",
"dia_suerte": "28"
},
....
To parse
try {
JSONObject jb = new JSONObject(lecturaJsonTusPerlas());
JSONObject job = jb.getJSONObject("channel");
String channeltitle= job.getString("title");
String channellink= job.getString("link");
String channeldecription= job.getString("description");
String channeldpubdate= job.getString("pubDate");
String channeldgenerator = job.getString("generator");
String channeldlanguage = job.getString("language");
JSONArray jr = job.getJSONArray("item");
for(int i=0;i<jr.length();i++)
{
JSONObject jb1 = (JSONObject) jr.get(i);
String title = jb1.getString("title");
// similar for title link and others
JSONObject enclosure = jb1.getJSONObject("enclosure");
JSONObject attributes= enclosure.getJSONObject("#attributes");
String url = attributes.getString("url");
Log.i("....",""+title);
String elemento= jb1.getString("elemento");
// similar for others planeta..
}
} catch (Exception e) {
e.printStackTrace();
}
Try this
JSONObject jObject = new JSONObject(lecturaJsonTusPerlas);
JSONArray jsonArray2 = jObject.getJSONArray("your array key");
for (int i = 0; i < jsonArray2.length(); i++) {
JSONObject jsonObject = jsonArray2.getJSONObject(i);
boolean var1 = jsonObject.getBoolean(atr1);
int var2 = jsonObject.getInt(atr2);
String var3 = jsonObject.getString(atr4);
}
don't initialize string values as null.
You might be getting NullPointerException because these lines:
String atr1 = null;
boolean var1 = jsonObject.getBoolean(atr1);
String atr2 = null;
int var2 = jsonObject.getInt(atr2);
String atr4 = null;
String var3 = jsonObject.getString(atr4);
you're trying to parse with "null" reference.
See atr1, atr2 and atr4; these strings are initialized with "null".
The reason you are getting this error is your top node of json element is object not an JSON Array.
So to begin parsing you need to write something like this
JSONObject jObject = new JSONObject(result);