how to fetch json object from url in android - android

I want to fetch json data from json object.
My json data is:{"avg":2.5} and my android code is
public class AsyncTaskParseJson extends AsyncTask < String, String, String > {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name;
// contacts JSONArray
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String...arg0) {
try {
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
JSONObject dataJsonArr = json.getJSONObject(str);
String c = dataJsonArr.getString("avg");
na = c;
starts = Float.parseFloat(c);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
super.onPostExecute(strFromDoInBg);
netRate.setRating(starts);
Toast.makeText(mybookview.this, Float.toString(starts), Toast.LENGTH_SHORT).show();
}
But somehow its not working.I have trie every tutorial and evrything but nothing works.plz help me

your getting the json data in response is as {"avg":2.5}
simple remove the below code
JSONObject dataJsonArr = json.getJSONObject(str);
String c = dataJsonArr.getString("avg");
with below line
String c = json.getString("avg");

this is for simple get data from url example:
Parse JSON from HttpURLConnection object
and if you want use library then try Volley:
tutorial link:
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

A very simple solution to your problem
String str = "{ \"avg\" :0 }";
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(str);
String value = object.get("avg").getAsString();
But first of all you have to correct the warning in your backend.
EDIT the complete solution
public class AsyncTaskParseJson extends AsyncTask < String, String, String > {
HttpURLConnection urlConnection;
#Override
protected String doInBackground(String...args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://www.bsservicess.com/photoUpload/star_avg.php?bookName=" + book_name);
urlConnection = (HttpURLConnection) url.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();
}
#Override
protected void onPostExecute(String result) {
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(result);
String value = object.get("avg").getAsString();
}
}
But first of all remove the warning from the web response!

Related

JSONObject can't be correctly created

I want to get images from server into my Android app.
My first steps are:
I have this JSON string array from server
{"results":"[{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara1.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara2.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara3.jpg\"}]"}
I got urls in my App from server with code below and working fine.
private void getURLs() {
class GetURLs extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(GalleryTargets.this, "Loading...", "Please Wait...", true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(GalleryTargets.this,s,Toast.LENGTH_LONG).show();
imageJSON = s;
Log.e(LOGTAG, "Succeed Read url" + imageJSON);
extractJSON(imageJSON);
}
#Override
protected String doInBackground(String... strings) {
String uri = strings[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json);
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetURLs gu = new GetURLs();
gu.execute(newurl);
}
But, i want to extract json into a new JSON Object with this method below but throws the exception, Json object not created.
Any ideas why this exception happens?
Thank you in advance!
private void extractJSON(String jsonString){
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jArray.length(); i++) {
JSONObject oneObject = jArray.getJSONObject(i);
oneObject.getString("url");//
}
Log.e(LOGTAG, "JsonArray Succeed" );
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOGTAG, "JsonArray exception");
}
}
Instead of JSONArray jArray = jsonObject.getJSONArray("results");
Try JSONArray jArray = new JSONArray (jsonObject.getString("results"));
You're asking for a json array but it is a string.
There is an error on the json.. after "results": there must not be
quotes
This is correct
{"results":[{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara1.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara2.jpg\"},{\"url\":\"https:\\\/\\\/augmentedandroidapp.000webhostapp.com\\\/images\\\/kamara3.jpg\"}]}

is there anything that i don't know about Json in Code

i'm trying to do some work with methods of json in android.
i read the documentation of json and its methods but when i use them,they don't do what i expected they do.
public class getData_jason extends AsyncTask{
String KholaseKQuery;
String User;
public getData_jason(String link,String user) {
KholaseKQuery = link;
User = user;
}
#Override
protected String doInBackground(Object[] params) {
try{
URL mylink = new URL(KholaseKQuery);
URLConnection connect = mylink.openConnection();
BufferedReader read = new BufferedReader(new InputStreamReader(connect.getInputStream()));
StringBuilder sB = new StringBuilder();
String eline;
while((eline = read.readLine())!= null)
{
sB.append(eline);
}
//MainActivity.jason_rs = sB.toString();
MainActivity.result = sB.toString();
MainActivity.is = true;
JSONObject jObj;
try{
jObj = new JSONObject(MainActivity.result.replace("callback(","")).getJSONObject("response");
JSONArray jsonArray = jObj.optJSONArray("Username");
for (int i = 0;i < jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.getBoolean("ali")){
MainActivity.jason_rs = jsonObject.optString("Name");
//MainActivity.jason_rs = jsonObject.getString("Name");
}
}
}catch (Exception e){
}
}catch (Exception e){
/*Any Exception Here*/
}
return "";
}
}
when the process of reading from database is finished,in the result string is:
{"Username":["Name":"ali","Name":"hasan"]},{"Password":["aliali","hasanhasan"]}
so when i want to get ali name from the jsonObject,the value of jason_rs is null.
plz guid me what is that i don't know yet about using json or i do it wrong.
Your "json" is invalid. You can't have the same key more than once in a hash, on the other hand you also can't have keys (certainly not strings) in an array. You can validate it on http://jsonlint.com

android:how to call method from hyperlink

I am trying to click a hyperlink and call method in android programming...
But the problem is , the link is not showing up and neither the method is getting called. How to achieve this result?
I am basically a javascript/jsp developer, this is my first android application , which i am learning. Accordingly i am trying to click link and call method with parameter....
Results looking like
Java code
private class CallAPI extends AsyncTask<String, String, String> {
private String Content;
#Override
protected String doInBackground(String... params) {
String urlString=params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
emailVerificationResult result = null;
// HTTP Get
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
System.out.println("test");
BufferedReader reader = null;
// Get the server response
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception e ) {
System.out.println(e.getMessage());
return e.getMessage();
}
/****************** Start Parse Response JSON Data *************/
String OutputData = "<center><b><u>Weight Training</u></b></center><br/><br/>";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("articleList");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for (int i = 0; i < lengthJsonArr; i++) {
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("menu_name").toString();
String number = jsonChildNode.optString("id").toString();
String date_added = jsonChildNode.optString("parent_id").toString();
OutputData += " " +
String.format("<a onClick='verifyEmail("+number+","+date_added+")'><b>"+name+"<b> "+ number+" "+ date_added+"</a> ") +"<br/><br/>";
}
/****************** End Parse Response JSON Data *************/
/* Show Parsed Output on screen (activity) */
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
resultToDisplay =OutputData ;
return resultToDisplay;
}
// This is the method that is called when the submit button is clicked
public void verifyEmail(String m,String p) {
String urlString = apiURL + "mid=" + m + "&pid=" + p;
new CallAPI().execute(urlString);
}
protected void onPostExecute(String result) {
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra(EXTRA_MESSAGE, result);
startActivity(intent);
}
Update:
Instead of link, can i put a button and provide on click method and pass parameter to the method
(Thankfully) You cannot call a function using HTML tags in android. Instead try setting ClickableSpan on you you TextView to get the desired effect
SpannableString ss = new SpannableString("Click Me to do magic");
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
doSomeMagic();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
}
};
// apply the clickable span on "Click Me" part which is on index 0 -> 7
// 8 is used because it goes from a -> b-1
ss.setSpan(clickableSpan, 0, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView textView = (TextView) findViewById(R.id.foo);
textView.setText(ss);

JSON AsyncTask ( get pictures of the site invisible for the user and very smoothly)

I am new to Android development. In my project I'm trying to get data from a site and show that data in a listview.
I am getting String data with httpGet and I'm parsing it with json and then put the data in adapter to show. However, it doesn't look smooth and it's working very slowly.
I should get 10 initial elements, and then when scrolling down get new 10 elements (but very smoothly).
videoList = new ArrayList<Videos>();
new JSONAsyncTask().execute(
"http://speechyard.com/api/content/?type=videolist&page=1&perPage=10");
ListView listview = (ListView)getView().findViewById(R.id.list);
VideoAdapter(Context context, int resource, ArrayList<Videos> objects)
adapter = new VideoAdapter(getActivity().getApplicationContext(), R.layout.content_row, videoList);
listview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
} #Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem +2> pageNumber*10) {
pageNumber+=1;
Log.d(TAG,pageNumber.toString());
new JSONAsyncTask().execute("http://speechyard.com/api/content/?type=videolist&page="+pageNumber+"&perPage=10");
}}});
}
//*******get data from http
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
//*****set progress dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setCancelable(false);
}
//*************HTTP Get save in String data
#Override
protected Boolean doInBackground(String... urls) {
try {//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
//**********Optimization String data for JSON parsing
String newdata="{\"video\":"+data+"}";
JSONObject jsono = new JSONObject(newdata);
JSONArray jarray = jsono.getJSONArray("video");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Videos video = new Videos();
video.setName(object.getString("name"));
video.setId(object.getString("id"));
video.setCategory(object.getString("category"));
video.setTime(object.getString("time"));
video.setSubtitles(object.getString("subtitles"));
video.setYoutube(object.getString("youtube"));
video.setImage(object.getString("image"));
videoList.add(video);
}
return true;
suggestion : Use HttpURLConnection !
1. create JSONParser.java
public class JSONParser extends Thread
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
URL myUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
connection.connect();
is = connection.getInputStream();
} catch (Exception e) {
is = null;
}
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) {
json = "";
}
try {
jObj = new JSONObject(json);
} catch (JSONException e)
{
jObj = null;
}
return jObj;
}
}
Use like this.
private class JSONParse extends AsyncTask
{
#Override
protected void onPreExecute()
{
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
//json.get......
}
I can see a lot of things you could be doing better.
The best way to load data onto a Fragment is using an ArrayAdapter (because you want to load a list) and a Loader.
Your App could get so much better if you use Google Volley as network provider and GSON or Jackson for JSON so you don't need to write this kind of code
Videos video = new Videos();
video.setName(object.getString("name"));
video.setId(object.getString("id"));
Fragments should be only used to display data, not to get it from network or have network code on the Fragment. To get data from the server you always need to be working with a Loader.
Basically you need to create a Loader class that extends from AsyncTaskLoader<ArrayList<Videos>> and your fragment needs to implement LoaderManager.LoaderCallbacks<ArrayList<Videos>> on the Loader public ArrayList<Videos> loadInBackground() you should be requesting the data from server and returning an ArrayList of Videos.

How to make onPostExecute() or Json parsing work?

I am a beginner in Android, and I am writing a short program to download a JSON feed from URL and parse it. I use AsyncTask to do the downloading.
The doInBackground() part seems to work well. Then I set my breakpoint to onPostExecute(), it can even stop at parseJSON(result), and 'result' is showing the correct json string downloaded. But when I try to step into parseJSON(result), it will NOT step into the function correctly(either throw JSONException directly or go to some random lines within parseJSON(result)).
From DDMS log it's not showing any valuable information as well.
How might I find what the problem is? Is it because I used onPostExecute() incorrectly, or parseJSON() has some problem?
public class MainActivity extends Activity {
private listItem[] items;
public class listItem {
String title;
String description;
String imageHref;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new listItem[50];
new DownloadJsonFeed().execute("http://dl.dropbox.com/u/10168342/facts.json");
}
private class DownloadJsonFeed extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
return downloadUrl(params[0]);
} catch (IOException e) {
return "Unable to retrieve json feed. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
try {
parseJSON(result); // Here !!!!!!
} catch (JSONException e) {
}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
} finally {
if (is != null) {
is.close();
}
}
}
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = new JSONArray(rows);
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}
JSONObject.getString() will try to get String type value, but what you want is array type.
I think you didn't get the JSON array right. The json_obj.getString will give you an String instead an array.
Try to change as follows:
private void parseJSON(String feed) throws JSONException {
JSONObject json_obj = new JSONObject(feed);
title = json_obj.getString("title");
String rows = json_obj.getString("rows");
JSONArray jArray = json_obj.getJSONArray("rows"); //<---- change this line
for (int i = 0; i < jArray.length(); i++) {
JSONObject tmp = jArray.getJSONObject(i);
items[i].title = tmp.getString("title");
items[i].description = tmp.getString("description");
items[i].imageHref = tmp.getString("imageHref");
}
}

Categories

Resources