I have a web service returning the following string verbatim:
"{\"type\":\"youtube\", \"data\":\"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk\",\"pixel_id\":\"471\",\"x\":\"12\",\"y\":\"14\",\"pid\":\"4\",\"surface_id\":\"7\",\"data_id\":\"7224\",\"user_id\":\"4\"}"
Code looks lke:
dataScanner.client = new DefaultHttpClient();
dataScanner.post = new HttpPost("http://someurl/somepage.php");
post.setEntity(new UrlEncodedFormEntity(userKV));
Log.d("DST Scanner", "post string:" + post.toString());
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line);
}
Log.d("DST Scanner", "Post Response (string)" + builder.toString());
//JSONTokener tokener = new JSONTokener(builder.toString());
finalResult = new JSONObject(builder.toString());
I've tried many different formats (escaped quotes, unescaped quotes, no surrounding quotes, escaped forward slashes), but I keep getting this error:
org.json.JSONException: Value {"type":"youtube", "data":"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk","pixel_id":"471","x":"12","y":"14","pid":"4","surface_id":"7","data_id":"7224","user_id":"4"} of type java.lang.String cannot be converted to JSONObject
Everything looks fine to me, but I've been looking at this so long I wouldn't be surprised if there's some silly thing I'm doing..
I'm new to json, but all of my JSON start and end with "[" and "]" and I use PHP to echo out the json_encode method.
On Android side i use:
try {
URL pHH = new URL("http://192.168.1.5/somephp.php");
URLConnection WC = pHH.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(WC.getInputStream()));
String line;
while((line = in.readLine()) != null){
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++){
JSONObject jo = (JSONObject) ja.get(i);
items[i] = jo.getString("title");
thumbnails[i] = jo.getString("thumb");
links[i] = jo.getString("link");
}
}
char[] utf8 = null;
StringBuilder properString = new StringBuilder("");
utf8 = Response.toCharArray();
for (int i = 0; i < utf8.length; i++) {
if ((int) utf8[i] < 65000) {
properString.append(utf8[i]);
}
}
System.out.println("Response of Login::"
+ properString.toString());
Related
i have diplayed the list name in logcat, but i am having difficulty in retreiving subscribers in list which i made in the mailChimp
what would be the perfect way to do this using AsyncTask?
thanks!
public class FetchLists extends AsyncTask<Integer, Void, List<MailChimpList>> {
#Override
protected List<MailChimpList> doInBackground(Integer... params) {
int count = params[0];
int offset = params[1];
String urlString = "https://us11.api.mailchimp.com/3.0/lists?apikey=..............";
urlString = urlString + "&count=" + count + "&offset=" + offset;
List<MailChimpList> listTitles = new ArrayList<>();
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while(line != null){
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
int itemCount = object.getInt("total_items");
Log.d("ashu", "total item count is " + itemCount);
JSONArray lists = object.getJSONArray("lists");
for (int i = 0; i < lists.length(); i++) {
JSONObject listData = (JSONObject) lists.get(i);
MailChimpList mailChimpList = new MailChimpList();
mailChimpList.id = listData.getString("id");
mailChimpList.title = listData.getString("name");
JSONObject contact = listData.getJSONObject("contact");
mailChimpList.emailId=contact.getJSONArray("lists/{list_id}/members");
listTitles.add(mailChimpList);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("codekamp", listTitles.get(1).id.toString());
Log.d("codekamp",listTitles.get(1).title.toString());
Log.d("codekamp",listTitles.get(1).emailId.toString());
return listTitles;
}
}
i want to retreive the list of all subscribers for a particular listname which are stored in it!
error:
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: in.codekamp.asynctaskdemo, PID: 17134
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at in.codekamp.asynctaskdemo.FetchLists.doInBackground(FetchLists.java:74)
at in.codekamp.asynctaskdemo.FetchLists.doInBackground(FetchLists.java:21)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
i have written some code to help you get the response
String urlString = "https://us11.api.mailchimp.com/3.0/lists?apikey=efb91redfef1215rac5rff4c8sdsfsf8a77-us11";
urlString = urlString + "&count=" + count + "&offset=" + offset;
List<String> listTitles = new ArrayList<>();
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while(line != null){
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
int itemCount = object.getInt("total_items");
Log.d("ashu", "total item count is " + itemCount);
JSONArray lists = object.getJSONArray("lists");
for (int i = 0; i < lists.length(); i++) {
JSONObject listData = (JSONObject) lists.get(i);
String id= listData.getString("id");
String title = listData.getString("name");
JSONObject contact = listData.getJSONObject("contact");
JSONArray list=contact.getJSONArray("lists");
JSONObject contactdata = list.getJSONObject(0);
String company=contactdata.getString("student");
JSONArray links = object.getJSONArray("_links");
for(int j=0;j<=links.length();i++)
{
JSONObject linkobjects = (JSONObject) links.get(i);
String relevance=linkobjects.getString("rel");
Log.d("rel", ""+relevance);
}
Log.d("id", ""+id);
Log.d("name", ""+title);
Log.d("cmpny", ""+company);
listTitles.add(mailChimpList);}
from this you can understand the code and you can store in your list. hope it helps.
I've an asynctask , this is the code inside background :
try {
URL url = new URL(urls);
Log.v("this", urls);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineC;
StringBuffer sb = new StringBuffer();
while ((lineC = bufferedReader.readLine()) != null)
{
sb.append(lineC );
}
Log.v("this",sb.toString() + " I need this for something else");
NodeList nodes = doc.getElementsByTagName("data");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("content");
Element line = (Element) title.item(0);
if (i == 0)
random = line.getTextContent();
else if (i == 1)
topsell = line.getTextContent();
else if (i == 2)
jadidtarin = line.getTextContent();
else if (i == 3)
pishnahad = line.getTextContent();
}
} catch (Exception e) {
e.printStackTrace();
goterror = true;
Log.v("this", e.getMessage() + "eror");
}
When I remove these lines , it works fine and I get no problem.
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineC;
StringBuffer sb = new StringBuffer();
while ((lineC = bufferedReader.readLine()) != null)
{
sb.append(lineC );
}
I don't close anything but when I run the code, I get this error "Stream is closed" , I don't know why .
How can I solve this problem ? as I said in the code, I need to save the whole returned value .
How can I solve this problem ?
Instead of using:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Use
BufferedReader bufferedReader = new BufferedReader(new BufferedInputStream(conn.getInputStream()));
I have a json response as shown below
[
{
"id": "1",
"name": "b day",
"date": "2015-12-08",
"start_time": "00:50:02",
"end_time": "05:00:00"
},
{
"id": "2",
"name": "game",
"date": "2015-11-18",
"start_time": "00:00:02",
"end_time": "09:10:00"
}
]
My android code to retrieve json is given below
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
You can get JSONArray like below.
JSONArray jsonArray = new JSONArray(responseString);
From array you can get JSONObject like below.
for(int i = 0 ; i< jsonArray.length() ; i++){
// This will get first JSONObject from JSONArray.
JSONObject jObject = jsonArray.getJSONObject(i);
// Get all key from array using JSONObject.
String id = jObject.getString("id");
String name = jObject.getString("name");
String date = jObject.getString("date");
String startTime = jObject.getString("start_time");
String endTime = jObject.getString("end_time");
}
Try this:
try
{
JSONObject issueObj = new JSONObject(JSONString);
Iterator iterator = issueObj.keys();
while (iterator.hasNext())
{
String key = (String) iterator.next();
JSONObject issue = issueObj.getJSONObject(key);
int pubKey = Integer.valueOf(issue.optString("id"));
mylist.add(pubKey);
JSONObject json = new JSONObject(JSONString);
JSONObject jArray = json.getJSONObject(String.valueOf(pubKey));
nameString = jArray.getString("name");
dateString = jArray.getString("date");
start_timeString = jArray.getString("start_time");
end_timeString = jArray.getString("end_time");
}
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Use this code
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
json = response.toString();
JSONArray jsonArray = new JSONArray(json);
ArrayList<String> al_ids=new ArrayList<String>();
Arraylist<String> al_name=new ArrayList<String>();
Arraylist<String> al_date=new ArrayList<String>();
Arraylist<String> al_start_time=new ArrayList<String>();
Arraylist<String> al_end_time=new ArrayList<String>();
for(int i = 0 ; i< jsonArray.length() ; i++){
// This will get first JSONObject from JSONArray.
JSONObject jObject = jsonArray.getJSONObject(i);
// Get all key from array using JSONObject.
String id = jObject.getString("id");
String name = jObject.getString("name");
String date = jObject.getString("date");
String startTime = jObject.getString("start_time");
String endTime = jObject.getString("end_time");
al_ids.add(id);
al_name.add(name);
al_date.add(date);
al_start_time.add(startTime);
al_end_time.add(endTime);
}
//here you can set text to Your TextView by getting position of arraylist
In my code I'm getting an array using a for loop. The array contains four values. How do I print the values in a textview? I want to print these four values in four textviews.
My Code:
HttpClient client2 = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client2.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client2.getParams(), 15000);
HttpUriRequest request2 = new HttpGet(SelectMenuAPI2);
HttpResponse response2 = client2.execute(request2);
InputStream atomInputStream2 = response2.getEntity().getContent();
BufferedReader in2 = new BufferedReader(new InputStreamReader(atomInputStream2));
String line2;
String str2 = "";
while ((line2 = in2.readLine()) != null) {
str2 += line2;
}
JSONObject json3 = new JSONObject(str2);
// message = json2.getString("message");
status = json3.getString("status");
if (status.equals("1")) {
JSONArray school2 = json3.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object3 = school2.getJSONObject(i);
Elementarytxt.settext("");
Middle.setText("");
High.setText("");
Atypical.setText("");
}
}
My JSON Data:
{
"status":1,
"data":[
{"title":"Elementary"},
{"title":"Middle"},
{"title":"High"},
{"title":"Atypical"}
]
}
JSONArray jsonArray = jObject.getJSONArray(ARRAYNAME);
if (jObject != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
txt.setttext(jsonObject.getString(CREATEDDATE));
txt.setttext(jsonObject.getString(SUBJECT));
}
}
Please check this. It might help you...
String [] mVal = new String[school2.length()];
for (int i = 0; i < school2.length(); i++)
{
mVal[i] =school2.getJSONObject(i).getString("title");
}
Elementarytxt.setText(mVal[0]);
Middle.setText(mVal[1]);
High.setText(mVal[2]);
Atypical.setText(mVal[3]);
I hope This will Help you..
String[] vals=new String[4];
for (int i = 0; i < school2.length(); i++) {
JSONObject object3 = school2.getJSONObject(i);
vals[i]=object3.getString("title");
}
Elementarytxt.settext(vals[0]);
Middle.setText(vals[1]);
High.setText(vals[2]);
Atypical.setText(vals[3]);
I'm begginer develop android.
I'm confuse. Because I didn't know to convert JSON to be view at Edit View (for example).
many totorial just view at Log.
this, my JSON file
EditText txt1 = (EditText) findViewById(R.id.Text1);
RestClient client = new RestClient("http://192.168.2.79/restserver/index.php/api/example/users");
//client.AddParam("id", "1"); //parameter
client.AddParam("format", "json"); //parameter format
client.AddHeader("GData-Version", "2"); //header
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Log.i("respon",response);
//Toast.makeText(this, "json : "+ response, 1).show();
//create json creation
try {
JSONObject json = new JSONObject(response);
Log.i("respon","<jsonobject>\n"+json.toString()+"\n</json>");
//Log.i("respon","<jsonobject>\n"+json.t
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
//try 1
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String[] id = new String[valArray.length()];
String[] name = new String[valArray.length()];
String Id,Name;
for(int i=0;i<valArray.length();i++) {
Log.i("respon","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
+"<jsonvalue"+i+"\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
//coba
JSONObject obj = valArray.getJSONObject(i);
id[i] = obj.getString("id");
name[i] = obj.getString("name");
//wanna show at EditView, ect (but I can't)
Toast.makeText(this, "id : " + " ,name : ", 1).show();
txt1.setText("id : " + id + " ,name : "+name);
}
how can to solve json to view not only at log. but also at object (widget android).
thanx alot guys....
I think your not able to get data from JSON go through with the following code.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("LINK");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
int statuscode = statusLine.getStatusCode();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is, "UTF8"), 16);
stringBuilder = new StringBuilder();
stringBuilder.append(bufferedReader.readLine() + "\n");
String line = "0";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
is.close();
Strign result = stringBuilder.toString();
JSONArray jArrayTemp = new JSONArray(result);
JSONObject json_data = null;
userID[i] = json_data.getString("UserID");
userName[i] = json_data.getString("UserName");
userLoginID[i] = json_data.getString("UserLoginID");
userPassword[i] = json_data.getString("UserPassword");
Try the above code.
If can take the help of below link also::
http://www.vogella.de/articles/AndroidJSON/article.html