Tom
Tom

Reputation: 561

Error Parsing JSON Data - Asynchronous Task

I am getting the error Error parsing Data which I have caught in the main exception when parsing JSON Data.

However - my error No Data Found is not being caught in the JSONException, which makes me think that the database is being read successfully,

I have a php file on my server:

<?php

mysql_connect("database_ip","database_username","database_password");
mysql_select_db("database_name");

$sql=mysql_query("select * from table");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));// this will print the output in json

mysql_close();
?>

Navigating the to the php file online shows the JSON data as expected:

[{"KEY_ROWID":"1","KEY_NAME":"Andrew","KEY_SCORE":"100","KEY_DATE":"0000-00-00 00:00:00"},{"KEY_ROWID":"2","KEY_NAME":"Peter","KEY_SCORE":"5000","KEY_DATE":"2013-11-29 10:58:21"}]

In Android, I use an Async task to read the data:

class Task extends AsyncTask<String, String, Void> {
        InputStream is = null;
        String result = "";

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            String url_select = "http://mywebsite.com/myphpfile.php";

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_select);

            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(param));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // read content
                is = httpEntity.getContent();

            } catch (Exception e) {

                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            return null;
        }

        protected void onPostExecute(Void v) {
            try {

                JSONArray Jarray = new JSONArray(result);
                for (int i = 0; i < Jarray.length(); i++) {
                    JSONObject Jasonobject = Jarray.getJSONObject(i);
                    text = (TextView) findViewById(R.id.textView1);
                    // get an output on the screen
                    String name = Jasonobject.getString("KEY_NAME");
                    text.append(name + "\n");

                }

            }

            catch (JSONException e1) {
                Toast.makeText(getBaseContext(), "NO Data Found",
                        Toast.LENGTH_LONG).show();
            }

            catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error parsing data " + e.toString());
            }

        }

    }

In my activites onCreate I instantiate the Async Class:

new Task().execute();

Any suggestions on why there is an error parsing data?

Thanks

Note : outputting the variable 'result' with println () outputs the Json to the logcat as expected

Upvotes: 1

Views: 551

Answers (2)

Rahul Gupta
Rahul Gupta

Reputation: 5295

Dud i pasted your json in a local file in assets folder and tried to retrieve it. It is working fine. Here is my code. I cannot use your code because the url will not work from my side . Anyways, here is my code :-

    package com.example.test;

import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {
    static InputStream is = null;
    static JSONObject jObj = null;
    String jsonString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Making HTTP request
        // String url = "http://api.worldbank.org/countries/ir?format=json";
        String url = "http://10.0.2.2/andApp/artikel.php";
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        // JSONArray json = jParser.getJSONFromUrl(url);
        // JSONObject json = jParser.getJSONFromUrl1(url);
        // JSONObject json = null;
        JSONArray json = null;
        try {
            InputStream is = getAssets().open("json1.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            jsonString = new String(buffer, "UTF-8");

            // json = new JSONObject(jsonString);
            json = new JSONArray(jsonString);

        } catch (Exception e) {
            e.printStackTrace();

        }

        try {
            JSONArray json2 = json;
            // .getJSONArray("artikel");

            for (int i = 0; i < json2.length(); i++) {

                JSONObject c = json2.getJSONObject(i);
                // Storing JSON item in a Variable
                String name = c.optString("KEY_ROWID", "");
                String capitalCity = c.optString("KEY_NAME", "");
                String score = c.optString("KEY_SCORE", "");
                String date = c.optString("KEY_DATE", "");

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77912

Form your code:

...
catch (Exception e) {
            // TODO: handle exception
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

The problem is that it might be not Json exception but any Exception. In practice it is not recommended to catch type Exception. We should only catch specific subtypes of the Exception class. In our case findViewById throws : NullPointerException. So first of all change it to NullPointerException (in additional to JSONException) and run program again.

I would change Error parsing data to something generic.

Suppose we don't have Exception on findViewById and our text is not null.

Try to use Handler to update main thread (aka GUI):

private Handler mHandler = null;

 ...

 mHandler = new Handler();

 ... 

    mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    text = (TextView) findViewById(R.id.textView1);
                    JSONArray Jarray = new JSONArray(result);
                    for (int i = 0; i < Jarray.length(); i++) {
                        JSONObject Jasonobject = Jarray.getJSONObject(i);

                        // get an output on the screen
                        String name = Jasonobject.getString("KEY_NAME");
                        text.append(name + "\n");
                    }
                }

                catch (JSONException e1) {
                    Toast.makeText(getBaseContext(), "NO Data Found",
                            Toast.LENGTH_LONG).show();
                }

                catch (NullPointerException e) {
                    // TODO: handle exception
                    Log.e("log_tag", "Error  " + e.toString());
                }
            }
        }, 100); // dummy delay

As a side note:

The row text = (TextView) findViewById(R.id.textView1); put outside of the loop for

Upvotes: 2

Related Questions