I implemented an app that gets data from a JSON. JSON is returning me characters:
Âé...
How I can get that return JSON:
áéíóú
instead of
Âé
private void parseJson(JSONObject json) {
nombresLista = new ArrayList<HashMap<String, String>>();
if (json != null){
try {
JSONArray sitios = json.getJSONArray("sites");
for (int i = 0; i < sitios.length(); i++) {
JSONObject jsonObj = sitios.getJSONObject(i);
String nombre = jsonObj.getString("name");
HashMap<String, String> lista = new HashMap<String, String>();
lista.put("name", nombre);
nombresLista.add(lista);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < nombresLista.size(); i++) {
String nombre = nombresLista.get(i).get("name");
Log.e("", "nombre = " + nombre);
}
}
Related
I am building an app in android studio that uses JSON to acess to my postgresql where is my data and I am receiving the data this way:
[
{"id":"1","title":"12 May to 30 Jun"},
{"id":"2","title":"3 Jun to 20 Jun"}
]
I tried to find every where how to use JSONObject or JSONArray for "unlock" the data for pass it to other variables
After sometime trying and trying I found a way to
String finalJson = buffer.toString();
try {
JSONArray parentArray = new JSONArray(finalJson);
int count = 0;
int[] id = new int[parentArray.length()];
String[] title = new String[parentArray.length()];
StringBuffer finalBufferedData = new StringBuffer();
while (count < parentArray.length())
{
JSONObject finalObject = parentArray.getJSONObject(count);
id[count] = finalObject.getInt("id");
title[count] = finalObject.getString("title");
finalBufferedData.append(id[count] + " - " + title[count] + "\n");
count++;
}
return finalBufferedData.toString();
} catch (JSONException e) {
e.printStackTrace();
}
this way I was able to get the 2 rows from postgresql and show it (later will add it the app sqlite so it doesn't require always to check in my postgresql)
Here is the working code:
public void parseJson() {
// Response from API call
String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" +
"{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]";
try {
JSONArray jsonArray = new JSONArray(response);
// Get all jsonObject from jsonArray
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = null, title = null;
// Id
if (jsonObject.has("id") && !jsonObject.isNull("id")) {
id = jsonObject.getString("id");
}
// Title
if (jsonObject.has("title") && !jsonObject.isNull("title")) {
title = jsonObject.getString("title");
}
Log.d("SUCCESS", "JSON Object: " + "\nId: " + id
+ "\nTitle: " + title);
}
} catch (JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
}
OUTPUT:
D/SUCCESS: JSON Object:
Id: 1
Title: 12 May to 30 Jun
D/SUCCESS: JSON Object:
Id: 2
Title: 3 Jun to 20 Jun
protected void onPostExecute(String result)
{
//result parameter should be final so that it can be used in cross thread operation
super.onPostExecute(result);
if (result != null) {
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String Brand = object.getString("UserName");
HashMap<String, String> itemList = new HashMap<String, String>();
itemList.put("UserName", Brand);
BrandList.add(itemList);
}
**adapter = new SimpleAdapter(Main2Activity.this, BrandList, R.layout.list, new String[]{"UserName"}, new int[]{R.id.txtTitel});
((AdapterView<ListAdapter>) listView).setAdapter(adapter);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
Toast.makeText(Main2Activity.this, "Could not get any data.", Toast.LENGTH_LONG).show();
}
}
This is my getView() method where I am trying to set the values of distance after fetching from the volley .Here distance calculation is proper.
public View getView(final int position, View convertView, ViewGroup parent)
{
listrowposition = position;
if (convertView == null)
{
LayoutInflater inflater = getActivity().getLayoutInflater();
convertView = inflater.inflate(R.layout.singlerowallassigendloction, null);
holder = new ViewHolder();
holder.distance = (TextView) convertView.findViewById(R.id.distance);
holder.lati = (TextView) convertView.findViewById(R.id.lati);
holder.longi = (TextView) convertView.findViewById(R.id.longi);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.lati.setText(salesmanlocationArrayList.get(listrowposition).getLati());
holder.longi.setText(salesmanlocationArrayList.get(listrowposition).getLongi());
double lat1= Double.parseDouble(holder.lati.getText().toString());
double lng1= Double.parseDouble(holder.longi.getText().toString());
vollyRequest_Fetch_distance(lat1,lng1,lat,lng);
Log.d("distance_ll=","tex="+text+" "+value+" "+lat1);
double d= Double.parseDouble(value)/1000;
holder.distance.setText(""+new DecimalFormat("##.##").format(d)+" KM");
return convertView;
}
This is my volley request code
public void vollyRequest_Fetch_distance(double lat11, double lon11, double lat22, double lon22)
{
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins="+lat11+","+lon11+"&"+"destinations="+lat22+","+lon22;
Log.d("RESPOetchlocation..>>> ", url + "<<<");
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d("RESPONFetchlocation>>> ", response + "<<<");
// progressDialog.dismiss();
Jsonresponse_Distance(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE:Error>>> ", error.toString() + "<<<");
// progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("key", "Arz5SyA5UFy-pTsr5cIdwxghhnV6BoH-pCJBARg");
return params;
}
};
queue.add(request);
}
public void Jsonresponse_Distance(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONArray jsonArray_elements = null;
JSONObject jsonObject_elements = null;
JSONObject jobj;
String error = null;
String msg = null;
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("OK"))
{
jsonArray = jsonObject.getJSONArray("rows");
Log.d("jsonArray.length()=",""+jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
jobj= jsonArray.getJSONObject(i);
jsonArray_elements= jobj.getJSONArray("elements");
Log.d("jsonArray_ets.length()=",""+jsonArray_elements.length());
for (int j = 0; j < jsonArray_elements.length(); j++)
{
jsonObject_elements= jsonArray_elements.getJSONObject(0);
Log.d("jsonObject_elements=",jsonObject_elements.toString());
JSONObject job= jsonObject_elements.getJSONObject("distance");
Log.d("job=",job.toString());
text= job.getString("text");
value= job.getString("value");
Log.d("job=",""+text+" "+value);
}
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
I am getting proper result for value (distance ) but getting null inside getview method please help me out.
// Here I am trying to set my adapter after fetching volley request
public void Jsonresponse_Viewlocation(String str)
{
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONObject jobj;
String error = null;
String msg = null;
salesmanlocationArrayList.clear();
try
{
jsonObject = new JSONObject(str);
Log.d("jsonObject==", jsonObject.toString());
msg = jsonObject.getString("status");
if (msg.equals("true")) {
jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++)
{
salesmanlocation = new Salesmanlocation();
jobj = jsonArray.getJSONObject(i);
address = jobj.getString("address");
salesmanlocation.setAddress(address); salesmanlocation.setAddress(jobj.getString("address"));
String latlong_string=getLocationFromAddress(address);
String latlong[]=latlong_string.split(",");
String lat1=latlong[0];
String lng1=latlong[1];
Log.d("latlng==",""+lat1+" "+lng1);
double latt= Double.parseDouble(lat1);
double lng1g= Double.parseDouble(lng1);
salesmanlocation.setLati(String.valueOf(lat1));
salesmanlocation.setLongi(String.valueOf(lng1));
salesmanlocationArrayList.add(salesmanlocation);
}
}
else
{
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter = new Baseddapter_Allassignloc();
alllist.setAdapter(adapter);
}
this is my request code ,please help me to parse it correctly. I want all the options for each particular question but I am getting only one option .can anyone solve it. I have attached SS of my data format.
JsonObjectRequest request = new JsonObjectRequest(
"http://www.proprofs.com/quiz-school/mobileData/request.php?request=QuizStart&module=handShake&title=does-your-crush-like-you-girls-only_1",
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
// ArrayList<Data> listData = new ArrayList<>();
if (response != null && response.length() > 0) {
try {
JSONArray array = response.getJSONArray("quiz");
// JSONObject jsonObject = array.getJSONObject(0);
for (int i = 0; i < array.length(); i++) {
JSONObject currentArray = array.getJSONObject(i);
DataQuestions movie = new DataQuestions();
movie.setQuestion(currentArray.getString("question"));
String question = currentArray.getString("question");
System.out.println("question----------" + question);
movie.setQuesImage(currentArray.getString("QuesImage"));
String image = currentArray.getString("QuesImage");
System.out.println("QuesImage----------" + image);
JSONArray keys= currentArray.getJSONArray("keys");
for(int j =0;j<keys.length();j++){
JSONObject keyobject = keys.getJSONObject(j);
movie.setOption(keyobject.getString("option"));}
/*String key = null;
if(keys.getJSONObject("option")) {
key = keys.getString("option");
}
movie.setOption(key);*/
/* JSONArray jsonArray1 = (jsonObject.getJSONArray("keys"));
int numberOfItemsInResp = jsonArray1.length();
for (int j = 0; j < numberOfItemsInResp; j++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
DataQuestions options = new DataQuestions();
// movie = new DataQuestions();
options.setOption(jsonObject2.getString("option"));
String optios = jsonObject2.getString("option");
System.out.println("option----------" + options);
// JSONArray jsonArray1 = (response.getJSONArray("keys"));*/
movieList.add(movie);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If an error occurs that means end of the list has reached
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hidePDialog();
Toast.makeText(MainActivity.this, "No Items Available", Toast.LENGTH_LONG).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request);
}
This is because, you use a single object in second for loop. You should to define keys object and stored within arraylist in main object. Like this
public class Quiz {
String quizId;
String QuesImage;
String question;
String questionId;
String Type;
int index;
ArrayList<Keys> keysList;
}
public class Keys{
String answerId;
String option;
String AnsImage;
}
and parse it
JSONArray array = response.getJSONArray("quiz");
for (int i = 0; i < array.length(); i++){
JSONObject jsonObj = array.getJSONObject(i);
Quiz quiz = new Quiz();
quiz.QuesImage = jsonObj.getString("QuesImage");
quiz.question = jsonObj.getString("question");
quiz.questionId = jsonObj.getString("questionId");
quiz.Type = jsonObj.getString("Type");
quiz.index = jsonObj.getInt("index");
JSONArray keys = jsonObj.getJSONArray("keys");
for (int j = 0; j < keys.length(); j++) {
JSONObject keysObj = keys.getJSONObject(j);
Keys keys = new Keys();
keys.answerId = keysObj.getString("answerId");
keys.option = keysObj.getString("option");
keys.AnsImage = keysObj.getString("AnsImage");
quiz.keysList.add(keys);
}
}
I want to first get particuler data from JsonObject then i also want to set that JsonObject as parallel data. I think it is possible with HashMap. But i do not know how to set data as parallel JsonObject. And How to use ?
Please Help me.
I want to each name with each own JsonObject.
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String name = json.optString("username");
list.add(json);
}
You can do like this
You declare global variable
private HashMap<String, JSONObject> mHashMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.admin_frag_update_driver, container, false);
mHashMap = new HashMap<String, JSONObject>();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String name = json.optString("username");
list.add(json);
mHashMap.put(name , object);
}
JSONObject object = mHashMap.get(name );
}
Try this way it will help
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(INTEREST_ACCEPT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
interestaccept = jsonObj.getJSONArray(INTEREST_ACCEPT);
for (int i = 0; i < interestaccept.length(); i++) {
JSONObject c = interestaccept.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(INTERESTACCEPT_USER_ID, c.getString(INTERESTACCEPT_USER_ID));
map.put(INTEREST_ACCEPT_NAME,c.getString(INTEREST_ACCEPT_NAME));
map.put(INTEREST_ACCEPT_PROFILE, c.getString(INTEREST_ACCEPT_PROFILE));
map.put(INTEREST_ACCEPT_IMAGE, c.getString(INTEREST_ACCEPT_IMAGE));
map.put(INTEREST_ACCEPT_CAST, c.getString(INTEREST_ACCEPT_CAST));
map.put(INTEREST_ACCEPT_AGE, c.getString(INTEREST_ACCEPT_AGE)+" years");
map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
I need to get Particular Object values ( A, B, C, D) and related key values (#"name" ). After getting (A, B, C, D ) object values I need to list out into list view Android. Here below I have posted my sample code and response. Please help me.
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
My JSON Response :
{"response" : [ {
"A" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
],
"B" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
]
} ]}
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value.
You can get dynamic keys like this
JSONObject responseDataObj = new JSONObject(responseData);
JSONArray responseArray = responseDataObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
nodes = new ArrayList<ArrayList<String>>();//nodes ArrayList<ArrayList<String>> declared globally
nodeSize = new ArrayList<Integer>();//nodeSize ArrayList<Integer> declared globally
JSONObject obj = responseArray.getJSONObject(i);
Iterator keys = obj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is A,B,...
// get the value of the dynamic key
JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
int sizeInArrayList = jsonrraySize + 1;
nodeSize.add(sizeInArrayList);
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
nameList = new ArrayList<String>();//nameList ArrayList<String> declared globally
if(ii == 0) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//store name in an arraylist
nameList.add(name);
}
}
}
nodes.add(nameList);
}
}
You can use following method to parse your response and handle output as per requirement.
private void parseJson(String res) {
try {
JSONObject mainObject = new JSONObject(res);
JSONArray response = mainObject.getJSONArray("response");
for (int i = 0; i < response.length(); i++) {
JSONObject obj = response.getJSONObject(i);
JSONArray A = obj.getJSONArray("A");
for (int j = 0; j < A.length(); j++) {
JSONObject objA = A.getJSONObject(j);
String name = objA.getString("name");
// use or store name here
}
JSONArray B = obj.getJSONArray("B");
for (int k = 0; k < B.length(); k++) {
JSONObject objB = B.getJSONObject(k);
String name = objB.getString("name");
// use or store name here
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This may work for you :
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts;
contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
JSONArray jsonArrayA=new JSONArray();
jsonArrayA=c.getJSONArray("A");
for(int j=0;j<jsonArrayA.length();j++){
String name=jsonArrayA.getJSONObject(j).getString("name");
Log.e("Name","name of jsonarray A "+i+" "+name);
}
JSONArray jsonArrayB=c.getJSONArray("B");
for(int k=0;k<jsonArrayB.length();k++){
String name=jsonArrayB.getJSONObject(k).getString("name");
Log.e("Name","name of jsonarray B "+i+" "+name);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}