check whether json object contains json array or not? - android

In my json response I getting json array and inside it there are 80 other json object and in each object has elements and some of objects has JsonArray also. So how can I check that whether json array is present or not?
I have tried optjsonarray also but it did not work for me.
Here is my code:
public static void insertMyDiaryValues(final JSONObject jobject)
throws Throwable {
String arrOfColumn[] = new String[] { "uuid", "date", "title", "diary",
"pictureurl", "pictureWidth", "pictureHeight", "child" };
try {
SmartTable DiaryData = null;
DiaryData = SmartApplication.REF_SMART_APPLICATION.getDataHelper()
.getTableList().get(DBTblNames.MyDiaryValues);
try {
JSONArray jarr = new JSONArray(jobject.getJSONArray("diary"));
for (int i = 0; i < jarr.length(); i++) {
// String childValue = ""
// + jarr.getJSONObject(i).getJSONArray("child").length();
// System.out.println("child Value :-"
// + jarr.getJSONObject(i).getJSONArray("child").length());
// if (!(childValue == null)) {
DiaryData.insertRow(
arrOfColumn,
new String[] {
jarr.getJSONObject(i).get("uuid")
.toString(),
jarr.getJSONObject(i).get("date")
.toString(),
jarr.getJSONObject(i).get("title")
.toString(),
jarr.getJSONObject(i).get("diary")
.toString(),
jarr.getJSONObject(i).get("pictureurl")
.toString(),
jarr.getJSONObject(i).get("pictureWidth")
.toString(),
jarr.getJSONObject(i).get("pictureHeight")
.toString(),
""
+ jarr.getJSONObject(i)
.getJSONArray("child")
.length()
});
}
} catch (Exception e) {
}
}
catch (Exception e) {
// TODO: handle exception
}
}

Simply check using try-catch case :
try{
JSONArray jsonArray = jsonObject.getJSONArray("key");
}catch (JSONException e){
e.printStackTrace();
// here write your code to get value from Json object which is not getJSONArray.
}

The below code worked for me :-
public static void insertMyDiaryValues(final JSONObject jobject) {
String arrOfColumn[] = new String[] { "uuid", "date", "title", "diary",
"pictureurl", "pictureWidth", "pictureHeight", "child" };
try {
SmartTable DiaryData = null;
DiaryData = SmartApplication.REF_SMART_APPLICATION.getDataHelper()
.getTableList().get(DBTblNames.MyDiaryValues);
JSONArray jarr = new JSONArray(jobject.getJSONArray("diary")
.toString());
for (int i = 0; i < jarr.length(); i++) {
String child;
if (jarr.getJSONObject(i).has("child")) {
child = ""
+ jarr.getJSONObject(i).getJSONArray("child")
.length();
} else {
child = "0";
}
try {
DiaryData.insertRow(arrOfColumn,
new String[] {
jarr.getJSONObject(i).get("uuid")
.toString(),
jarr.getJSONObject(i).get("date")
.toString(),
jarr.getJSONObject(i).get("title")
.toString(),
jarr.getJSONObject(i).get("diary")
.toString(),
jarr.getJSONObject(i).get("pictureurl")
.toString(),
jarr.getJSONObject(i).get("pictureWidth")
.toString(),
jarr.getJSONObject(i).get("pictureHeight")
.toString(), child
});
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
} catch (Exception e) {
// TODO: handle exception
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Related

List item to list view

I want to convert this program to dynamic. Get JSON from server and return to list item.
public List<Item> getData() {
return Arrays.asList(
new Item(1, "Everyday" , "$12.00 USD"),
new Item(2, "Small Porcelain Bowl", "$50.00 USD"),
new Item(3, "Favourite Board", "$265.00 USD"),
);
}
I parsed the json but return type error.
Error:(73, 8) error: incompatible types: List<String> cannot be converted to List<Item>
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
Information:BUILD FAILED in 13s
Information:2 errors
Here my code:
List<String> listItems = new ArrayList<String>();
try {
URL arc= new URL(
"https://arc.000webhostapp.com/data/Cse.json");
URLConnection tc = arc.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.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);
listItems.add(jo.getString("text"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItem;
You've declared that your function will return a List of Item objects but instead you're returning a List of String objects. When parsing the JSON you get from the server you must turn it into the same Item objects like you did in the offline version of your code.
Judging by your code the JSON that you download from the server looks something like this:
[
{
id: 1,
text: "Everyday",
price: "$12.00 USD"
},
{
id: 2,
text: "Small Porcelain Bowl",
price: "$50.00 USD"
},
{
id: 3,
text: "Favourite Board",
price: "$265.00 USD"
},
]
Your function should then look something like this:
public List<Item> getData() {
List<Item> listItems = new ArrayList<Item>();
try {
URL arc= new URL(
"https://arc.000webhostapp.com/data/Cse.json");
URLConnection tc = arc.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.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);
listItems.add(new Item(jo.getInt("id"), jo.getString("text"), jo.getString("price")));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}

Multiple rows data in single textview android

Here is the code i had tried with multiple times to get multiple rows values in a single text view with json.
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textview.setText(json.getString("survey_textresponse"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Hiding progress bar after done loading TextView.
progressbar.setVisibility(View.GONE);
}
}
}
when i run php file in chrome directly it shows all values from database while in android app it shows only the first row value.
Because you are only storing the last value of JSONobject in json reference
// assume JArray length = 5
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
// only have last object value , in last iteration jArray.getJSONObject(4)
}
There can be many solutions to this
Collect data as list of Values
Collect in a String or StringBuilder Object
StringBuilder sb = new StringBuilder();
// or List<String> list = new ArrayList<>();
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
sb.append(json.optString("survey_textresponse")+"\n");
// or list.add(json.optString("survey_textresponse"));
}
and later
textview.setText(sb.toString());
// or can collect list as string using loop and display it
The loop that you've written for retrieving the values from the JSONArray is not proper. Its only storing the last object while iterating through the loop. You could store the retrieved values in a collection of string.
Here's an example code you could follow:
private class RetrieveTask extends AsyncTask<Void,Void,Void>{
List<String> jsonResults;
String str;
JSONObject json;
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonResults=new ArrayList<>();
}
#Override
protected void onPostExecute(Void aVoid) {
for(String data:jsonResults)
textview.append(data);
}
#Override
protected Void doInBackground(Void... voids) {
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.5/send-data.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jArray = new JSONArray(str);
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
if(json.optString("survey_textresponse")!=null){
jsonResults.add(json.getString("survey_textresponse"));
}
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Your json variable contains only last element of JsonArray when it is finished. You can display on TextView while retrieving your values from JsonArray.
for( int i=0; i <jArray.length(); i++) {
json = jArray.getJSONObject(i);
textview.setText(textview.getText() + json.getString("survey_textresponse") + "\n");
}

unable to save data to txt in loop asynctask

I am trying to save every output data in asynctask for each http call.But I am unable to see any data in a file.I really appreciate any help.Thanks in Advance.
final String[] ar={"1","2","3",.............,"25"}
filename="test_file";
myFile = new File("/sdcard/"+filename);
try {
myFile.createNewFile();
fOut = new FileOutputStream(myFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
myOutWriter = new OutputStreamWriter(fOut);
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = params[0];
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(url_select));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
//
// // Read content & Log
// inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return null;
} // protected Void doInBackground(String... params)
protected void onPostExecute(Void v) {
//parse JSON data
try{
JSONObject jArray = new JSONObject(result);
String name = jArray.getString("name");
if (name!=null) {
Log.w("idname", name);
//
myOutWriter.append(name).append("\r\n");
//
Toast.makeText(getBaseContext(), name, 5).show();
}
// End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
for ( j = 0; j < ar.length; j++) {
u="http://www.example.com/"+ar[j];
JSONParser jParser=new JSONParser();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,u);
}
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You close the myOutWriter after start MyAsyncTask. So when MyAsyncTask try to write data to file, it throw OutputStreamWriter is closed exception.
You need remove the code of close myOutWriter from here. Add add close code at the end of onPostExecute like below:
void onPostExecute(Void v) {
.....
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = taskCount.decrementAndGet()
if(count == 0 ) {
try {
myOutWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // protected void onPostExecute(Void v)
the definition of taskCount is like this:
AtomicInteger taskCount = new AtomicInteger(ar.length - 1);
At last, I think Thread and CountDownLatch is better option
check if entity not null then write to db
HttpEntity entity = response.getEntity();
if(entity!=null ){
inputStream = entity.getContent();
}

Parsing asmx returned JSON on Android

I have an ASP.Net 3.5 Webservice (asmx) that returns what appears to be valid JSON. I have validated the returned JSON using an online validator (JSONLint . com) and it says it is valid. I can not figure out how to parse this string.
{
"d": "{\"returnType\":\"authToken\",\"returnData\":\"b1ec28b8-3fca-427a-bbce-8802fb95d94b\"}"
}
Below is my code.
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
JSONObject joD = joRaw.getJSONObject("d");
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
try this way
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
String str1 = joRaw.getString("d");
JSONObject joD = new JSONObject(str1);
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
try this one. In your sample response, d is a an attribute, not a JSONObject. So have to parse the string first, then convert the d string as a JSONObject.
public static JSONObject DotNetJSONResponse(String raw) throws Exception {
JSONObject joRaw;
try {
joRaw = new JSONObject(raw);
String t=joRaw.getString("d");
System.out.println(t); \\< ----------
JSONObject joD = new JSONObject(t);
return joD;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}

Json MySql get Two Integers and a String

Here is the class where i get JSON objects. In this code I get only one object and I don't really know how to return from the method, there is a Protected Void method where it is a settext method called and there is where the only JSON object goes.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://79.114.48.119/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("latitude");
}
public JSONObject lastTweet(String username) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet("");
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}
}
}
What I want to do is to have an array where i could store three kind of objects (exemple Latitude[1], Longitude [1], Description[1]; Latitude[2] etc... I would like the latitude and longitude to be as integers ). After this I will use a for loop to call a function with this 3 parameters. Could anyone help me or could give me some tips ?
Thank you!
Dont use AsyncTask, as it executes in background, and this is why it causes some problems for you.
And when you have your twitter arser working, integrate it in a AsyncTask. Code below is not tested.
public class ConnectMySql extends Activity {
TextView httpStuff;
HttpClient client;
int i;
JSONObject json;
final static String URL = "http://localhost/RadarsMySql.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
for(i=0;i<2;i++){
new Read().execute("latitude");
try {
json = lastTweet("",i);
String result = json.getString(params[i]);
httpStuff.setText(result);
int myNum = 0;
try {
myNum = Integer.parseInt(result);
httpStuff.setText(myNum);
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public JSONObject lastTweet(String username,int i) throws ClientProtocolException, IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
//if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
data = data.substring(data.indexOf("["));
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(i);
return last;
//}else{
//Toast.makeText(ConnectMySql.this, "error", Toast.LENGTH_LONG);
//return null;
//}
}
}

Categories

Resources