{
"batchcomplete": "",
"query": {
"pages": {
"25675557": {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
}
}
}
this is the code I tried :
public void getJSON(final String city) throws JSONException {
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + city);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null) {
json.append(tmp).append("\n");
}
reader.close();
data = new JSONObject(json.toString());
if (data.getInt("cod") != 200) {
System.out.println("Cancelled");
return null;
}
} catch (Exception e) {
System.out.println("Exception " + e.getMessage());
return null;
}
return null;
}
#Override
protected void onPostExecute(Void Void) {
if (data != null) {
Log.d("my weather received", data.toString());
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
// JSONArray idArray = pagesArray.getJSONArray(0);
//JSONArray idArray = pagesArray.get(0);
System.out.println(pagesArray);
JSONObject obj = pagesArray.getJSONObject(0);
System.out.println(obj);
//JSONObject weatherarray = data.getJSONObject("pages");
//JSONObject weather = weatherarray.getJSONObject(0);
// final String des = weather.getString("description");
/*for (int i = 0; i < forecastArray.length(); i++) {
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("main");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
}*/
System.out.println("Temp Value : "+" : ");
runOnUiThread(new Runnable() {
#Override
public void run() {
textvw.setText("");
}
});
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
}
}
}.execute();
}
The exception is because the response does not contain JSON Array. Change your
JSONArray pagesArray = forecastArray.getJSONArray("pages");
to
JSONObject pagesArray = forecastArray.getJSONObject("pages");
and I believe that you're trying to get keys which are dynamic. You cloud get the objects using JSONObject.getKeys() like below.
Iterator keys = pagesArray.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject jObj = pagesArray.getJSONObject(dynamicKey);
//Get other attributes by jObj.getString() method.
}
Try and let me know if it works.
The error is clear enough. you try to assign a JSONobject to a JSONArray
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Replace by
JSONObject pagesArray = forecastArray.JSONObject("pages");
the data of a JSONArray are between [] and not {}.
your error is in :
JSONArray pagesArray = forecastArray.getJSONArray("pages");
Your problem is that you getJSONArray while pages are a JsonObject in your data .if your "pages" is a array in your data you must send it in [] from server like this:
{
"batchcomplete": "",
"query": {
"pages": [ {
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
},
{
"pageid": 25675557,
"ns": 0,
"title": "Cricket",
"extract": "Cricket is a bat-and-ball game played between two teams of eleven players each on a cricket field, at the centre of which is a rectangular 22-yard-long (20 metres) pitch with a target at each end called the wicket (a set of three wooden stumps upon which two bails sit). "
}
]
}
}
and in android :
try {
//JSONObject forecastJson = new JSONObject(data);
JSONObject forecastArray = data.getJSONObject("query");
System.out.println(forecastArray);
JSONArray pagesArray = forecastArray.getJSONArray("pages");
System.out.println(pagesArray);
for (int k = 0; k < pagesArray.length(); k++) {
try {
JSONObject object = pagesArray.getJSONObject(k);
String pageid = object.getString("pageid");
String ns = object.getString("ns");
String title = object.getString("title");
String extract = object.getString("extract");
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Log.e("GetFeedTask", "Error:" + e.getMessage());
}
Related
I am trying to fetch videos from a channel's playlist. There are 132 videos but I cant fetch more than 50 videos.
I know that nextPageToken has to be fetched and passed along with url?
This is my first time working with api.
This is how I am able to fetch 50 videos.
Edit
private static String GOOGLE_YOUTUBE_API_KEY = "<API Key>";
private static String CHANNLE_GET_URL="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PL-nbe4FPvDBElyW0Iww5suxJqqmuGBgIH&key="+GOOGLE_YOUTUBE_API_KEY;
public ArrayList<YoutubeDataModel> parseVideoListFromResponse(JSONObject jsonObject) {
ArrayList<YoutubeDataModel> mList = new ArrayList<>();
if (jsonObject.has("items")) {
try {
JSONArray jsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
if (json.has("id")) {
JSONObject jsonID = json.getJSONObject("id");
String video_id = "";
if (jsonID.has("videoId")) {
video_id = jsonID.getString("videoId");
}
if (jsonID.has("kind")) {
if (jsonID.getString("kind").equals("youtube#video")) {
YoutubeDataModel youtubeObject = new YoutubeDataModel();
JSONObject jsonSnippet = json.getJSONObject("snippet");
String title = jsonSnippet.getString("title");
String description = jsonSnippet.getString("description");
String publishedAt = jsonSnippet.getString("publishedAt");
String thumbnail = jsonSnippet.getJSONObject("thumbnails").getJSONObject("high").getString("url");
youtubeObject.setTitle(title);
youtubeObject.setDescription(description);
youtubeObject.setPublishedAt(publishedAt);
youtubeObject.setThumbnail(thumbnail);
youtubeObject.setVideo_id(video_id);
mList.add(youtubeObject);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mList;
}
Edit 2:
Added the following but it is not fetching any value.
try {
// String data=null;
JSONObject reader = new JSONObject();
String next_Page_Token = reader.getString("nextPageToken");
Log.d("NextPAgeToken", "NpT"+next_Page_Token);
}
catch (JSONException e)
{
Log.e("Error", "Error is "+e.getMessage());
Toast.makeText(getApplicationContext(),"No next page found", Toast.LENGTH_LONG).show();
}
You need to add one extra query parameter pageToken like below
private static String CHANNLE_GET_URL =
"https://www.googleapis.com/youtube/v3/playlistItems" +
"?part=snippet" +
"&maxResults=50" +
"&playlistId=PL-nbe4FPvDBElyW0Iww5suxJqqmuGBgIH" +
"&key="+GOOGLE_YOUTUBE_API_KEY +
"pageToken=" + NEXT_PAGE_TOKEN;
//Pass like this one
"https://www.googleapis.com/youtube/v3/search?part=snippet&order=date&channelId=UC2LrGJYe_uzI3FBj05BuvLA&key=AIzaSyBlj1dJ9txGcXOOblCJuQ0iwIkhUCgVt1Y&maxResults=50&pageToken=CJYBEAA"
and when you get data, you need to update NEXT_PAGE_TOKEN by fetching value from nextPageToken.
You will get data as
{
"kind": "youtube#searchListResponse",
"etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/MgcKz6rwie5hyKKWdwMChcXzNzU\"",
"nextPageToken": "CJYBEAA",
"prevPageToken": "CGQQAQ",
"regionCode": "IN",
"pageInfo": {
"totalResults": 184,
"resultsPerPage": 50
},
"items": [...]
}
So, convert this data into JSONObject as
JSONObject mainObject = new JSONObject(data);
NEXT_PAGE_TOKEN = mainObject.getString("nextPageToken");
...//Rest your task here
This works fine.
I have received a string value from JSON, but when I add that JSON value to a JSON array it gives an error stating that it can not convert String value to JSONArray. Please help me.
In the response there are a 3 values in "Value"
protected class AsyncMenuRate extends
AsyncTask<ForGettingRate, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onPostExecute(JSONObject objects) {
try {
//String ss= objects.getString("Value").;
JSONArray jarray=objects.getJSONArray("Value");
//jarray = new JSONArray(ss);
for (int i = 0; i < jarray.length(); i++) {
jsonObj = jarray.getJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
This is a function that I have return value:
String menuTotal = "0";
String item_rate;
public String MenuRate(int t_id, String menunameoflist) {
if (dbConnection.State.ToString() == "Closed") {
dbConnection.Open();
}
if (db.ChkDb_Value("select * from table_status where table_type='" + "A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select rate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else if (db.ChkDb_Value("select * from table_status where table_type='" + "Non A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select non_ACrate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else
item_rate = db.getDb_Value("select driverRate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
//menuRate = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return item_rate;
}
This is the JSON format:
{
"name": "MenuRate",
"parameters": [
{
"name": "t_id",
"type": "int32"
},
{
"name": "menunameoflist",
"type": "string"
}
],
"returnvalue": "string"
}
This is function that I have get a response from JSON:
public JSONObject MenuRate(int t_id, String menunameoflist) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuRate");
p.put("t_id",mapObject(t_id));
p.put("menunameoflist",mapObject(menunameoflist));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
First your MenuRate method returns String not JSONObject. So you had to get that as String and convert it into JSONObject, as shown below.
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
String jsonString = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
return new JSonObject(jsonString);
} catch (Exception | JsonException e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
Don't forgot to add the JsonException, no problem some how it will ask to add the exception.
Now the string value is converted to JSON, so now you can fetch the values and while fetching use opt instead of get like optJsonArray("key") instead of getJsonArray("key") by this way we will get null value instead of exception, if the key is not present in the JSON.
Now coming to the "value" key access in your JSON response. Below is the JSON value which you have provided,
{
"name": "MenuRate",
"parameters": [{
"name": "t_id",
"type": "int32"
}, {
"name": "menunameoflist",
"type": "string"
}],
"returnvalue": "string"
}
In your question you have mentioned that you need access a json array with the key "Value". But in this there is no array with key "Value". So the below code will explain you how to access the "name" string value and "parameters" Json array.
try {
//Name String value...
String name = objects.optString("name");
//Parameter Json Array...
JSONArray parameterarray =objects.optJSONArray("parameters");
for (int i = 0; i < parameterarray.length(); i++) {
JsonObject jsonObj = parameterarray.optJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this is helpful :)
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
I want to get two json array from remote url
I am using AsyncTask to do that but i can't get any data !
#Override
protected Void doInBackground(String... params) {
try {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(params[0]);
// Getting Array of Contacts
data = new JSONArray(json);
JSONArray cities = data.getJSONArray();
// looping through All cities
for (int i = 0; i < cities.length(); i++) {
JSONObject e = cities.getJSONObject(i);
String ci_name = e.getString("ct_name");
String ci_web_id = e.getString("ct_id");
db.addCity(ci_name, ci_web_id);
db.closeDatabase();
}
JSONArray districts = data.getJSONArray(1);
// looping through All districts
for (int i = 0; i < districts.length(); i++) {
JSONObject e = districts.getJSONObject(i);
String di_name = e.getString("ar_name");
String di_web_id = e.getString("ar_id");
db.addDistrict(di_name, di_web_id);
db.closeDatabase();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The return data is like that :
{"city":[
{"ct_id":"1432","ct_name":"\u062e\u0645\u064a\u0633 \u0645\u0634\u064a\u0637","ct_hide":"0","ct_ord":"0","ct_created":"0"},
{"ct_id":"1434","ct_name":"\u0639\u0633\u064a\u0631","ct_hide":"0","ct_ord":"0","ct_created":"0"},{"ct_id":"1435","ct_name":"\u0627\u0644\u0645\u0646\u0637\u0642\u0629 \u0627\u0644\u0634\u0631\u0642\u064a\u0629","ct_hide":"0","ct_ord":"0","ct_created":"0"}
], "area":[
{"ar_id":"1422","ar_name":"\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0647","ar_hide":null,"ar_ord":null,"ar_created":null}, {"ar_id":"1433","ar_name":"\u0646\u062c\u0631\u0627\u0646","ar_hide":null,"ar_ord":null,"ar_created":null}]
}
Your json is a JSONObject not a JSONarray.
This
data = new JSONArray(json);
is wrong.
{ // json object node
"city": [ // json array city
{ // json object
"ct_id": "1432",
"ct_name": "خميس مشيط",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1434",
"ct_name": "عسير",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1435",
"ct_name": "المنطقة الشرقية",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
}
],
"area": [ // json array area
{
"ar_id": "1422",
"ar_name": "المدينة المنوره",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
},
{
"ar_id": "1433",
"ar_name": "نجران",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
}
]
}
To parse
JSONObject jb = new JSONObject(json);
JSONArray city = jb.getJSONArray("city");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 = city.getJSONObject(i);
String id = jb1.getString("ct_id");
String name = jb1.getString("ct_name");
String hide = jb1.getString("ct_hide");
String ord = jb1.getString("ct_ord");
String created = jb1.getString("ct_ord");
Log.i("city id is",id);
}
JSONArray area = jb.getJSONArray("area");
for(int i=0;i<area.length();i++)
{
JSONObject jb1 = area.getJSONObject(i);
String id = jb1.getString("ar_id");
String name = jb1.getString("ar_name");
String hide = jb1.getString("ar_hide");
String ord = jb1.getString("ar_ord");
String created = jb1.getString("ar_ord");
Log.i("Area id is",id);
}
You could also consider using gson to parse json to java objects
http://code.google.com/p/google-gson/
I don't see any request to remote url. How do you get data from your server?
Generally, it looks like this:
public void execute() {
final AndroidHttpClient client = AndroidHttpClient.newInstance("TAG");
try {
HttpUriRequest request = getRequest();
HttpResponse response = client.execute(request);
final int code = response.getStatusLine().getStatusCode();
Log.d("TAG", "Server returns " + code);
if (code == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
handleResult(json);
}
} catch (IOException e) {
Log.e("TAG", "Failed to execute response", e);
}
}
private void handleResult(String json) {
try {
JSONObject jObject = new JSONObject(json);//your response is not an array
JSONArray content = jObject.getJSONArray("city")
final int count = content.length();
for (int i = 0; i < count; i++) {
JSONObject city = content.getJSONObject(i);
Log.d("TAG", city.getString("ct_id"));
}
} catch (JSONException e) {
Log.e("TAG", "Failed to obtain json", e);
}
}
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();
}