-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?

Roy Scheffers
  • 3,832
  • 11
  • 31
  • 36
  • This is happening because something is going wrong with your php script output. Try to run this script i postman. – Zankrut Parmar Sep 12 '18 at 04:05
  • Whats the format of the result ? Can you share please – Abdul Kawee Sep 12 '18 at 04:05
  • And you should use that result in ‘onPostExucute()’ – Abdul Kawee Sep 12 '18 at 04:06
  • May be its because I use echo and print on my php? – Kim Ivan Bay-an Sep 12 '18 at 04: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"}] – Kim Ivan Bay-an Sep 12 '18 at 04:16
  • Possible duplicate of [org.json.JSONException: Value
    – Rohit5k2 Sep 12 '18 at 04:28
  • you likely receive not a JSONArray as a response for some reason – Vladyslav Matviienko Sep 12 '18 at 04:40
  • found it in my 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"); $ suppose to & but its only pushing the last data in my notification – Kim Ivan Bay-an Sep 12 '18 at 04:48
  • okey it good now – Kim Ivan Bay-an Sep 12 '18 at 04:49

1 Answers1

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

Mahdi Rajabi
  • 582
  • 1
  • 4
  • 11