Match `json` response with string - android

On click of selected date, I want to display related tasks or events.
public static List<ScheduledTasks> getResponse() {
String res = "[{\n" +
"\t\"scheduleId\": \"999\",\n" +
"\t\"eventType\": \"first\",\n" +
"\t\"impacts\": \"high\",\n" +
"\t\"startDate\": 27032018,\n" +
"\t\"endDate\": 27032018,\n" +
"\t\"machineOwner\": \"Nilesh\",\n" +
"\t\"description\": \"good\",\n" +
"\t\"status\": \"working\"\n" +
"}, ...
"}]";
return new Gson().fromJson(res, new TypeToken<List<ScheduledTasks>>(){}.getType());
this is the JSON.
Using the below
LayoutManager = new LinearLayoutManager(this);
String s = getIntent().getStringExtra("dateselected");
ScheduledTasks=getResponse();
adapter = new RecyclerAdapter(ScheduledTasks);
recyclerView.setAdapter(adapter);
List<ScheduledTasks>
I want to display only tasks for selected date.
String S date needs to be matched with json response and show particular tasks.
for date 27 only the tasks on that day should be displated.

try changing your getResponse method a bit like this so you can filter by date
public static List<ScheduledTasks> getResponse(String dateselected) {
String res = "[{\n" +
"\t\"scheduleId\": \"999\",\n" +
"\t\"eventType\": \"first\",\n" +
"\t\"impacts\": \"high\",\n" +
"\t\"startDate\": 27032018,\n" +
"\t\"endDate\": 27032018,\n" +
"\t\"machineOwner\": \"Nilesh\",\n" +
"\t\"description\": \"good\",\n" +
"\t\"status\": \"working\"\n" +
"}, ...
"}]";
JSONArray array= null;
JSONArray filter=new JSONArray();
try {
//change res to a JsonArray object so i can filter
array = new JSONArray(res);
try {
for (int i=0; i<array.length();i++){
String date=array.getJSONObject(i).has("startDate")?array.getJSONObject(i).getString("startDate"):"";
//if i match selected date i pick it
if (!TextUtils.isEmpty(date)&&date.equals(dateselected))
filter.put(array.getJSONObject(i));
}
}catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
//res
res=filter.toString();
return new Gson().fromJson(res, new TypeToken<List<ScheduledTasks>>() {
}.getType());
}

Related

how to merge 2 data records to one in a recyclerView ? (mysql & volley)

I want to merge two data records to become one based on the same DAY, but different "Sesi" such as Sesi 1, and Sesi 2 being 1 in a recyclerVCiew
please see my application Image
here I use mySql with volley JSON + Inner Join MYSQL
Main Activity:
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ALL_JADWAL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
if (kelas.equals(Kelas)) {
jadwalHarianList.add(new JadwalHarian(
jadwal.getString("Nama_Pengajar"),
jadwal.getString("Mata_Kuliah"),
jadwal.getString("Ruang"),
jadwal.getInt("Sesi"),
jadwal.getString("Hari"),
jadwal.getString("Jam")
));
}
JadwalRV jadwalRV = new JadwalRV(getApplicationContext(), jadwalHarianList);
recyclerView.setAdapter(jadwalRV);
jadwalRV.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
JadwalRV Adapter:
public void onBindViewHolder(JadwalRV.MyViewHolder myViewHolder, int i) {
JadwalHarian jadwalHarian = mJadwalHarian.get(i);
myViewHolder.tHari.setText(jadwalHarian.getHari());
myViewHolder.tIsi.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
// SESI 2
myViewHolder.tIsi2.setText("Waktu\n" +
"Ruang\n" +
"Mata Kuliah\n" +
"Dosen Pengajar");
myViewHolder.thjam2.setText(
"= " + jadwalHarian.getJam()+
"\n= " + jadwalHarian.getRuang() +
"\n= " + jadwalHarian.getMata_Kuliah() +
"\n= " + jadwalHarian.getNama_Pengajar() );
}
Here is Structure Table which I used inner join in my PHP json
You can try like this following not obvious, but It can help you:
try
{
JSONArray array = new JSONArray();
ArrayList<HashMap<String,Object>> jadwalHarianList = new ArrayList<>();
JSONObject jsonObject=new JSONObject();
try
{
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "1");
jsonObject.put("Mata_Kuliah", "Pemprograman #1");
array.put(jsonObject);
jsonObject = new JSONObject();
jsonObject.put("Kelas", "R28");
jsonObject.put("Sesi", "2");
jsonObject.put("Mata_Kuliah", "Algoritma #2");
array.put(jsonObject);
}
catch (Exception e)
{
Log.e("ldfjdlfj","data----111_jsonOb_ex>>>"+e);
}
Log.e("ldfjdlfj","data----2222>>>"+array);
String previous = "";
for (int i = 0; i < array.length(); i++) {
JSONObject jadwal = array.getJSONObject(i);
String kelas = jadwal.getString("Kelas");
String Sesi = jadwal.getString("Sesi");
String Mata_Kuliah = jadwal.getString("Mata_Kuliah");
if(kelas.equalsIgnoreCase(previous))
{
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i-1).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i-1).getString("Sesi"));
map.put("Sesi2",Sesi);
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
else
{
previous = kelas;
HashMap<String,Object> map = new HashMap<>();
map.put("kelas",array.getJSONObject(i).getString("Kelas"));
map.put("Sesi",array.getJSONObject(i).getString("Sesi"));
map.put("Sesi2","");
map.put("Mata_Kuliah",Mata_Kuliah);
jadwalHarianList.add(map);
}
}
Log.e("ldfjdlfj","data----333_>>>"+jadwalHarianList);
} catch (JSONException e) {
e.printStackTrace();
}

How to retrieve genre from JSON result

I can not retrieve all key values from JSON object retrieved from HTTP request.
This is the returned JSON object from http request:
{"data":[{"movie_id":3,"movie_name":"Promithius","genre":"a dude","year":"2016","rating":45}]}
my Android Code:
try {
//HttpJsonParser httpJsonParser = new HttpJsonParser();
JSONObject JSonObj = (JSONObject) new
JSONTokener(result).nextValue();
String mymovie = JSonObj.getString("movie_name" );
String movieGenre = JSonObj.getString("genre" );
etResponse.setText("movie=" + mymovie + " genre=" +
movieGenre);
} catch (JSONException e) {
etResponse.setText("ERROR=" + e.getMessage());
e.printStackTrace();
}
When I run it in emulator with only:
String mymovie = JSonObj.getString("movie_name" );
etResponse.setText("movie=" + mymovie;
I get back the Movie name with no error. So the issue is I can retrieve movie_name but no Genre.
Error returned says "No value for genre"
Thanks in advance.
I think the data is JSONArray.
String result = "{\"data\":[{\"movie_id\":3,\"movie_name\":\"Promithius\",\"genre\":\"a dude\",\"year\":\"2016\",\"rating\":45}]}";
try {
JSONObject JSonObj = (JSONObject) new JSONTokener(result).nextValue();
JSONArray data = JSonObj.getJSONArray("data");
for (int i=0; i<data.length(); i++){
JSONObject jsonObject = data.getJSONObject(i);
String mymovie = jsonObject.getString("movie_name" );
String movieGenre = jsonObject.getString("genre" );
String dest = "movie=" + mymovie + " genre=" + movieGenre;
Log.d(TAG, dest);
}
} catch (JSONException e) {
e.printStackTrace();
}
Below is the code that finally worked for me. I hope it can help someone else.
try{
JSONObject object = new JSONObject(result);
JSONArray Jarray = object.getJSONArray("data");
object = Jarray.getJSONObject(0);
String MovieName = object.getString("movie_name");
String Genre = object.getString("genre");
String Rating = object.getString("rating");
String Year = object.getString("year");
etResponse.setText("Movie Name = " + MovieName + " \n Genre = " +
Genre + "\n Rating = " + Rating + " \n Year = " + Year );
} catch (JSONException e) {
etResponse.setText("JSONException: " + e.getMessage());
}

Concatenation inside try catch

try {
final List<NetworkType> dataReceived = getData();
int i = 0;
//Array Iteration
for(final NetworkType networkType : dataReceived) {
i++;
if (i > 3) {
Toast.makeText(getApplicationContext(), "Done!!", Toast.LENGTH_SHORT);
} else {
String mCell1CID = networkType.getCell1CID();
String mCell1LAC = networkType.getCell1LAC();
String mCell1MCC = networkType.getCell1MCC();
String mCell1MNC = networkType.getCell1MNC();
String mCell1CI = networkType.getCell1CI();
String mCell1TAC = networkType.getCell1TAC();
//API requestBody
String url = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyA8NAA3dUpECFn2j6pdcQT3wgqUM98UZ2Q";
String cellID = null;
String locationAreaCode = null;
if (mCell1CID.equals("") && mCell1LAC.equals("")) {
cellID = mCell1CI;
locationAreaCode = mCell1TAC;
} else if (mCell1CI.equals("") && mCell1TAC.equals("")) {
cellID = mCell1CID;
locationAreaCode = mCell1LAC;
} else {
Log.d("GeoL", "3");
}
String requestBody =
"{" +
"\"cellTowers\":[" +
"{" +
"\"cellId\" :" + cellID + "," +
"\"locationAreaCode\" :" + locationAreaCode + "," +
"\"mobileCountryCode\" :" + "\"" + mCell1MCC + "\"" + "," +
"\"mobileNetworkCode\" :" + "\"" + mCell1MNC + "\"" +
"}" +
"]" +
"}";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(String.valueOf(response));
JSONObject latitude = jsonObject.getJSONObject("location");
String lat = latitude.getString("lat");
String lng = latitude.getString("lng");
String acc = jsonObject.getString("accuracy");
if (!dataReceived.listIterator().hasNext()){
String print;
print = String.format("%s%s", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
} else {
String print;
print = String.format("%s%s,", print, print(lat.toString(), lng.toString(), acc.toString()));
writeToFile(print, getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Response", "error" + error.toString());
}
});
queue.add(jsObjRequest);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to concat the received value to the print variable.
But this the error which i receive
print needs to be initialized is what I receive.
also if declared outside the try/catch block it requires it to be final.
What to do?
just use String print = null; when you declare print
You are providing a value that is not initialized to the String.format
You need to initialize the variable "print" with what you want to be used in the String.format (for example an empty String) :
String print= ""
Or use String Builder:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("1");
stringBuilder.append("2");
String finalString = stringBuilder.toString();

How i can retrieve this array of images from json?

I have his json and i need to retrieve array of images from images Variable..
this my json :
{
id: 215,
title: " this is title",
image: "1464958558.jpg",
description: "description",
images: "["1464958558.jpg","1464958559.jpg","1464958561.jpg","1464958563.jpg","1464958564.jpg","1464958568.jpg","1464958569.jpg","1464958570.jpg","1464958573.jpg","1464958574.jpg"]",
user_name: "user name",
telephone: "0123456789"
}
i want to retrieve this images array and display it in grid view... and i can't find any response in logcat
my doInBackGround()
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
ID = mCursor.getString(ArticleLoader.Query._ID);
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + String.valueOf(Config.BASE_URL));
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
GridItem item;
item = new GridItem();
Log.i(TAG, "parseResult: " + jsonObj);
for (int i = 0; i < jsonObj.length(); i++) {
// if (response != null) {
String images = jsonObj.getString("images");
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
dose i retrieve data correctly ?
Is images json object string or json array? In your code is string.
If WebService changes are possible, request to given you a json array of images, this is best practice.
If not possible you must parse json image object with regex.
No your doing wrong just try below code
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
for(int i=0;i<arrayObj.length();i++)
{
String item = arrayObj.getString(i);
// now you use item string where you want
}
} catch (JSONException e) {
e.printStackTrace();
}
images should be a JSONArray, and hence you can do that to parse it (inside your for loop!):
JSONArray imagesJSON = jsonObj.getJSONArray("images");
for(int k = 0 ; k<imagesJSON.length() ; k++){
String image = imagesJSON.getString(k);
item.setImage(IMAGE_LINK + image);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + image);
mGridData.add(item);
}

How do I structure my data to switch from using ParseJsonArray/ParseJsonObject to using GSON.fromJson(...)

I have been working with GSON to try and parse a Json response I am getting from a CakePHP server for about a week. Here is what the response looks like :
[{"BaseObject": {"field1":"1","field2":"1639","field3":"10","field4":"1","field5":"12","field6":"10.765984","field7":"-25.768357","field8":"1327790850"}},{"BaseObject":{"field1":"2","field2":"1934","field3":"19","field4":"30","field5":"2","field6":"10.758662","field7":"-25.769684","field8":"1327790850"}},{"BaseObject":{"field1":"3","field2":"2567","field3":"33","field4":"6","field5":"98","field6":"10.758786","field7":"-25.769843","field8":"1327790850"}},{"BaseObject":{"field1":"4","field2":"0","field3":"33","field4":"7","field5":"0","field6":"10.758786","field7":"-20.769843","field8":"1327790850"}},{"BaseObject":{"field1":"5","field2":"1097","field3":"33","field4":"1","field5":"0","field6":"15.758786","field7":"50.769843","field8":"1327790850"}},{"BaseObject":{"field1":"6","field2":"1936","field3":"50","field4":"0","field5":"9","field6":"19.234987","field7":"-67.340065","field8":"1327798560"}}]
I used a plugin for Notepad++ to verify that the response is valid Json and it is.
First I tried this function:
public static List<BaseObject> parserInputStreamGson(InputStream stream)
{
List<BaseObject> objList = new ArrayList<BaseObject>();
if(stream != null){
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG,"Trying to Parse Reader");
try{
objList = gson.fromJson(r, new TypeToken<List<BaseObject>>() {}.getType() );
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage() );
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage() );
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage() );
}
}
}
Log.d(TAG,"BaseObject[] = " + objList.toString());
return objList;
}
Then I tried this function:
public static BaseObject[] parserInputStreamGsonArray(InputStream stream)
{
BaseObject[] objectArray = null;
if (stream != null) {
Gson gson = new Gson();
Reader r = new InputStreamReader(stream);
Log.d(TAG, "Trying to Parse Reader");
try {
objectArray = gson.fromJson(r, new TypeToken<Event[]>() {}.getType());
} catch (JsonSyntaxException e) {
Log.d(TAG, "JsonSyntaxException : " + e.getMessage());
} catch (JsonIOException e) {
Log.d(TAG, "JsonIOException : " + e.getMessage());
} finally {
try {
r.close();
} catch (IOException e) {
Log.d(TAG, "IOException : " + e.getMessage());
}
}
}
if(eventArray != null){
for(int m=0;m<eventArray.length;m++){
Log.d(TAG, "objectArray[" + String.valueOf(m) + "] = " + objectArray[m].toString());
}
}
return objectArray;
}
And in both cases Gson returned 5 objects, but all of the fields were set to zero.
Finally I got this function to work, but it feels clunky.
public static List<BaseObject> ParseInputStream(InputStream stream) {
Reader r = new InputStreamReader(stream);
List<BaseObject> baseObjectList = new ArrayList<BaseObject>();
try {
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(r).getAsJsonArray();
JsonObject topObject = new JsonObject();
JsonObject subObject = new JsonObject();
for (int m = 0; m < array.size(); m++) {
if (array.get(m).isJsonObject()) {
topObject = array.get(m).getAsJsonObject();
if (topObject.get("BaseObject").isJsonObject()) {
subObject = topObject.get("BaseObject").getAsJsonObject();
BaseObject baseobject = new BaseObject();
baseobject.field1 = subObject.get("field1").getAsLong();
baseobject.field2 = subObject.get("field2").getAsInt();
baseobject.field3 = subObject.get("field3").getAsLong();
baseobject.field4 = subObject.get("field4").getAsInt();
baseobject.field5 = subObject.get("field5").getAsInt();
baseobject.field6 = subObject.get("field6").getAsDouble();
baseobject.field7 = subObject.get("field7").getAsDouble();
baseobject.field8 = subObject.get("field8").getAsLong();
baseObjectList.add(baseobject);
} else {
Log.e(TAG, "topObject[" + String.valueOf(m)+ "].subObject is not a JsonObject");
}
} else {
Log.e(TAG, "Array # " + String.valueOf(m)+ " is not a JsonObject!");
}
}
} catch (Exception ex) {
Log.e(TAG, "Exception thrown = " + ex.toString());
ex.printStackTrace();
}
return baseObjectList;
}
Here is the class I created for BaseObject.
public class BaseObject {
#SerializedName("field1")
public long field1;
#SerializedName("field2")
public int field2;
#SerializedName("field3")
public long field3;
#SerializedName("field4")
public int field4;
#SerializedName("field5")
public int field5;
#SerializedName("field6")
public double field6;
#SerializedName("field7")
public double field7;
#SerializedName("field8")
public long field8;
#Override
public String toString() {
return "(" +
"field1= " + String.valueOf(this.field1) + ", " +
"field2= " + String.valueOf(this.field2) + ", " +
"field3= " + String.valueOf(this.field3) + ", " +
"field4= " + String.valueOf(this.field4) + ", " +
"field5= " + String.valueOf(this.field5) + ", " +
"field6= " + String.valueOf(this.field6) + ", " +
"field7= " + String.valueOf(this.field7) + ", " +
"field8= " + String.valueOf(this.field8) +
")";
}
}
Can anyone tell me how I need to structure my data classes in order use Gson.fromJson to work.
Since your response is actually List<BaseObject>, you should be using
List baseObjectList = new Gson().fromJson(r,new TypeToken>() {}.getType())
Also I should mention that, you do not really need to use the #SerializedName annotations since your attribute names in the json reply and in the class are same.
UPDATE:
Oops.. Sorry, I should have tried your code before answering. Please refer to the following code. Everything boiled down to the Structuring of classes.
public class Sample {
public static class Wrapper{
private BaseObject BaseObject;
#Override
public String toString() {
return BaseObject == null? null : BaseObject.toString();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String json = "[{\"BaseObject\": {\"field1\":\"1\",\"field2\":\"1639\",\"field3\":\"10\",\"field4\":\"1\",\"field5\":\"12\",\"field6\":\"10.765984\",\"field7\":\"-25.768357\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"2\",\"field2\":\"1934\",\"field3\":\"19\",\"field4\":\"30\",\"field5\":\"2\",\"field6\":\"10.758662\",\"field7\":\"-25.769684\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"3\",\"field2\":\"2567\",\"field3\":\"33\",\"field4\":\"6\",\"field5\":\"98\",\"field6\":\"10.758786\",\"field7\":\"-25.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"4\",\"field2\":\"0\",\"field3\":\"33\",\"field4\":\"7\",\"field5\":\"0\",\"field6\":\"10.758786\",\"field7\":\"-20.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"5\",\"field2\":\"1097\",\"field3\":\"33\",\"field4\":\"1\",\"field5\":\"0\",\"field6\":\"15.758786\",\"field7\":\"50.769843\",\"field8\":\"1327790850\"}},{\"BaseObject\":{\"field1\":\"6\",\"field2\":\"1936\",\"field3\":\"50\",\"field4\":\"0\",\"field5\":\"9\",\"field6\":\"19.234987\",\"field7\":\"-67.340065\",\"field8\":\"1327798560\"}}]";
List<Wrapper> results = new Gson().fromJson(json,new TypeToken<List<Wrapper>>(){}.getType());
System.out.println(results);
}
}
Just curious, do you have the liberty to change the JSON reply coming from server? IMHO, Its structure is a little complicated.

Categories

Resources