After getting response from server i am storing points in my integer array and i am trying to add that array in my horizontal scrollview,but it gives me error in my loop,following is my code can anyone help?thanks advance
Error near this line
tv.setText(points.get(i));
JAVA
protected ArrayList<HashMap<String, String>> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(PLACE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
placejsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
jobject = placejsonObj.getJSONObject(0);
msgs=jobject.getString("user_status");
pointsarray=placejsonObj.getJSONArray(1);
// points=pointsarray.getString("point");
System.out.println("Kya yar" + "Failure"+pointsarray);
points = new int[pointsarray.length()];
for(int m=0; m<pointsarray.length(); m++) {
points[m] = pointsarray.getJSONObject(m).getInt("point");
}
System.out.println("array contains" + points.length + " elements");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
for (int i = 0; i < points.length; i++) {
tv = new TextView(getActivity());
tv.setText(points[i]+",");
tv.setTag(points[i]);
yourLayout.addView(tv);
}
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int point = (int) view.getTag();
Toast.makeText(getActivity(),point,Toast.LENGTH_SHORT).show();
}
});
}
}
points is an array so do like
tv.setText(""+points[i]);
To get item from Array Use points[i] and to get item from List use points.get(i);
You have 2 problems as I see. The first is you try to set the text using an int, and the second is the way you try to access the data in the array (you use it like a list). Try it like this:
tv.setText(points[i] + "");
Related
The carList is declared as a public variable in the class, and the log shows that values are added in the array, yet when I call the list is empty, how to solve it with Volley response?
public void onResponse(JSONObject response) {
try {
JSONArray resArray = response.getJSONArray("result");
for(int i=0;i<resArray.length();i++) {
JSONObject car = resArray.getJSONObject(i);
String id = car.getString("id");
String brand = car.getString("brand");
String created = car.getString("created");
carList.add(new CarListItem(brand, plate_number));
Log.d(TAG, "ADDED___: " +brand + " " + plate_number);
}
Thanks
#Benp
You right, the solution is to add the recycler adapter within the onResponse body as here:
public void onResponse(JSONObject response) {
try {
JSONArray resArray = response.getJSONArray("result");
for (int i = 0; i < resArray.length(); i++) {
JSONObject car = resArray.getJSONObject(i);
String id = car.getString("id");
String brand = car.getString("brand");
String created = car.getString("created");
carList.add(new CarListItem(car_id, brand, plateNumber, color));
}
} catch (JSONException e) {
e.printStackTrace();
}
if (carList.size() > 0) {
mAdapter = new RecyclerAdapterCarsList(carList);
buildRecyclerView();
}
}
It was simple, need a tiny clue to fix it ;)
Thanks for helping
I am trying to order my JSON data by name, I've found some answers here, but nothing works for my case. I have tried to update my code as you see below. I marked there what I have removed from original code, and what have I added:
#Override
protected Boolean doInBackground(String... args) {
HttpHandler sh = new HttpHandler();
String url = "androidnews.json";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
//removed this:
//JSONObject jsonObj = new JSONObject(jsonStr);
//JSONArray actors = jsonObj.getJSONArray("result");
//ADDED:
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
JSONArray actors = new JSONArray("result");
for (int i = 0; i < actors.length(); i++) {
JSONObject c = actors.getJSONObject(i);
//ADDED:
array.add(actors.getJSONObject(i));
Actors actor = new Actors();
actor.setName(c.getString("name"));
actor.setThumb(c.getString("thumb"));
actorsList.add(actor);
}
//ADDED:
Collections.sort(array, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
// TODO Auto-generated method stub
try {
return (lhs.getString("name").toLowerCase().compareTo(rhs.getString("name").toLowerCase()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
}
});
} catch (final JSONException e) {
Zoznam.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Zoznam.this.getApplicationContext(),
"Data error " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); }
return true;
} else {
Zoznam.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(Zoznam.this.getApplicationContext(),
"Chyba internetového pripojenia.",
Toast.LENGTH_LONG).show();
}
});
return false;
}
}
But after I test it, I have this error: Value result of type java.lang.String cannot be converted to JSONArray
My JSON begins with: {"result": [{"name": "Joe","thumb": "image.jpg",...
Instead of sorting your JSONArray try sorting your Arraylist with custom object and use it. you can do something like this
Collections.sort(actorsList, new Comparator<Actors>() {
#Override
public int compare(Actors lhs, Actors rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
A solution to your current problem:
Im guessing that you are using the org.json library.
Currently you are trying to create a JSONArray from the string "result".
This is how you access an array within the JSON file:
JSONObject obj = new JSONObject(Files.readAllLines(Paths.get("/path/to/your/file.json")));
JSONArray arr = obj.getJSONArray("number");
Source: more helpful examples like the one above
Further information:
As it seems like your not to familiar with the org.json approach I would highly recommend taking a look at gson as it provides an easy way to map JSON entries to objects (or even Arrays of an Object).
See: this and this
I am running the commands like so:
new GetGameScoresFromFuhantikAPI()
And my method for this is ->
private class GetGameScoresFromFuhantikAPI extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
MethodContants.showLog(TAG, "Loading FUHNATIK API", true);
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = API_URL + jsonFile;
// String url = "http://www.nfl.com/liveupdate/game-center/" + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from FUHNATIK API: " + url);
if (jsonStr != null) {
try {
//JSONObject object = new JSONObject(json);
JSONObject object = new JSONObject(jsonStr);
currentWeek = object.getString("pypwk");
currentWeekDB = object.getString("mdb");
JSONArray array = (JSONArray) object.get("g");
scheduleModelList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
//TODO IF WE DONT PLAY THURSDAY GAMES PUT LIST.ADD IN HERE
// if (!array.getJSONObject(i).getString("-d").equals("Thu")){
//
// }
scheduleModelList.add(new ScheduleModel(array.getJSONObject(i).getString("-v"),
array.getJSONObject(i).getString("-h"),
array.getJSONObject(i).getString("-t"),
array.getJSONObject(i).getString("-d"),
array.getJSONObject(i).getString("-eid").substring(0, 8),
array.getJSONObject(i).getString("-t") + array.getJSONObject(i).getString("-q"),
array.getJSONObject(i).getString("-vnn"),
array.getJSONObject(i).getString("-hnn"),
"...select a team...",
array.getJSONObject(i).getString("-eid"),
array.getJSONObject(i).getString("-vs"),
array.getJSONObject(i).getString("-hs"),
array.getJSONObject(i).getString("-w")));
}
} catch (final JSONException e) {
Log.e(TAG, "FUHNATIK API: Json parsing error: " + e.getMessage());
}
} else {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "FUHNATIK API: Couldn't get json from server.");
Toast.makeText(getContext(), "Getting from ESPN", Toast.LENGTH_SHORT).show();
//new GetGameScoresFromESPN().execute();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final ListViewAdapterResults adapter = new ListViewAdapterResults(listView.getContext(), scheduleModelList);
listView.setAdapter(adapter);
MethodContants.showLog(TAG, "DONE WITH LOADING FUHNATIK API", false);
}
}
I can't seem to figure out why the code never get ran. I ran through the debugger but I really can't pinpoint where this is failing out. Any help on this would be appreciated.
Eventually if the json file is not at this URL, I will be getting the json from NFL. However, Without this working, the ESPN won't work either, and I really can not figure out where the error is on my end. I have to assume this will be a pretty easy fix.
Again, as said before, any help would be very appreciated!!
In the above line of code you call the Class but you forgot to execute your asynctask. So no Overriden methods are called. Try this:
new GetGameScoresFromFuhantikAPI().execute();
If you want to pass something as argument, give parameters separated by coma like this:
new GetGameScoresFromFuhantikAPI().execute(arg0, arg1);
I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:
[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]
I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables
After sometime trying and trying I found a way to
String finalJson = buffer.toString();
try {
JSONArray parentArray = new JSONArray(finalJson);
int count = 0;
int[] id = new int[parentArray.length()];
String[] title = new String[parentArray.length()];
StringBuffer finalBufferedData = new StringBuffer();
while (count < parentArray.length())
{
JSONObject finalObject = parentArray.getJSONObject(count);
id[count] = finalObject.getInt("id");
title[count] = finalObject.getString("title");
finalBufferedData.append(id[count] + " - " + title[count] + "\n");
count++;
}
return finalBufferedData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
this way I was able to get the 2 rows from postgresql and show it (later will add it the app sqlite so it doesn't require always to check in my postgresql)
Here is the working code:
public void parseJson() {
// Response from API call
String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" +
"{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]";
try {
JSONArray jsonArray = new JSONArray(response);
// Get all jsonObject from jsonArray
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = null, title = null;
// Id
if (jsonObject.has("id") && !jsonObject.isNull("id")) {
id = jsonObject.getString("id");
}
// Title
if (jsonObject.has("title") && !jsonObject.isNull("title")) {
title = jsonObject.getString("title");
}
Log.d("SUCCESS", "JSON Object: " + "\nId: " + id
+ "\nTitle: " + title);
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
OUTPUT:
D/SUCCESS: JSON Object:
Id: 1
Title: 12 May to 30 Jun
D/SUCCESS: JSON Object:
Id: 2
Title: 3 Jun to 20 Jun
protected void onPostExecute(String result)
{
//result parameter should be final so that it can be used in cross thread operation
super.onPostExecute(result);
if (result != null) {
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String Brand = object.getString("UserName");
HashMap<String, String> itemList = new HashMap<String, String>();
itemList.put("UserName", Brand);
BrandList.add(itemList);
}
**adapter = new SimpleAdapter(Main2Activity.this, BrandList, R.layout.list, new String[]{"UserName"}, new int[]{R.id.txtTitel});
((AdapterView<ListAdapter>) listView).setAdapter(adapter);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
Toast.makeText(Main2Activity.this, "Could not get any data.", Toast.LENGTH_LONG).show();
}
}
I'm trying to get this array of images in this json bellow and display it in GridView but i don't know why i can't reach that >>>
{
id: 241,
title: "title",
image: "1469370455.jpg",
description: " descriotion ",
images: [
"1469370455.jpg",
"1469370458.jpg",
"1469370481.jpg",
"1469370484.jpg"
]}
and this is my full AyncTask.
private class AysncImages extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(getActivity());
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
// pDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
Log.i(TAG, "array: "+ jsonObj);
GridItem item = new GridItem();
for (int i = 0; i < arrayObj.length(); i++) {
String images = arrayObj.getString(i);
Log.i(TAG, "parseResult: " + jsonObj);
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
// Getting JSON Array node
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// if (result == 1) {
mGridAdapter.setGridData(mGridData);
//} else {
// Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
// }
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
In my log i can't reach jsonObj or arrayObj I just can reach jsonStr what I'm missing ?
My Log for jsonStr
the json string you get is [{id:abc,...}]
but a JsonObject should start with {id:abc,...}
maybe you try to remove the '[' and ']' at the end of string in order to get the object
as start with '[' should be an array