-1

I'm trying to push Notifications of Book On Due today for my library Mobile app but after I log in this error pops up in my app.

4:run java.lang.string cannot be converted to JSONArray.

My PHP is working fine but how can I fix this error?

W/System.err: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
W/System.err:     at com.example.ivan.librarymobileapp.backWorkerNotif.doInBackground(backWorkerNotif.java:67)
W/System.err:     at com.example.ivan.librarymobileapp.backWorkerNotif.doInBackground(backWorkerNotif.java:23)
W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)

Here's my code:

backWorkerNotif Class

public class backWorkerNotif extends AsyncTask<String, String, String> {
   String result = null;
   String[] BookTittle;
   Context context;
   public  backWorkerNotif(Context context){this.context = context;}

   @Override
   protected String doInBackground(String... params) {
      String selectNotif_url = "http://192.168.254.120/LibrayAPI/SelectNotif.php";
      String type = params[0];

      if (type.equals("Notif")) {
        String DateNow = params[1];
        String BorrowerID = params[2];
        try {

          String data = URLEncoder.encode("date_now", "UTF-8") + "=" +
                        URLEncoder.encode(DateNow, "UTF-8");
                data += "$" + URLEncoder.encode("borrower_id", "UTF-8") + "=" +
                        URLEncoder.encode(BorrowerID, "UTF-8");

               URL url = new URL(selectNotif_url);
               URLConnection urlConnection = url.openConnection();
               urlConnection.setDoOutput(true);

               OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());

               outputStreamWriter.write(data);
               outputStreamWriter.flush();

               BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
               StringBuilder sb = new StringBuilder();
               String line;
               while ((line = bufferedReader.readLine()) != null) {

                 sb.append(line + "\n");
               }
               result = sb.toString();
            } catch (Exception ex) {


            }
            //Json
            try {
                JSONArray jsonArray = new JSONArray(result);
                JSONObject jsonObject;
                BookTittle = new String[jsonArray.length()];
                for (int i = 0;i< jsonArray.length();i++){
                    jsonObject = jsonArray.getJSONObject(i);
                    BookTittle[i] = jsonObject.getString("BookTittle");

                    NotificationCompat.Builder  mbuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_book_black_24dp)
                            .setContentTitle("Library notification")
                            .setContentText("Today is the Due Day of"+ BookTittle[i] +"You Borrowed");
                    NotificationManager notificationManager =(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
                    notificationManager.notify(0,mbuilder.build())
                }   
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String jsonArray) {
        super.onPostExecute(jsonArray);
    }
}

Log In Classs

public class Login extends AppCompatActivity {

    EditText username,password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = findViewById(R.id.edtUsername);
        password = findViewById(R.id.edtPassword);
    }

    public void onLogin(View view) {

        String Username = username.getText().toString();
        String Password = password.getText().toString();
        backWorkerNotif backWorkerNotif = new backWorkerNotif(this);
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat SF = new SimpleDateFormat("yyyy-MM-dd");
        String DateNow = SF.format(date);
        backWorkerNotif.execute("Notif", DateNow, Username);

        String Type = "login";
        GlobalVariable.BorrowerID = Username;
        backgroundWorker _backgroundWorker = new backgroundWorker(this);
        _backgroundWorker.execute(Type, Username, Password);
    }
}

My php Code

<?php
require "Connection.php";
$DateNow = $_POST["date_now"];
$BorrowerID = $_POST["borrower_id"];

$query = "SELECT A.`BookId`,B.`BookTittle`,A.`BorrowerId` FROM `tblborrow` AS A INNER JOIN `tblbooks` AS B ON A.`BookId` = B.`BookId` WHERE `DueDate` = '$DateNow' AND `BorrowerId` = '$BorrowerID'";
$result = mysqli_query($conn,$query);

while($e = mysqli_fetch_assoc($result)){
    $output[] = $e;
}
echo json_encode($output);
print (json_encode($output));
?>

The result from my PHP

[
  {"BookId":"101","BookTittle":"Counting dolars","BorrowerId":"11"},
  {"BookId":"9876","BookTittle":"ihi","BorrowerId":"11"},
  {"BookId":"542","BookTittle":"hiragana","BorrowerId":"11"},
  {"BookId":"5421","BookTittle":"wow","BorrowerId":"11"}
][
  {"BookId":"101","BookTittle":"Counting dolars","BorrowerId":"11"},
  {"BookId":"9876","BookTittle":"ihi","BorrowerId":"11"},  
  {"BookId":"542","BookTittle":"hiragana","BorrowerId":"11"},  
  {"BookId":"5421","BookTittle":"wow","BorrowerId":"11"}
] 

What did I do wrong?

9
  • This is happening because something is going wrong with your php script output. Try to run this script i postman. Commented Sep 12, 2018 at 4:05
  • Whats the format of the result ? Can you share please Commented Sep 12, 2018 at 4:05
  • And you should use that result in ‘onPostExucute()’ Commented Sep 12, 2018 at 4:06
  • May be its because I use echo and print on my php? Commented Sep 12, 2018 at 4:10
  • [{"BookId":"101","BookTittle":"Counting dolars","BorrowerId":"11"},{"BookId":"9876","BookTittle":"ihi","BorrowerId":"11"},{"BookId":"542","BookTittle":"hiragana","BorrowerId":"11"},{"BookId":"5421","BookTittle":"wow","BorrowerId":"11"}][{"BookId":"101","BookTittle":"Counting dolars","BorrowerId":"11"},{"BookId":"9876","BookTittle":"ihi","BorrowerId":"11"},{"BookId":"542","BookTittle":"hiragana","BorrowerId":"11"},{"BookId":"5421","BookTittle":"wow","BorrowerId":"11"}] Commented Sep 12, 2018 at 4:16

1 Answer 1

0

as Exception says you have received <br value in response which is not json format.

put "application/json" as header for your request content-type. but this is not guarantee that your code will always work. by doing so you only make sure that you will receive response in json format.

the problem is about format of output stream. if your connection get any type of HTTP exception or other type of errors, you will not get aware, since you swallow it. change it in this way:

try {

                String data = URLEncoder.encode("date_now", "UTF-8") + "=" +
                        URLEncoder.encode(DateNow, "UTF-8");
                data += "$" + URLEncoder.encode("borrower_id", "UTF-8") + "=" +
                        URLEncoder.encode(BorrowerID, "UTF-8");

                URL url = new URL(selectNotif_url);
                URLConnection urlConnection = url.openConnection();
                urlConnection.setDoOutput(true);

                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());

                outputStreamWriter.write(data);
                outputStreamWriter.flush();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {

                    sb.append(line + "\n");
                }
                result = sb.toString();
                //JSON
                JSONArray jsonArray = new JSONArray(result);
                JSONObject jsonObject;
                BookTittle = new String[jsonArray.length()];
                for (int i = 0;i< jsonArray.length();i++){
                    jsonObject = jsonArray.getJSONObject(i);
                    BookTittle[i] = jsonObject.getString("BookTittle");

                    NotificationCompat.Builder  mbuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_book_black_24dp)
                            .setContentTitle("Library notification")
                            .setContentText("Today is the Due Day of"+ BookTittle[i] +"You Borrowed");
                    NotificationManager notificationManager =(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
                    notificationManager.notify(0,mbuilder.build());


                }


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

Please provide us with sample out put which you receive from php. I mean the result value

Sign up to request clarification or add additional context in comments.

7 Comments

I cant see the difference between my code with your code
I have merged two try-catch blocks into one block
} catch (Exception ex) { } //Json try { are removed
okey thankyou .found the issue the $ is supposed to be & in my UrlEncoder
I have another question sir .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.