I try to get xml data then I parse it to JSON, I use OkHttp as a connection. I managed to get data from LOG but I can't display it in my RecyclerView, when I LOG to adapter and the result is size 0
I set the response to the model and sharedpreference
The point of the problem is that I just don't understand how to take the response from the presenter then I set it to the adapter in the main Fragment.
public class ParentCategories {
#SerializedName("idkategori")
#Expose
private String idkategori;
#SerializedName("namakategori")
#Expose
private String namakategori;
#SerializedName("fileicon")
#Expose
private String fileicon;
#SerializedName("subkategori")
#Expose
private SubCategories subkategori;
public ParentCategories(Parcel in) {
this.idkategori = in.readString();
this.namakategori = in.readString();
this.fileicon = in.readString();
}
public ParentCategories() {
}
public String getIdkategori() {
return idkategori;
}
public void setIdkategori(String idkategori) {
this.idkategori = idkategori;
}
public String getNamakategori() {
return namakategori;
}
public void setNamakategori(String namakategori) {
this.namakategori = namakategori;
}
public String getFileicon() {
return fileicon;
}
public void setFileicon(String fileicon) {
this.fileicon = fileicon;
}
public SubCategories getSubkategori() {
return subkategori;
}
public void setSubkategori(SubCategories subkategori) {
this.subkategori = subkategori;
}
}
public class CategoriesPresenter {
....
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
JSONObject jsonObj = null;
try {
jsonObj = XML.toJSONObject(mMessage);
JSONObject jsonObject = new JSONObject(jsonObj.toString());
JSONObject object = jsonObject.getJSONObject("posh");
String attr2 = object.getString("resultcode");
com.davestpay.apphdi.helper.Log.d("hasil", String.valueOf(object));
if (attr2.equalsIgnoreCase("0000")) {
String idAgen = object.getString("idagen");
int jumlahKategori = object.getInt("jumlahkategori");
JSONArray category = object.getJSONArray("kategori");
List<ParentCategories> parentCategories = new ArrayList<ParentCategories>();
for (int i = 0; i < category.length(); i++) {
ParentCategories categories = new ParentCategories();
JSONObject c = category.getJSONObject(i);
Log.d(TAG, "onResponseC: "+c);
String idKategori = c.getString("idkategori");
String namaKategori = c.getString("namakategori");
Log.d(TAG, "onResponseNamaKategori: "+namaKategori);
String fileIcon = c.getString("fileicon");
JSONObject subCategories = c.getJSONObject("subkategori");
JSONArray subCategory = subCategories.getJSONArray("kategori2");
Log.d(TAG, "onResponseSubCategories: "+subCategory);
for (int subCatPosition = 0; subCatPosition < subCategory.length(); subCatPosition++) {
SecondCategories secondCategories = new SecondCategories();
List<SecondCategories> listSecondCategories = new ArrayList<>();
JSONObject sc = subCategory.getJSONObject(subCatPosition);
String secIdKategori = sc.getString("idkategori");
String secNamaKategori = sc.getString("namakategori");
String secFileIcon = sc.getString("fileicon");
secondCategories.setIdkategori(secIdKategori);
secondCategories.setNamakategori(secNamaKategori);
secondCategories.setFileicon(secFileIcon);
listSecondCategories.add(secondCategories);
}
categories.setIdkategori(idKategori);
categories.setNamakategori(namaKategori);
categories.setFileicon(fileIcon);
parentCategories.add(categories);
Log.d(TAG, "onResponseFinalCategories: "+parentCategories);
}
iCategories.onSuccessCategories(parentCategories);
preferenceHelper.clear(PreferenceHelper.CATEGORIES);
preferenceHelper.putList(PreferenceHelper.CATEGORIES, parentCategories);
} else {
Log.d(TAG, "onResponse: ");
}
} catch (JSONException e) {
com.davestpay.apphdi.helper.Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
}
}
private void getInit() {
if (preferenceHelper != null) {
idAgen = preferenceHelper.getString(PreferenceHelper.ID_AGEN);
namaAgen = preferenceHelper.getString(PreferenceHelper.NAMA_AGEN);
password = preferenceHelper.getString(PreferenceHelper.PASSWORD);
categories = preferenceHelper.getList(PreferenceHelper.CATEGORIES, ParentCategories[].class);
}
authPresenter = new AuthPresenter(getContext());
presenter = new CategoriesPresenter();
presenter.setBaseView(this);
presenter.onCreate(getContext());
if (authPresenter.isLoggedIn()) {
// kategori.setText(categories.toString());
presenter.getCategories(idAgen, password, counter);
}
kategori = mView.findViewById(R.id.kategori);
categories = new ArrayList<>();
rvMain = mView.findViewById(R.id.rv_categories);
adapter = new CategoriesListViewAdapter(getContext(), categories);
layoutManager = new LinearLayoutManager(getdActivity());
adapter.notifyDataSetChanged();
rvMain.setLayoutManager(layoutManager);
rvMain.setAdapter(adapter);
}
This is the problem.
categories = new ArrayList<>();
Here, you are initialising categories to new ArrayList<>(); It is like you are creating a new arraylist.
Just remove this line.
Related
I need to retrieve data to listview from this link http://www.autotrack.rs/android_juzna_backa/get_voznja.php?. I need to send key, with value-POST method, to get something like this: http://www.autotrack.rs/android_juzna_backa/get_voznja.php?voznja_id=42. My code is bellow: Thanks. ERROR Value null at data of type org.json.JSONObject$1 cannot be converted to JSONArray
public class fetchData extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
super.onPreExecute();
swipeRefresh.setRefreshing(true);
}
#Override
protected String doInBackground(String... params) {
arrayList.clear();
String result = null;
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("voznja_id", "42")
.build();
Request request = new Request.Builder()
.url("http://www.autotrack.rs/android_juzna_backa/get_voznja.php")
.method("POST", body)
.build();
try {
response = client.newCall(request).execute();
// System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
public void onPostExecute(String rezultat) {
try {
rezultat = response.body().string();
}catch (Exception m)
{
m.printStackTrace();
}
Intent intent;
Gson gson = new Gson();
Type type = new TypeToken<Voznja>() {
}.getType();
Voznja voznja = gson.fromJson(rezultat, type);
Intent im = new Intent(getApplicationContext(), Unos.class);
im.putExtra("voznja", voznja);
// startActivity(im);
swipeRefresh.setRefreshing(false);
try {
JSONObject object = new JSONObject(rezultat);
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
VoznjaAdapter adapter = new VoznjaAdapter(ListaVoznji.this, arrayList);
listView.setAdapter(adapter);
Your api response is JSONObject.
{"data":{"id":"42","vozilo_id":"777777003561","vozac_id":"2","pocetna_kilometraza":"50000","pocetno_vreme":"2020-12-25 07:15:00","projekat":null,"razlog":"Sastanak","zavrsna_kilometraza":"50150","zavrsno_vreme":"2020-12-25 10:45:00","moto_sati":"3","insert_time":"2021-01-08 10:47:33.683885","id_projekat_jb":"330"}}
So you should use JSONObject instead JSONArray
try {
JSONObject object = new JSONObject(rezultat);
JSONObject jsonObject = object.getJSONObject("data");
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
I want to display two data on listview through the json input. All the code are alter from internet which I got error. I have not clear logic to understand the meaning of the code. Please give me advice and alter my code.
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String, ActivityInfo>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject ;
ArrayList<HashMap<String, ActivityInfo>> arrayList = new ArrayList<HashMap<String, ActivityInfo>>();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
ActivityInfo activityInfo =new ActivityInfo();
activityInfo.eventName = jsonObjRow.getString("eventName");
activityInfo.date = jsonObjRow.getString("date");
HashMap<String, String> map= new HashMap<String, ActivityInfo>();
map.put("eventName", activityInfo.eventName );
map.put("date", activityInfo.date);
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
for (int j=0;j<jsonArray2.length();j++) {
JSONObject jsonObjRow2 = jsonArray2.getJSONObject(j);
activityInfo.review = jsonObjRow2.getString("review");
}
arrayList.add(activityInfo);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}
ActivityInfo class (using the serializable to got the result )
public class ActivityInfo implements Serializable {
String eventName;
String date ;
public void setEventName(String eventName){
this.eventName =eventName ;
}
public String toString(){
return this.eventName;
}
}
Json Response is no problem
{
"article":[
{
"activityId":"5c5d8addd404c",
"eventName":"running",
"date":"2019-02-08",
"content":[
{
"review":"you there"
},
{
"review":"please go away"
},
]
},
{
"activityId":"5c5d8b318df62",
"eventName":"basketball",
"date":"2019-02-13",
"content":[
{
"review":"confirm again"
}
]
},
{
"activityId":"5c5d8b9308018",
"eventName":"playing",
"date":"2019-02-16",
"content":[
{
"review":"provid of you"
}
]
}
]
}
I totally do it like this:
public class menuCreation()
{
public string Category { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
public string FileName { get; set; }
public menuCreation[] Arr { get; set; }
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string json = (reader.ReadToEnd());
List<menuCreation> items = JsonConvert.DeserializeObject<List<menuCreation>>(json);
Arr = items.ToArray();
}
menuCreation mc = new menuCreation();
foreach (var item in mc.Arr)
{
PictureBox pb = new PictureBox();
pb.Tag = item.ItemName;
pb.Name = item.Price;
}
You can see, I reach itemName with class object.So, you can add listview with this method.
This is your Model Class..
ActivityInfo.java
public class ActivityInfo implements Serializable {
String eventName;
String date;
public void setEventName(String eventName){
this.eventName = eventName ;
}
public String getEventName(){
return this.eventName;
}
public void setDate(String date){
this.date = date;
}
public String getDate(){
return date;
}
}
This will be your final errorfree code..
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String,String>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject;
ArrayList<HashMap<String,String>> arrayList = new ArrayList();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
HashMap<String,String> hashMap=new HashMap<>();//create a hashmap to store the data in key value pair
hashMap.put("eventName",jsonObjRow.getString("eventName"));
hashMap.put("date",jsonObjRow.getString("date"));
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
/*If you want to get Content Reviews from Json, you need to make another attributes like Content in ActivityInfo Class*/
arrayList.add(hashmap);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}
I am trying to populate the recycler view using json data from dummy api but it is not working. I have tried almost several solutions given in stack overflow.
Here is my code below:
public class loadOrdersList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
ordersList = new ArrayList<>();
rvor = findViewById(R.id.recycler_view_orders);
rvor.setHasFixedSize(true);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
}
#Override
protected void onPostExecute(Void aVoid) {
if (new CheckNetworkUtil(OrdersActivity.this).isNetworkAvailable()) {
Log.d("TEST", "------------------ordersList: " + ordersList.size());
OrdersAdapter adapter = new OrdersAdapter(getApplicationContext(), ordersList);
rvor.setAdapter(adapter);
srl.setRefreshing(false);
} else
Toast.makeText(OrdersActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(Void... voids) {
try {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url("https://api.myjson.com/bins/la2gh")
.build();
Response responses = client.newCall(request).execute();
JSONArray orders = new JSONArray(responses.body().string());
ordersList = new ArrayList<>();
for (int i = 0; i < orders.length(); i++) {
JSONObject name = orders.getJSONObject(i);
String customerName = name.getString("customer_name");
String agentAssigned = name.getString("agent_assigned");
String orderId = name.getString("order_id");
Integer totalQuantity = name.getInt("total_quantity");
String orderDate = name.getString("order_date");
Integer orderNo = name.getInt("order_no");
String schoolYear = name.getString("school_year");
String company = name.getString("company");
String deliveryDate = name.getString("delivery_date");
String orderStatus = name.getString("order_status");
Integer grossRevenue = name.getInt("gross_revenue");
Integer netRevenue = name.getInt("net_revenue");
Integer totalOrdered = name.getInt("total");
Integer grandTotalOrdered = name.getInt("grand_total");
OrderModel orderModel = new OrderModel(customerName
,agentAssigned
,orderId
,totalQuantity
,orderDate
,orderNo
,schoolYear
,company
,deliveryDate
,orderStatus
,grossRevenue
,netRevenue
,totalOrdered
,grandTotalOrdered);
ordersList.add(orderModel);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
I suspected that integer is not supported by the string during execution.
You are expecting order_no to be an Integer and thus written this
Integer orderNo = name.getInt("order_no");
But you are receiving an alphanumeric value for orderNo in recycler view.
So either you have to change the type of orderNo property of OrderModel from Integer to String or restrict values to Integer type only.
I would like to combine two separate parsed jsonObjects into a single arraylist, then display the results as Strings?
I would like to store summaryJsonObject & segment in storylineData. When I step through the code using the debugger summaryJsonObject & segment both hold the raw json. The raw json data also shows in the logcat but storylineData remains null & unavailable throughout.
Here is the parsing code.
public class StorylineData {
private static String date;
private ArrayList<SummaryData> summary;
private ArrayList<SegmentData> segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public ArrayList<SummaryData> getSummary() {
return summary;
}
public ArrayList<SegmentData> getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(ArrayList<SummaryData> summary) {
this.summary = summary;
}
public void setSegments(ArrayList<SegmentData> segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = new ArrayList<SummaryData>();
storylineData.segments = new ArrayList<SegmentData>();
JSONArray summariesJsonArray= jsonObject.optJSONArray("summary");
if (summariesJsonArray != null) {
for (int i = 0; i < summariesJsonArray.length(); i++) {
JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
if (summaryJsonObject != null) {
storylineData.summary.add(SummaryData.parse(summaryJsonObject));
Log.d("storylineHandler", summaryJsonObject.toString());
}
}
}
JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
if (segmentsJsonArray != null) {
for (int i = 0; i < segmentsJsonArray.length(); i++) {
JSONObject segment = segmentsJsonArray.optJSONObject(i);
if (segment != null) {
storylineData.segments.add(SegmentData.parse(segment));
Log.d("storylineHandler", segment.toString());
}
}
}
return storylineData;
}
return null;
}
}
The MainActivity looks like this:
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener{
..other variables here..
List<StorylineData> storylineData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...other ui elements here...
mEditTextResponse = (TextView) findViewById(R.id.editResponse);
storylineData = new StorylineData();
MovesAPI.init(this, CLIENT_ID, CLIENT_SECRET, CLIENT_SCOPES.....
#Override
public void onClick(View v) {
toggleProgress(true);
switch (mSpinnerAPI.getSelectedItemPosition()) {
... other cases here...
break;
...other cases here...
case 4: // Get Summary Day
MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
break;
Other cases here..
case 10: // Get Storyline Day
MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", null, false);//Date changed to "20150418"
break;
...Other cases here..
}
}
... Other MovesHandlers here...
private JSONObject summaryJsonObject;
private List<StorylineData> storylineList;
private JSONObject summariesJsonArray;
private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() {
#Override
public void onSuccess(ArrayList<StorylineData> result) {
toggleProgress(false);
storylineList = (List<StorylineData>) StorylineData.parse(summaryJsonObject);
updateResponse( + storylineData.toString() + "\n" //displays true to layout view
result.add(StorylineData.parse(summariesJsonArray))+ "\n"
+Log.d("call result", result.toString()) + "\n" //displays 60 in layout view & com.protogeo.moves.demos.apps.storyline.StorylineData#52824f88, null]
+ Log.d("Log.d storylineHandler", storylineHandler.toString()) + "\n" ); //returns 78 in layout view & com.protogeo.moves.demos.apps.Mainactivity#234234 to log cat
onFailure code here..
}
};
public void toggleProgress(final boolean isProgrressing) {
togglePregress code here..
}
public void updateResponse(final String message) {
runOnUiThread(new Runnable() {
public List<StorylineData> storylineList;
#Override
public void run() {
mEditTextResponse.setText(message);
if (storylineData!= null) {
for (StorylineData storylineData : storylineList) {
mEditTextResponse.append(("storylineData" + storylineData.toString()));
}
}
}
});
}
}
HttpClass
public static void getDailyStorylineList(final MovesHandler<JSONArray> handler,
final String specificSummary,
final String from,
final String to,
final String pastDays,
final String updatedSince,
final boolean needTrackPoints) {
new Thread(new Runnable() {
#Override
public void run() {
try {
/* Refresh access token if only AuthData.MOVES_REFRESHBEFORE days are there to expire current token */
AuthData.refreshAccessTokenIfNeeded();
/* Exchange the authorization code we obtained after login to get access token */
HashMap<String, String> nameValuePairs = new HashMap<String, String>();
nameValuePairs.put("access_token", AuthData.getAuthData().getAccessToken());
// if (specificSummary != null && specificSummary.length() > 0) nameValuePairs.put("specificSummary", specificSummary);//att
if (from != null && from.length() > 0) nameValuePairs.put("from", from);
if (to != null && to.length() > 0) nameValuePairs.put("to", to);
if (pastDays != null && pastDays.length() > 0) nameValuePairs.put("pastDays", pastDays);
if (updatedSince != null && updatedSince.length() > 0) nameValuePairs.put("updatedSince", updatedSince);
if (needTrackPoints) nameValuePairs.put("trackPoints", "true");
URL url = new URL(MovesAPI.API_BASE + MovesAPI.API_PATH_STORYLINE + (specificSummary != null ? specificSummary : "") + "?" + Utilities.encodeUrl(nameValuePairs));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
if (urlConnection.getResponseCode() != 200) {
/* All other HTTP errors from Moves will fall here */
handler.onFailure(getErrorStatus(Utilities.readStream(urlConnection.getErrorStream()), urlConnection.getResponseCode()), "Server not responded with success ("+ urlConnection.getResponseCode() +")");
return;
}
String response = Utilities.readStream(urlConnection.getInputStream());
Object object = new JSONTokener(response).nextValue();
if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
ArrayList<StorylineData> storylineData = new ArrayList<StorylineData>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject storylineJsonObject = jsonArray.optJSONObject(i);
if (storylineJsonObject != null) {
storylineData.add(StorylineData.parse(storylineJsonObject));
}
}
}
handler.onSuccess(storylineData);
} else {
handler.onFailure(MovesStatus.INVALID_RESPONSE, "Expected a JSONArray from server, but failed");
}
} catch (Exception ex) {
ex.printStackTrace();
handler.onFailure(MovesStatus.UNEXPECTED_ERROR, "An unexpected error occured, please check logcat");
}
}
}).start();
}
MovesHandler
public interface MovesHandler<T> {//T stands for generic type
/**
* Implement this method to get success notifications along with the result
* #param result : Result of the operation completed with this handler
*/
public void onSuccess(ProfileData result);
/**
* Implement this method to get failure notifications along with the {#link MovesStatus} code and a brief message
* #param status : Status code of the failure
* #param message : A brief message about the reason behind failure
*/
public void onFailure(MovesStatus status, String message);
}
If you wanted to have one ArrayList to store both SummaryData and SegmentData, you could just created an ArrayList of Objects, ArrayList<Object>. This would be the more general solution.
The alternative would be having SummaryData and SegmentData inherit the same class or implement the same interface.
Using an extended class, you could have:
class Data {
}
class SegmentData extends Data {
}
class SummaryData extends Data {
}
You could then have an ArrayList that would be able to add both SegmentData and SummaryData objects.
If you wanted to show each item as a String you would need to loop through the list and call the toString() function of each item
ArrayList<Data> dataList;
for (Data d : dataList) {
Log.d("data", d.toString())
}
Just make sure to overwrite the toString() function in SegmentData and SummaryData
EDIT: Showing how to print JsonArray
If you wanted to just print for JsonArrays, you could:
public class StorylineData {
private static String date;
private JSONArray summary;
private JSONArray segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public JSONArray getSummary() {
return summary;
}
public JSONArray getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(JSONArray summary) {
this.summary = summary;
}
public void setSegments(JSONArray segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = jsonObject.optJSONArray("summary");
storylineData.segments = jsonObject.optJSONArray("segments");
return storylineData;
}
return null;
}
#Override
public String toString() {
JSONArray combined = new JSONArray(summary);
combined.put(segment);
return combined.toString();
}
}
In your MainActivity
private StorylineData storylineData;
private MovesHandler<JSONArray> storylineHandler = new MovesHandler<JSONArray>() {
#Override
public void onSuccess(JSONArray result) {
toggleProgress(false);
storylineData = StorylineData.parse(summaryJsonObject);
updateResponse(storylineData.toString()) //displays true to layout view
result.add(storylineData.getSummary());
Log.d("call result", result.toString());
Log.d("Log.d storylineHandler", storylineHandler.toString());
}
};
I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..
here my MainActivity.java
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;
// panggil class parser
JSONparser parser = new JSONparser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getJSONArray(TAG_ID);
page = json.getJSONArray(TAG_page);
pages = json.getJSONArray(TAG_total_pages);
tot_result = json.getJSONArray(TAG_total_results);
for (int i = 0; i < results.length(); i++) {
JSONObject data = results.getJSONObject(i);
String backdrop = data.getString(TAG_backdrop_path);
String idd = data.getString(TAG_id).toString();
String ori = data.getString(TAG_original_title);
String releas = data.getString(TAG_release_date);
String poster = data.getString(TAG_poster_path);
String title = data.getString(TAG_title);
String average = data.getString(TAG_vote_average);
String count = data.getString(TAG_vote_count);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_backdrop_path, backdrop);
map.put(TAG_ID, idd);
map.put(TAG_original_title, ori);
map.put(TAG_release_date, releas);
map.put(TAG_poster_path, poster);
map.put(TAG_title, title);
map.put(TAG_vote_average, average);
map.put(TAG_vote_count, count);
genreList.add(map);
}
// Sort by
/*********************************
* Collections.sort(genreList, new Comparator<HashMap<String,
* String>>() {
*
* #Override public int compare(HashMap<String, String> a,
* HashMap<String, String> b) { return
* a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
******************************/
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
// tampilkan ke listadapter
ListAdapter adapter = new SimpleAdapter(this, genreList,
R.layout.list_data, new String[] { TAG_ID, TAG_page,
TAG_results, TAG_backdrop_path, TAG_id,
TAG_original_title, TAG_release_date, TAG_poster_path,
TAG_title, TAG_vote_average, TAG_vote_count,
TAG_total_pages, TAG_total_results }, new int[] {
R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
R.id.idd, R.id.original_title, R.id.release_date,
R.id.poster_path, R.id.title, R.id.vote_average,
R.id.vote_count, R.id.total_pages, R.id.total_results });
setListAdapter(adapter);
}
}
here my JSONparser.java
public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONparser() {
}
public JSONObject getJSONFromUrl(String url) {
// http request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
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) {
// TODO: handle exception
Log.e("BUffer Error", "Error converting result" + e.toString());
}
// try parse string to a json
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO: handle exception
Log.e("Json parser", "error parsing data" + e.toString());
}
return jObj;
}
}
here my json data.
{
"id": 18,
"page": 1,
"results": [
{
"backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
"id": 238,
"original_title": "The Godfather",
"release_date": "1972-03-24",
"poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
"title": "The Godfather",
"vote_average": 9.1999999999999993,
"vote_count": 125
},
{
"backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
"id": 857,
"original_title": "Saving Private Ryan",
"release_date": "1998-07-24",
"poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
"title": "Saving Private Ryan",
"vote_average": 8.9000000000000004,
"vote_count": 83
}
],
"total_pages": 25,
"total_results": 499
}
JSONObject jObject_Main= new JSONObject(jsonstring);
//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");
//get json Array and parse it.
JSONArray jsonArray = jObject_Main
.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");
}
i hope its useful to you.
please change this in your code:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString("id");
page = json.getString("page");
tot_result = json.getJSONArray(results);
i hope you understand it.
Try this..
In your Global:
JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;
Inside Try Catch:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString(TAG_ID); // Changes here
page = json.getString(TAG_page); // Changes here
pages = json.getString(TAG_total_pages); // Changes here
tot_result = json.getString(TAG_total_results); // Changes here
results = json.getJSONArray(TAG_results); // Add this line
for (int i = 0; i < results.length(); i++) {
// Remaining all correct
}
EDIT:
new DownloadImageTask()
.execute("your image url");
}
and DownloadImageTask.class
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}
Your JSON is JSONObject and it contains JSONArray
Parse Object
Parse Array
Example:
JSONObject jsonObj = new JSONObject(your_json_string);
String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");
JSONArray results = jsonObj.getJSONArray("results");
int len = results.length(); // length or size, I don't remember, you can check it
for (int i = 0; i < len; i++) {
JSONObject obj = results.getJSONObject(i);
String backdropPath = obj.getString("backdrop_path");
// ...
}
you need add " results= json.getJSONArray(TAG_results);" below
"tot_result = json.getJSONArray(TAG_total_results);"