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

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

Related

How to retreive data from mysql database and parse it in textview?

im new in programming with android , i am trying to get data from mysql database and parse it into textView , i tried to get json and it works fine. But when i try to parse it into textView it doesn't work ??
Please any help to provide ??
Here is my java method :
protected String doInBackground(Void...params){
InputStream is=null;
String result="";
try{
URL url = new URL(json_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
is = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
while((json_string = reader.readLine())!=null){
stringBuilder.append(json_string+"\n");
}
JSONObject jObject = new JSONObject(json_string);
JSONArray jArray = jObject.getJSONArray("utilisateur");
for (int i = 0; i < jArray.length();i++){
JSONObject oneObject = jArray.getJSONObject(i);
oneObject.getString("nom");//return the address
oneObject.getString("prenom");//return the name
}
reader.close();
is.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
}catch(IOException e){
e.printStackTrace();
}catch (JSONException e){
e.printStackTrace();
}
This is my php code :
<?php
$DB_USER='mootaz';
$DB_PASS='mootaz';
$DB_HOST='localhost';
$DB_NAME='mvoting_db_1.0.0.0';
$sql = "select * from utilisateur where role='administrateur';";
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$result = mysqli_query($con,$sql);
$response = array();
while ($row = mysqli_fetch_array($result))
{
array_push($response,array("name"=>$row[3],"prenom"=>$row[4]));
}
echo json_encode(array("utilisateur"=>$response));
mysqli_close($con);
?>
When you getting data that store in object and then after bind data into text view like below code..
make pojo class for your response like
public class User {
private String name,addres;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddres() {
return addres;
}
public void setAddres(String addres) {
this.addres = addres;
}
}
make array list to store data like below ..
private List<User> mUserList=new ArrayList<>();
when you doInBackground method used below like ..
User user=new User();
for (int i = 0; i < jArray.length();i++){
JSONObject oneObject = jArray.getJSONObject(i);
user.setAddres(oneObject.getString("nom"));//return the address
user.setName(oneObject.getString("prenom"));//return the name
mUserList.add(user);
}
then after onPostExecute bind data.
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
for(User user:mUserList)
{
textview.setText(user.getAddres());
}
}

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\"}]}

how to fetch json object from url in 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!

Android - How to properly set up an AsyncTask to fetch JSON data from URL?

I have an object, contact, with a detailsURL String. At that URL is some JSON with more information about the contact that I need to set. The way I'm attempting to do this AsyncTask is like this:
class detailDownloader extends AsyncTask<String, Void, Void> {
String detail;
private contact c;
public detailDownloader(String detail, contact c) {
this.c = c;
this.detail = detail;
}
protected Void doInBackground(String... urls) {
String url = urls[0];
Log.d("contact", "1");
String s;
try {
InputStream in = new java.net.URL(url).openStream();
Log.d("contact", "2");
BufferedReader br2 = null;
br2 = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder sb2 = new StringBuilder();
Log.d("contact", "3");
while((s = br2.readLine()) != null) {
sb2.append(s);
}
s = sb2.toString();
JSONArray detail = new JSONArray(s);
for(int j = 0; j < detail.length(); j++){
JSONObject obj2 = detail.getJSONObject(j);
boolean favorite = obj2.getBoolean("favorite");
String email = obj2.getString("email");
String largeURL = obj2.getString("largeImageURL");
JSONObject address = obj2.getJSONObject("address");
String street = address.getString("street");
String city = address.getString("city");
String state = address.getString("state");
c.setFavorite(favorite);
c.setLargeURL(largeURL);
c.setEmail(email);
c.setStreet(street);
c.setCityState(city + ", " + state);
}
in.close();
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
return null;
}
}
The detailDownloader is called by:
new detailDownloader(c.getDetailsURL(), c).execute();
But I get a response in my Log: "03-06 16:30:24.724: I/Choreographer(29237): Skipped 370 frames! The application may be doing too much work on its main thread."
Any idea how to fix this issue?
This code looks OK to me at first glance. Are you sure it's this class that's causing the skipped frames? Are you sure that you're not doing something else on the main thread that's causing this problem?
Does your detailsDownloader class implement onPreExecute or onPostExecute? If so, you should post your code for those methods, too.
Such kind of error is usually caused by using too much UI threads, check this for more information.

How to download a JSON Object array from URL, and Store for Android App?

I'm trying to integrate an API into an android application I am writing, but am having a nightmare trying to get the JSON array. The API has a URL that returns a an JSON array, but having never used JSON before I have no idea how this works, or how to do it.
I've looked and found tons, and tons of examples, but nothing to explain why/how it is done. Any help understanding this would be greatly appreciated.
This is what I've ended up with, again with no understanding of JSON, it was a shot in the dark on my part (using examples/tutorials as a guide)...but it doesn't work :(
import org.json.*;
//Connect to URL
URL url = new URL("URL WOULD BE HERE");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
//Get Data from URL Link
int ok = connection.getResponseCode();
if (ok == 200) {
String line = null;
BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while ((line = buffer.readLine()) != null)
sb.append(line + '\n');
//FROM HERE ON I'm Kinda Lost & Guessed
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString()); //ERROR HERE:complains it dosn't know what JSONValue is
JSONArray array = (JSONArray)obj.get("response");
for (int i=0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("name")); //Used to debug
}
}
UPDATE/SOLUTION:
So, it turns out that there was nothing wrong w/t the code. I was missusing what I thought it returns. I thought it was a JSONObject array. In actuality it was a JSONObjects wrapped in an array, wrapped in a JSONObject.
For those interested/ having similar issues, this is what I ended up with. I broke it into two methods. First connect/download, then:
private String[] buildArrayList(String Json, String Find) {
String ret[] = null;
try {
JSONObject jObject = new JSONObject(Json);
JSONArray jArray = jObject.getJSONArray("response");
ret = new String[jArray.length()];
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String var = json_data.getString(Find);
ret[i] = var;
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
1) use webservice to download your required Json string
2) convert it to your desired object using Google Gson
Gson gson = new Gson();
MyClass C1 = gson.fromJson(strJson, MyClass.class);
Here you used JSONValue.parse() that is invalid.
Insted of that Line write this code:
JSONObject obj = new JSONObject(<String Value>);
Ok my friend, i solved the same problem in my app with the next code:
1.- Class to handle the Http request:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONObject jObj1 = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
//Log.e("JSONObject(JSONParser1):", json);
} catch (Exception e) {
Log.e("Buffer Error json1" +
"", "Error converting result json1:" + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj1 = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser1:", "Error parsing data json1:" + e.toString());
}
// return JSON String
return jObj;
}
}
Later, a class to handle the json info (Arrays, Objects, String, etc...)
public class ListViewer extends ListActivity{
TextView UserName1;
TextView LastName1;
// url to make request
private static String url = "http://your.com/url";
// JSON Node names
public static final String TAG_COURSES = "Courses"; //JSONArray
//public static final String TAG_USER = "Users"; //JSONArray -unused here.
//Tags from JSon log.aspx All Data Courses.
public static final String TAG_COURSEID = "CourseId"; //Object from Courses
public static final String TAG_TITLE = "title";
public static final String TAG_INSTRUCTOR = "instructor";
public static final String TAG_LENGTH = "length";
public static final String TAG_RATING = "Rating"; //Object from Courses
public static final String TAG_SUBJECT = "subject";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_STATUS = "Status"; //Object from Courses
public static final String TAG_FIRSTNAME = "FirstName"; //Object from User
public static final String TAG_LASTNAME = "LastName"; //Object from User
// contacts JSONArray
JSONArray Courses = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lay_main);
// Hashmap for ListView
final ArrayList<HashMap<String, String>> coursesList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance (json2)
JSONParser2 jParser2 = new JSONParser2();
// getting JSON string from URL json2
final JSONObject json2 = jParser2.getJSONFromUrl(url);
try {
// Getting Array of Contacts
Courses = json2.getJSONArray(TAG_COURSES);
// looping through All Courses
for(int i = 0; i < Courses.length(); i++){
JSONObject courses1 = Courses.getJSONObject(i);
// Storing each json item in variable
String courseID = courses1.getString(TAG_COURSEID);
//String status = courses1.getString(TAG_STATUS);
String Title = courses1.getString(TAG_TITLE);
String instructor = courses1.getString(TAG_INSTRUCTOR);
String length = courses1.getString(TAG_LENGTH);
String rating = courses1.getString(TAG_RATING);
String subject = courses1.getString(TAG_SUBJECT);
String description = courses1.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_COURSEID,courseID);
map.put(TAG_TITLE, Title);
map.put(TAG_INSTRUCTOR, instructor);
map.put(TAG_LENGTH, length);
map.put(TAG_RATING, rating);
map.put(TAG_SUBJECT, subject);
map.put(TAG_DESCRIPTION, description);
//adding HashList to ArrayList
coursesList.add(map);
}} //for Courses
catch (JSONException e) {
e.printStackTrace();
}
//Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, coursesList,
R.layout.list_courses,
new String[] { TAG_COURSEID, TAG_TITLE, TAG_INSTRUCTOR, TAG_LENGTH, TAG_RATING, TAG_SUBJECT, TAG_DESCRIPTION }, new int[] {
R.id.txt_courseid, R.id.txt_title, R.id.txt_instructor, R.id.txt_length, R.id.txt_rating, R.id.txt_topic, R.id.txt_description });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
//#Override --------check this override for onClick event---------
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String courseID = ((TextView) view.findViewById(R.id.txt_courseid)).getText().toString();
String Title = ((TextView) view.findViewById(R.id.txt_title)).getText().toString();
String instructor = ((TextView) view.findViewById(R.id.txt_instructor)).getText().toString();
String length = ((TextView) view.findViewById(R.id.txt_length)).getText().toString();
String rating = ((TextView) view.findViewById(R.id.txt_rating)).getText().toString();//Check place in layout
String subject = ((TextView) view.findViewById(R.id.txt_topic)).getText().toString();// <- HERE
String description = ((TextView) view.findViewById(R.id.txt_description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(TAG_COURSEID, courseID);
in.putExtra(TAG_TITLE, Title);
in.putExtra(TAG_INSTRUCTOR, instructor);
in.putExtra(TAG_LENGTH, length);
in.putExtra(TAG_RATING, rating);
in.putExtra(TAG_SUBJECT, subject);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});//lv.SetOnclickListener
}//onCreate
}// Activity
in this case, i'll get the Arrays, objects... Hope this give you ideas...

Categories

Resources