I am struggling with something that really p*sses me off for several hours.
My android app manages to connect to a websoket, and receives json data which for now has worked perfectly, and here is the code for this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
This code above as I said works perfectly, and i get the data in everytime. HOWEVER, HOWEVER, HOWEVER: If i try to receive 2 json-objects at the sametime through this emittener, it does not work!!!!
Here is example when i try to receive multiple JSON objects, and NONE of them works!
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetFromSensor = new JSONObject( (String) args[0]);
int targetNum = incomingTargetFromSensor.getInt("target_number_count");
showTargetRep(targetNum); //NOT WORKING!
JSONObject incomingPositionFromSensor = new JSONObject( (String) args[0]);
double the_position = incomingPositionFromSensor.getDouble("position");
CalculateValue(the_position); //NOT WORKING!
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
In the first example I could receive the position data, and the code is exactly similar as the example above, but for some reasons it can not recevice data when i try to receive another JSON object.
Another example of why I always disliked JSON object.
Any help plz?
The solution at the end was to add multiple try/catches like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
mSocket.on("dev0", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
JSONObject incomingTargetRepFromSensor = new JSONObject((String ) args[0]);
int target_rep = incomingTargetRepFromSensor.getInt("target_repetition_count");
showTargetRep(target_rep);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingDataFromSensor = new JSONObject((String ) args[0]);
double the_position = incomingDataFromSensor.getDouble("position");
CalculateValue(the_position);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingTargetSetFromSensor = new JSONObject((String ) args[0]);
int target_set = incomingTargetSetFromSensor.getInt("target_set_count");
showTargetSet(target_set);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingRepsFromSensor = new JSONObject((String ) args[0]);
int the_repetitions = incomingRepsFromSensor.getInt("repetitions");
showCurrentReps(the_repetitions);
} catch (JSONException e) {
e.printStackTrace();
}
try{
JSONObject incomingSetsFromSensor = new JSONObject((String ) args[0]);
int the_sets = incomingSetsFromSensor.getInt("sets");
showCurrentSets(the_sets);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
Related
I am getting a org.json.JSON.typeMismatch(JSON.java:111) error while trying to create a JSON array. The received data looks like this:
{
"result":[
{
"#type":"d",
"#rid":"#-2:0",
"#version":0,
"a_adres":"kepez merkez geliyor herkez",
"takipkodu":"464664",
"agirlik":50
},
{
"#type":"d",
"#rid":"#-2:1",
"#version":0,
"a_adres":"merkez mahallesi 4 sok",
"takipkodu":"sd4fs654f64",
"agirlik":60
}
]
}
Code:
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONArray yukilanarray = new JSONArray(getResponse);
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}
Please help.
I think you made a mistake in reading the json. the first element would be a JSONObject not a JSONArray.Below is the revised code.
protected String doInBackground(String... urls) {
try {
String getResponse = get("http://178.18.206.128:2480/command/nakliye/sql/select a_adres,takipkodu,agirlik from yukilan");
return getResponse;
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String getResponse) {
ListView liste=(ListView)findViewById(R.id.list_view);
try {
JSONObject jsonObject = new JSONObject(getResponse);
JSONArray yukilanarray = jsonObject.getJSONArray("result");
List<Yukilan> yukilanlar = new ArrayList<>();
//Populate the EmployeeDetails list from response
for (int i = 0; i<yukilanarray.length();i++){
Yukilan yeniilan = new Yukilan();
JSONObject yukilanobject = yukilanarray.getJSONObject(i);
yeniilan.setAdres(yukilanobject.getString(KEY_ADRES));
yeniilan.setAgirlik(yukilanobject.getString(KEY_AGIRLIK));
yeniilan.setTakip_kod(yukilanobject.getString(KEY_TAKIPKODU));
yukilanlar.add(yeniilan);
}
//Create an adapter with the EmployeeDetails List and set it to the LstView
yukilanadapter = new Yukilanadapter(yukilanlar,getApplicationContext());
liste.setAdapter(yukilanadapter);
} catch (JSONException e) {
e.printStackTrace();
}
// System.out.println(getResponse);
}
I am working on an android project that will get a Json array from a server and then I want to iterate through the array and extract data from each Json object in the array. When I run this code the textviews do not change, but if I remove the for loop and everything in it, and then uncomment the two lines below the for loop, things seems to work. How can you iterate through the Json objects in the array so that the info will be updated on the screen and change every second for each object in the array?
Thank you in advance!
name = (TextView)findViewById(R.id.nameTxt);
email = (TextView)findViewById(R.id.emailTxt);
serverButton = (Button)findViewById(R.id.getInfoBtn);
serverButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(server_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject nameJson = response.getJSONObject(i);
name.setText(nameJson.getString("FirstName") + " " + nameJson.getString("LastName"));
email.setText(nameJson.getString("Email"));
Thread.sleep(1000);
}
//JSONObject nameJson = response.getJSONObject(1);
// name.setText(nameJson.getString("FirstName"));
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
name.setText("Something is wrong");
}
});
MySingleton.getInstance(MainActivity.this).addToRequestQueue(jsonArrayRequest);
I'm using retrofit to POST a json array to server. Data is something like this:
{something:
{somethings:
[
{"param1":"value", "param2":value},
{"param1":"value", "param2":value}
]
}
}
however, my server forces me to MUST include the indices in the array like:
{something:
{somethings:
{
"0":{"param1":"value", "param2":value},
"1":{"param1":"value", "param2":value}
}
}
}
In other words cannot send parameters like this:
something[somethings][][param1]
something[somethings][][param2]
I must include indices:
something[somethings][0][param1]
something[somethings][0][param2]
How to do this using retrofit?
My interface looks like this:
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body Something something);
}
My classes look like following:
public class PostSomething {
private MapOfSomething something = new MapOfSomething();
public MapOfSomething getSomething() {
return portfolio;
}
public void setSomething(MapOfSomething something) {
this.something = something;
}
}
public class MapOfSomething {
private JSONObject somethings = new JSONObject();
public JSONObject getPortfolios() {
return somethings;
}
public void setSomethings(List<Something> somethingList) {
for (int i = 0; i<somethingList.size(); i++) {
try {
somethings.put(String.valueOf(i).toString(), somethingList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and calling the method like:
PostSomethings something = new PostSomethings();
MapOfSomething map = new mapOfSomething();
map.setSomethings(listofSomething);
something.setSomethings(map);
apiService.postSomething(something);
One way to solve your problem is to put json directly into body , so your interface will look like this
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body JSONObject jsonObject);
}
Now you need to create the JSONObject , here is how I have created your desired JSONObject
JSONObject mainJson = new JSONObject();
JSONArray list = new JSONArray();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet1 = new JSONObject();
try {
singleElementSet1.put("1",singleElement1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet2 = new JSONObject();
try {
singleElementSet2.put("2",singleElement2);
} catch (JSONException e) {
e.printStackTrace();
}
list.put(singleElementSet1);
list.put(singleElementSet2);
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("json",""+mainJson.toString());
I am assuming right now you are calling your service like this way
Call<Something> call = instanceOfYourAPIService.postSomething(anInstanceOfSomethingObject);
But now you have to replace this with the following
Call<Something> call = instanceOfYourAPIService.postSomething(mainJson); //mainJson is the JSONObject which is created earlier
Hope it helps
EDIT
JSONObject mainJson = new JSONObject();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();
//hope you can add item to this arraylist via some loop
jsonObjectArrayList.add(singleElement1);
jsonObjectArrayList.add(singleElement2);
JSONArray list = new JSONArray();
for(int i = 0;i<jsonObjectArrayList.size();i++){
JSONObject elementSet = new JSONObject();
try {
elementSet.put(String.valueOf(i).toString(),jsonObjectArrayList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
list.put(elementSet);
}
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}
#Override
public void onResponse(String response, int id) {
try {
JSONObject pollresult = new JSONObject(response);
List<OrderInfo> info = new Gson().fromJson(pollresult.getString("data"), new TypeToken<ArrayList<OrderInfo>>() {
}.getType());
orderId = info.get(0).getOrderID();
} catch (JSONException e) {
e.printStackTrace();
}
}
info.get(0) returns null and i get NullPointerException
I am using volley in my android app and i add Torrent objects to the Arraylist and it fills the list but after the program exits this method getAllDetails() the arraylist is empty..could someone please explain what is really going on???
private void getAllDetails() {
String URL = MOVIE_DETAILS_URL + movie.getId() + CAST_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataObject = response.getJSONObject(Keys.DATA);
JSONObject movieObject = dataObject.getJSONObject(Keys.MOVIE);
JSONArray torrentsArray = movieObject.getJSONArray(Keys.TORRENTS);
for (int i = 0; i < torrentsArray.length(); i++) {
JSONObject torrentObject = torrentsArray.getJSONObject(i);
Torrent torrent = new Torrent();
torrent.setUrl(torrentObject.getString(Keys.URL));
torrent.setSize(torrentObject.getString(Keys.SIZE));
torrent.setQuality(torrentObject.getString(Keys.QUALITY));
torrent.setSeeds(Integer.parseInt(torrentObject.getString(Keys.SEEDS)));
torrent.setPeers(Integer.parseInt(torrentObject.getString(Keys.PEERS)));
torrentList.add(torrent);
}
getTorrent();//when this method is called here the list has items on it and it works fine
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
this method uses the torrentlist arraylist to download the .torrent file
private void getTorrent() {
String mUrl = torrentList.get(0).getUrl();
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
String name = movie.getMovie_title() + ".torrent";
File torrentDirectory = createFolder();
File file = new File(torrentDirectory, name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(response);
Toast.makeText(ViewMovie.this,"Successfully Downloaded",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
}
A quick fix you can try to pass your ArrayList to your getTorrent() function.
getTorrent(torrentList);
You will call your function like this.
private void getTorrent(ArrayList<Torrent> passedList) {
String mUrl = passedList.get(0).getUrl();
// rest of your code here
}
But you need to know that, this function will always give you the result of first torrent. Because you are getting 0 index in ArrayList. Maybe by passing index also, you can create more functional method.