I can't get complete data from server by using API.
I use AsyncTask and HttpURLConnection to get data, it can work.
But when server return more data, I found that I can't get complete data.
How can I fix that, thank you.
Here is my code. and in these code, I can't get data of jsonArray_banner, it always return null array.
public class JSONTask_Login extends AsyncTask<String, String, String> {
private String deviceId, os, ver;
public JSONTask_Login(String _deviceId, String _os, String _ver) {
this.deviceId = _deviceId;
this.os = _os;
this.ver = _ver;
}
#Override
protected String doInBackground(String... params) {
try {
String SERVER_WS_URL = params[0];
parameter.clear();
parameter.put("deviceId", deviceId);
parameter.put("os", os);
parameter.put("ver", ver);
return ApiCall.postWebserviceCall(SERVER_WS_URL, parameter); // POST.
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
if (result != null) {
JSONObject jsonObject = new JSONObject(result);
code = jsonObject.getString("code");
msg = jsonObject.getString("msg");
if (Integer.valueOf(code) == 0) {
// 1st block.
JSONObject jsonObject_userInfo = jsonObject.getJSONObject("userInfo");
....
// 2nd block.
JSONArray jsonArray_first = jsonObject.getJSONArray("anonymous_first_name");
for(int i = 0; i < jsonArray_first.length(); i++) {
JSONObject jsonObject_anonFirst = jsonArray_first.getJSONObject(i);
...
}
// 3rd block.
JSONArray jsonArray_Second = jsonObject.getJSONArray("anonymous_second_name");
for(int i = 0; i < jsonArray_Second.length(); i++) {
JSONObject jsonObject_anonSecond = jsonArray_Second.getJSONObject(i);
...
}
// 4th block.
JSONArray jsonArray_Head = jsonObject.getJSONArray("anonymous_head");
for(int i = 0; i < jsonArray_Head.length(); i++) {
JSONObject jsonObject_anonHead = jsonArray_Head.getJSONObject(i);
...
}
// 5th block.
JSONArray jsonArray_list = jsonObject.getJSONArray("posts_group_list");
for(int i = 0; i < jsonArray_list.length(); i++) {
JSONObject jsonObject_list = jsonArray_list.getJSONObject(i);
...
}
// 6th block.
// I can get data of this block, jsonArray_banner always return null array.
JSONArray jsonArray_banner = jsonObject.getJSONArray("banner_home");
for(int i = 0; i < jsonArray_banner.length(); i++) {
JSONObject jsonObject_banner = jsonArray_banner.getJSONObject(i);
...
}
}
else
return;
} else
return;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is my ApiCall code:
class ApiCall {
static String postWebserviceCall(String URL, LinkedHashMap<String, String> params) {
try {
URL url = new URL(URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
if (params != null)
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
conn.connect();
int responseCode = conn.getResponseCode();
InputStream iStream;
if (responseCode == HttpURLConnection.HTTP_OK)
iStream = conn.getInputStream();
else
iStream = conn.getErrorStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line);
Log.e("test", line);
}
return response.toString();
} catch (Exception e) {
return null;
}
}
static String getWebserviceCall(String URL, LinkedHashMap<String, String> params) {
...
}
private static String getPostDataString(LinkedHashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Here is my api structure:
{
code: 0,
msg: "",
userInfo: {
token: "token",
nick: "user",
head: "Head/Default.png",
...
},
anonymous_first_name: [
{
id: "1",
nick_name: "one",
},
{
id: "2",
nick_name: "two",
},
...
],
anonymous_second_name: [
{
id: "1",
nick_name: "one",
},
{
id: "2",
nick_name: "two",
},
...
],
anonymous_head: [
{
id: "1",
head: "System/AnonHead/star_head_01.png",
},
{
id: "2",
head: "System/AnonHead/star_head_02.png",
},
...
],
posts_group_list: [
{
post_group: "1",
title: "title",
short_title: "stitle",
icon: "System/Classify/classify_01_food.png",
img: "",
color_code: "#E53737",
},
{
post_group: "2",
title: "title",
short_title: "stitle",
icon: "System/Classify/classify_02_travel.png",
img: "",
color_code: "#3C9BA5",
},
...
],
banner_home: [
{
title: "title",
gid: "25",
url: "url",
banner: "imgurl",
start_time: "2019-08-30 00:00:00",
end_time: "2021-08-30 00:00:00",
},
{
title: "title",
gid: "24",
url: "url",
banner: "imgurl",
start_time: "2019-08-30 00:00:00",
end_time: "2021-08-30 00:00:00",
},
...
],
}
Related
I'm trying to pull the "price" object from the "current" array, I have been at it for hours now with no luck, any help is appreciated! :)
try {
URL url = new URL("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=2");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
JSONArray nu1 = jobj.getJSONArray("current");
JSONObject jobj = nu1.getJSONObject(0);
String price = jobj.getString("price");
Toast.makeText(getApplicationContext(), price, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
}
}
}
I tried to get response from your URL. here is the response :
{
"item": {
"icon": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_sprite.gif?id=2",
"icon_large": "http://services.runescape.com/m=itemdb_rs/1502782993572_obj_big.gif?id=2",
"id": 2,
"type": "Ammo",
"typeIcon": "http://www.runescape.com/img/categories/Ammo",
"name": "Cannonball",
"description": "Ammo for the Dwarf Cannon.",
"current": {
"trend": "neutral",
"price": 339
},
"today": {
"trend": "positive",
"price": "+1"
},
"members": "true",
"day30": {
"trend": "positive",
"change": "+1.0%"
},
"day90": {
"trend": "negative",
"change": "-11.0%"
},
"day180": {
"trend": "negative",
"change": "-21.0%"
}
}
}
there is no array in the response.
Edit:
assume that you store your response in a String named response, you can get price, using the following code:
JSONObject json = new JSONObject(response);
JSONObject item = json.getJSONObject("item");
JSONObject current = item.getJSONObject("current");
int price = current.getInt("price");
Edit2: use
String response = stringBuilder.toString();
and then make a JSONObject from 'response' .
I am working on application in which i want one output as shown in below image.
for that i tried following code:
private ListView notification_listview;
private String BeauticianId="98";
private String serviceType="all";
private ArrayList<NameValuePair> params11;
ArrayList<MainArray_method> MainList;
MainArray_adapter main_adapter;
ArrayList<SubArray_method> SubList;
SubArray_adapter sub_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notification_listview = (ListView) findViewById(R.id.listView_notification);
}
#Override
public void onResume() {
super.onResume();
params11 = new ArrayList<NameValuePair>();
params11.add(new BasicNameValuePair("iBeauticianId", BeauticianId));
params11.add(new BasicNameValuePair("serviceType", serviceType));
new background().execute();
}
private class background extends AsyncTask<Void, Void, String> {
ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/services", params11);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result", "" + result);
try {
JSONObject json = new JSONObject(result);
String status = json.getString("status");
Log.d("Status:", status);
String data = json.getString("data");
Log.d("Data:", data);
MainList = new ArrayList<MainArray_method>();
JSONArray MainArray = json.getJSONArray("data");
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
}
if (main_adapter== null && sub_adapter == null)
{
main_adapter=new MainArray_adapter(getApplicationContext(),MainList);
notification_listview.setAdapter(main_adapter);
sub_adapter=new SubArray_adapter(getApplicationContext(),SubList);
notification_listview.setAdapter(sub_adapter);
} else {
sub_adapter.notifyDataSetChanged();
main_adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
pDialog.dismiss();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// 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);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
but in this i just get two record of subarray.
What should i do to get output as shown in image.
Thanks in advance.
JSON response:
{
"status":1,
"data":[
{
"iMainServiceId":1,
"main":"NAILS",
"sub":[
{
"iSubServiceId":1,
"vName":"Manicure",
"fPrice":15,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":2,
"vName":"Gel Manicure",
"fPrice":25,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":5,
"vName":"Nail art ",
"fPrice":10,
"vDuration":"20 Minutes"
},
{
"iSubServiceId":6,
"vName":"Nail Pain ",
"fPrice":10,
"vDuration":"20 Minutes"
}
]
},
{
"iMainServiceId":2,
"main":"HAIR",
"sub":[
{
"iSubServiceId":3,
"vName":"Haircuts",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":4,
"vName":"Hair color",
"fPrice":50,
"vDuration":"60 Minutes"
},
{
"iSubServiceId":7,
"vName":"Textures",
"fPrice":20,
"vDuration":"30 Minutes"
},
{
"iSubServiceId":8,
"vName":"Treatments",
"fPrice":30,
"vDuration":"60 Minutes"
}
]
},
{
"iMainServiceId":3,
"main":"Face",
"sub":[
{
"iSubServiceId":9,
"vName":"Facials",
"fPrice":20,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":10,
"vName":"Brow Bar",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":11,
"vName":"Makeup ",
"fPrice":40,
"vDuration":"49 Minutes"
}
]
},
{
"iMainServiceId":4,
"main":"Body",
"sub":[
{
"iSubServiceId":12,
"vName":"Hair Removal",
"fPrice":40,
"vDuration":"49 Minutes"
},
{
"iSubServiceId":13,
"vName":"Body Treatments",
"fPrice":30,
"vDuration":"30 Minutes"
}
]
}
]
}
and wt i get as enter image description hereoutput is:
for (int i = 0; i < MainArray.length(); i++) {
JSONObject jsonObject = MainArray.getJSONObject(i);
String MainServiceId = jsonObject.getString("iMainServiceId");
Log.d("MainServiceId:", MainServiceId);
String MainService = jsonObject.getString("main");
Log.d("MainService:", MainService);
String sub = jsonObject.getString("sub");
Log.d("sub:", sub);
SubList = new ArrayList<SubArray_method>();
JSONArray SubArray = jsonObject.getJSONArray("sub");
for (int j = 0; j < SubArray.length(); j++) {
/*JSONObject subjsonObject = SubArray.getJSONObject(j);*/
/*String SubServiceId = subjsonObject.getString("iSubServiceId");
Log.d("subserviceid:", SubServiceId);
String SubServiceName = subjsonObject.getString("vName");
Log.d("SubServiceName:", SubServiceName);
String SubServicePrice = subjsonObject.getString("fPrice");
Log.d("SubServicePrice:", SubServicePrice);
String SubServiceTime = subjsonObject.getString("vDuration");
Log.d("SubServiceTime:", SubServiceTime);*/
SubList.add(new SubArray_method(SubArray.getJSONObject(j).getString("iSubServiceId"),
SubArray.getJSONObject(j).getString("vName"),
SubArray.getJSONObject(j).getString("fPrice"),
SubArray.getJSONObject(j).getString("vDuration")));
}
// This should be in outer for loop<<---------------------<<<<<
MainList.add(new MainArray_method(MainArray.getJSONObject(i).getString("iMainServiceId"),
MainArray.getJSONObject(i).getString("main")));
}
{
"page": 1,
"results": [
{
"poster_path": "/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg",
"adult": false,
"overview": "Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.",
"release_date": "2014-10-10",
"genre_ids": [
18,
10402
],
"id": 244786,
"original_title": "Whiplash",
"original_language": "en",
"title": "Whiplash",
"backdrop_path": "/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg",
"popularity": 7.361171,
"vote_count": 1949,
"video": false,
"vote_average": 8.32
}
]
}
This is my JSON response but when i parse it the value of id is always null
Below is my networking and JSON parsing code please help..
public class movietask extends AsyncTask<String, Void, List<movieobject>> {
private String TAG;
private static final String Base_string = "http://api.themoviedb.org/3/movie/";
private static final String api_key = "388e5684ea2f3bb8de279874cb6990a5";
private static final String MOVIE_ID="id";
private static final String MOVIE_OVERVIEW="overview";
private static final String MOVIE_TITLE="original_title";
private static final String MOVIE_VOTE="vote_average";
private static final String MOVIE_POSTERPATH="poster_path";
private static final String MOVIE_RELEASE_DATE="release_date";
private static final String MOVIE_BACKDROP_PATH="backdrop_path";
// Parse json data to get arraylist of movieobjects
private List<movieobject> getparseddata(String forecastjsonstr)
throws JSONException {
final String START_OF_JSON = "results";
JSONObject startlist = new JSONObject(forecastjsonstr);
JSONArray startarray = startlist.getJSONArray(START_OF_JSON);
int noofobjects = startarray.length();
List<movieobject> objectarray = new ArrayList<>();
for (int i = 0; i < noofobjects; i++) {
JSONObject object = startarray.getJSONObject(i);
movieobject finalobjectarray = new movieobject();
finalobjectarray.setMovieId(object.getString(MOVIE_ID));
finalobjectarray.setOverview(object.getString(MOVIE_OVERVIEW));
finalobjectarray.setTitle(object.getString(MOVIE_TITLE));
finalobjectarray.setMovieRating(object.getString(MOVIE_VOTE));
finalobjectarray.setPosterPath(object.getString(MOVIE_POSTERPATH));
finalobjectarray.setReleaseDate(object.getString(MOVIE_RELEASE_DATE));
finalobjectarray.setBackdroppath(object.getString(MOVIE_BACKDROP_PATH)+"/10");
objectarray.add(finalobjectarray);
}
return objectarray;
}
protected List<movieobject> doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
List<movieobject> finalobjectarray = new ArrayList<>();
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
URL url = new URL(Base_string + params[0] + "?api_key="+api_key);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
Log.i("hey", "Hello" + forecastJsonStr);
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
finalobjectarray = getparseddata(forecastJsonStr);
} catch (JSONException e) {
Log.e("Json exception", e.getMessage(), e);
e.printStackTrace();
}
return finalobjectarray; //final movieobject array
}
//onPostExecute method of asynctask
protected void onPostExecute(List<movieobject> results) {
}
}
The ID is null because "id" is not a String.
Let's check your JSON.
{
"page":1,
"results":[
{
"poster_path":"/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg",
"adult":false,
"overview":"Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.",
"release_date":"2014-10-10",
"genre_ids":[
18,
10402
],
"id":244786, <------- Without "" = Integer
"original_title":"Whiplash", <-------- With "" = String
"original_language":"en",
"title":"Whiplash",
"backdrop_path":"/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg",
"popularity":7.361171,
"vote_count":1949,
"video":false,
"vote_average":8.32
}
]
}
So, to get the value you will use getInt()
finalobjectarray.setMovieId(object.getInt(MOVIE_ID).toString());
this might help. Ideally the MovieId in your movie object should be an int:
finalobjectarray.setMovieId(""+object.getInt(MOVIE_ID));
Getting org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject..Where would be code went wrong?This is a program to get values from a live streaming ..complete code is given below..
JSON given
race: {
id: "44708",
track_id: "1",
track: "International",
starts_at: "2016-05-04 06:16:00",
finish_time: "1970-01-01 01:00:00",
heat_type_id: "123",
heat_status_id: "1",
speed_level_id: "5",
speed_level: "Nat Cadet & Junior",
win_by: "position",
race_by: "minutes",
duration: 10,
race_name: "Inkart National Heat",
race_time_in_seconds: 276.336
},
scoreboard: [
{
position: "1",
nickname: "Emily Linscott",
average_lap_time: "90.053",
fastest_lap_time: "60.490",
last_lap_time: "60.490",
rpm: "1225",
first_name: "Emily",
last_name: "Linscott",
is_first_time: "0",
total_races: "6",
racer_id: "1157509",
lap_num: "3",
kart_num: "63",
gap: ".000",
ambtime: "31728819591"
},
Code
protected JSONObject doInBackground(String... urls) {
JSONObject jsonObj = null;
Log.d("TAG","inside doInBackground..");
try {
URL url = new URL("http://daytonamk.clubspeedtiming.com/api/index.php/races/scoreboard.json?track_id=1&key=cs-dev" + kartNumber);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
BufferedInputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String result = convertInputStreamToString(inputStream);
parseResult(result);
Log.e("Message", "This is a message");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObj;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
String result = "";
{
while ((line = bufferedReader.readLine()) != null) {
builder.append( line);
}
return result;
}
}
private JSONObject parseResult(String result) {
JSONObject jsonObj = null;
if (result == null) {
Toast.makeText(Main_Activity.this, "Race not currently running", Toast.LENGTH_LONG).show();
} else {
try {
int number = 0;
jsonObj = new JSONObject("result");
JSONObject race = jsonObj.getJSONObject("race");
int durationInMins = race.getInt("duration");
String win_by = race.getString("win_by");
JSONArray scoreboard = jsonObj.getJSONArray("scoreboard");
Log.d("TAG", "Json value :" + scoreboard);
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
number = data.getInt("kart_num");
while (kartNumber == number) {
int gridPosition = data.getInt("position");
int gap = data.getInt("gap");
int lastLapTime = data.getInt("last_lap_time");
int bestLapTime = data.getInt("fastest_lap_time");
int raceInTime = race.getInt("race_time_in_seconds");
duration = durationInMins * 60 - raceInTime;
if (!(gridPosition == 1)) {
JSONObject dataPreviousGap = scoreboard.getJSONObject(i - 1);
int gapPrev = dataPreviousGap.getInt("gap");
gapUp = gap - gapPrev;
}
if (!(i == scoreboard.length() - 1)) {
JSONObject dataNext = scoreboard.getJSONObject(i + 1);
int gapNext = dataNext.getInt("gap");
gapDown = gapNext - gap;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObj) {
Intent myIntent = new Intent(Main_Activity.this, Display_Activity.class);
try {
JSONObject jsonObje = new JSONObject("result");
JSONArray scoreboard = jsonObje.getJSONArray("scoreboard");
for (int i = 0; i < scoreboard.length(); i++) {
JSONObject data = scoreboard.getJSONObject(i);
myIntent.putExtra("GridPosition", data.getInt("position"));
myIntent.putExtra("LastLapTime", data.getInt("last_lap_time"));
myIntent.putExtra("MinutesToGo", duration);
myIntent.putExtra("BestLapTime",data.getInt("fastest_lap_time"));
myIntent.putExtra("GapUp", gapUp);
myIntent.putExtra("GapDown", gapDown);
}
Just as your logcat reads org.json.JSONException: Value result of type java.lang.String cannot be converted to JSONObject
Log the response you are getting without parsing the data first. Then you may find out what data types you are dealing with eg: Strings, Integers, Floats,etc.
Post the response here for more help.
EDIT:
This line here jsonObj = new JSONObject("result");
Do this instead jsonObj = new JSONObject(result);
EDIT:
jsonObj = new JSONObject(result);
JSONObject obj = jsonObj.getJSONObject("race");
String id = obj.getString("id");
//do the same for all objects inside race
How i can convert my code into "utf-8"?i have a text file which name is "textarabics.txt"
and this text file contains utf-8 characters..below is my code please suggest me how i can convert into utf-8?
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
String jsonStr = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
jsonStr = Charset.defaultCharset().decode(bb).toString();
Log.d("Noga Store", "jString = " + jsonStr);
}
finally {
stream.close();
}
Log.d("Noga Store", "jString = " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting data JSON Array nodes
JSONArray data = jsonObj.getJSONArray("data");
// looping through All nodes
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
// String duration = c.getString("duration");
int duration = c.getInt("duration");
// tmp hashmap for single node
/* HashMap<String, String> parsedData = new HashMap<String, String>();
// adding each child node to HashMap key => value
parsedData.put("id", id);
parsedData.put("title", title);
parsedData.put("duration", duration);*/
textnames.add(title);
textduration.add(duration);
// textnames.add(duration);
// do what do you want on your interface
}
} catch (Exception e) {
e.printStackTrace();
}
This is my "textarabics.txt" file
{
"data": [
{
"id": "1",
"title": "تخطي نوجا نوجا أخبار واستعراض السوق",
"duration": 10
},
{
"id": "2",
"title": "أحدث نوجا الأخبار وآخر المستجدات",
"duration": 3
},
{
"id": "3",
"title": "نوجا الأخبار وآخر المستجدات",
"duration": 5
},
{
"id": "4",
"title": "لا تحتوي على تطبيقات وجد نوع الكلمة",
"duration": 7
},
{
"id": "5",
"title": "تحتاج إلى إعادة تشغيل التطبيق لاتخاذ تغييرات الخط. هل تريد إعادة التشغيل الآن",
"duration": 4
}
]
}
Instead of using Charset.defaultCharset() you can use Charset.forName("UTF-8"). Also you are missing a JSONTokener that you should use with your input. This is based on your code:
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
String jsonStr = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
jsonStr = Charset.forName("UTF-8").decode(bb).toString();
Log.d("Noga Store", "jString = " + jsonStr);
}
finally {
stream.close();
}
Log.d("Noga Store", "jString = " + jsonStr);
// A JSONTokener is needed in order to use JSONObject correctly
JSONTokener jsonTokener = new JSONTokener(jsonStr);
// Pass a JSONTokener to the JSONObject constructor
JSONObject jsonObj = new JSONObject(jsonTokener);
// Getting data JSON Array nodes
JSONArray data = jsonObj.getJSONArray("data");
// looping through All nodes
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
// String duration = c.getString("duration");
int duration = c.getInt("duration");
// tmp hashmap for single node
/* HashMap<String, String> parsedData = new HashMap<String, String>();
// adding each child node to HashMap key => value
parsedData.put("id", id);
parsedData.put("title", title);
parsedData.put("duration", duration);*/
textnames.add(title);
textduration.add(duration);
// textnames.add(duration);
// do what do you want on your interface
}
} catch (Exception e) {
e.printStackTrace();
}
A more efficient way of dealing with the file would be to wrap the FileInputStream in a InputStreamReader and using InputStreamReader with charset constructor appending the characters to read to a StringBuffer.
Another solution - working on Android 11+ is
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
try {
JsonReader jsonReader = new JsonReader(reader);
jsonReader.beginObject();
jsonReader.nextName();
jsonReader.beginArray();
while (jsonReader.hasNext()) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equalsIgnoreCase("id")) {
String id = jsonReader.nextString();
// use the id parameter in some way
System.out.println("id = " + id);
}
if (name.equalsIgnoreCase("title")) {
String title = jsonReader.nextString();
// use the title parameter in some way
System.out.println("title = " + title);
}
if (name.equalsIgnoreCase("duration")) {
// use the duration parameter in some way
int duration = jsonReader.nextInt();
System.out.println("duration = " + duration);
}
}
jsonReader.endObject();
}
jsonReader.endArray();
jsonReader.endObject();
} finally {
try {
if (reader != null) {
reader.close();
}
reader = null;
} catch (Exception e) {
// TODO: handle exception
}
try {
if(stream != null) {
stream.close();
}
stream = null;
} catch (Exception e) {
// TODO: handle exception
}
}
} catch (Exception e) {
e.printStackTrace();
}