0

It return exception when I run the php script. Here is my java class

public class ShowAllQuestions extends ListActivity {

    int cntChoice;
    ArrayList<String> selected;
    Button getChoice;
    // Progress Dialog
    private ProgressDialog pDialog;
    public static String mode;
    private static final String CONNECTION_FAILED_MSG = "connection";
    private ArrayList<String> nameList = new ArrayList<String>();
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    String id;
    ArrayList personList;

    // url to get all products list
    private static String url_all_products = "http://www.rpscadda.com/QuizAPP/getallmcq.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_Person = "person";
    private static final String TAG_PID = "id";
    private static final String TAG_NAME = "fname";
    private static final String TAG_RESULT = "result";


    // products JSONArray
    JSONArray person = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_questions);

        personList = new ArrayList<HashMap<String, String>>();
        final ListView myList=(ListView)findViewById(android.R.id.list);
        getChoice=(Button) findViewById(R.id.button);
        getChoice.setOnClickListener(new Button.OnClickListener(){



            @Override

            public void onClick(View v) {

                // TODO Auto-generated method stub



               selected=new ArrayList<String>();;



                cntChoice = myList.getCount();

                SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();

                for(int i = 0; i < cntChoice; i++){

                    if(sparseBooleanArray.get(i)) {

                        selected.add(i, myList.getItemAtPosition(i).toString()) ;

                         Log.d("Message",String.valueOf(selected.get(i)));



                        String selectedFromList =selected.get(i);
                        String a[]=selectedFromList.split(" ");
                        Toast.makeText(getApplicationContext(), a[0], Toast.LENGTH_SHORT).show();
                        selected.add(i,a[0]);
                        Log.d("Message",a[0]);





                    }

                }
                try {
                    //receiving result from Connect class.
                    String result = new Connect().execute().get();
                    if (result != null) {
                    Log.i("Test", result);

                        JSONObject jsonObject = new JSONObject(result);
                        String response = (String) jsonObject.get("result");
                        if(response.equals("success")){
                            Toast.makeText(getApplicationContext(),"connected",Toast.LENGTH_LONG).show();
                        } else if(response.equals(CONNECTION_FAILED_MSG)) {
                            Toast.makeText(getApplicationContext(), "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        Log.i("Test", "Result is empty");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }



            }});

        try {
            //receiving result from Connect class.
            ArrayList<String> result = new LoadAllProducts().execute().get();
            if(result != null){
                Log.i("BulkQuestions", "Updating");


                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                        android.R.layout.simple_list_item_multiple_choice, result);
                 myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                for(String r : result){
                    Log.i("BulkQuestions", r);
                }

                myList.setAdapter(adapter);
                myList.refreshDrawableState();

            }




        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }

    public class Connect extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            BufferedReader inBuffer = null;
            String result = "fail";


            //sending POST request.
            try {
                String url="http://www.rpscadda.com/QuizAPP/deletemcq.php";
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost request = new HttpPost(url);
                for(int i=0;i<selected.size();i++) {
                    List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

                    postParameters.add(new BasicNameValuePair("id", selected.get(i)));

                    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                            postParameters);

                    request.setEntity(formEntity);
                    //executing request and storing result.
                    HttpResponse httpResponse = httpClient.execute(request);

                    //translating into input stream
                    HttpEntity httpEntity = httpResponse.getEntity();
                    InputStream content = httpEntity.getContent();

                    //reading from the buffer.
                    BufferedReader reader = new BufferedReader(new InputStreamReader(content, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;

                    //storing into string.
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                }
            } catch(Exception e) {
                // Do something about exceptions
                result = e.getMessage();
                e.printStackTrace();
            } finally {
                if (inBuffer != null) {
                    try {
                        inBuffer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return  result;    }

        @Override
        protected void onPostExecute(String result) {

        }
    }
    class LoadAllProducts extends AsyncTask<String, String, ArrayList<String>> {


        protected ArrayList<String> doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                String result = json.getString(TAG_RESULT);

                if (result.equals("success")) {
                    // products found
                    // Getting Array of Products
                    person = json.getJSONArray("mcq");

                    // looping through All Products
                    for (int i = 0; i < person.length(); i++) {
                        JSONObject c = person.getJSONObject(i);

                        // Storing each json item in variable
                         id = c.getString("id");
                        String name = id +" "+c.getString("question");
                        nameList.add(name);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_NAME, name);

                        Log.i("BulkQuestions", name);

                        // adding HashList to ArrayList
                        personList.add(map);

                    }
                } else {                   Log.i("BulkQuestions", "result = failed");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return nameList;
        }

        @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        protected void onPostExecute(String file_url) {
        }

    }
}

here is my php code

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        $response['result']="connection";
        die("Connection failed: " . $conn->connect_error);
    } 


    $result = $conn->query("SELECT * FROM mcq");

    $num_rows = $result->num_rows;
    if($num_rows > 0){  
        // looping through all results
        // products node
        $response["mcq"] = array();

        while ($row = $result->fetch_assoc()) {
            // print_r($row);
            // temp user array
            $mcq= array();
            $mcq["id"] = $row["id"];
                    $mcq["question"] = utf8_decode($row["question"]);
            $mcq["op1"] = utf8_decode($row["op1"]);
            $mcq["op2"] = utf8_decode($row["op2"]);
            $mcq["op3"] = utf8_decode($row["op3"]);
            $mcq["op4"] = utf8_decode($row["op4"]);
            $mcq["correct"] = utf8_decode($row["correct"]);
            $mcq["explanation"] = utf8_decode($row["explanation"]);
            $mcq["maincat"] = $row["mainCategory"];
            $mcq["subcat"] = $row["subcategory"];



            $response["mcq"][] = $mcq;
        }
        $response['result']= "success";

    } else {
    //  echo "Error: " . $sql . "<br>" . $conn->error;
        $response['result']= "failed";
    }
    $conn->close();
     // echoing JSON response   
    echo json_encode($response);?>

My Logcat error [LogcatError][1] [1]: https://i.stack.imgur.com/M7BSb.png

My code works perfectly when I insert/retrieve short string in/from my table while if I insert long strings it works perfectly, although it gives this exception on retrieval.

I am a php beginner and posting my first question on stackoverflow, very sorry for poor description.

1 Answers1

0

From the description of the error, it looks like PHP returned empty JSON data. I am sure that you have already checked the table to make sure that the queried data exists in the table.

Are you able to check PHP log files? Can you run that PHP script (or a portion of it) on the server from command line so that you can check the errors and see the returned data?

blackpen
  • 2,339
  • 13
  • 15
  • Yes, the data exists in the table. I have checked the script by running it on chrome browser, when I add data in english/other language containing small no of characters it works perfectly while i enter large strings like this "400 character of other language" it stores the data in utf8-encoded string to the table and on retrieval it returns null. – Maryum Shiekh Oct 02 '16 at 19:28
  • When it returned null, are you able to see any errors in php/webserver/appserver log files? – blackpen Oct 02 '16 at 20:17
  • Look at this [post](http://stackoverflow.com/a/8059044/3196458). It advises you to escape your foriegn characters before you insert into MySQL so that they can be properly handled by json_encode() later. Look at your data in MySql to see if you have things like **u0644** instead of **\u0644** – blackpen Oct 02 '16 at 20:21
  • You are running utf8_decode on strings returned from database. Most of the posts on SO seems to advise the other way around; to run utf8_encode (if it has not already been encoded) and then run json_encode on it. Look [here](http://stackoverflow.com/a/9100349/3196458). Since we don't know what form your data is in the database, you may have to experiment with (1) by removing utf8_decode (2) by using utf8_encode on the strings returned from MySql. – blackpen Oct 02 '16 at 20:38
  • let me check. Thanks – Maryum Shiekh Oct 04 '16 at 14:40