0

I was trying to pass the result on my onPostexecute to my Global Variabless class and get the value in my booklist class, for checking if the bookid and borrower id is already on my database. my php is working.

BackgroundWorkerReserve class:

/**
* Created by ivan on 9/9/2018.
*/

public class backWorkerReserveCheck extends AsyncTask<String, String ,String> {
    Context context;
    backWorkerReserveCheck(Context ctx){
    context = ctx;
    }


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

    if (type.equals("Checking")){
        String BorrowerID = params[1];
        String BookID = params[2];

        try {
            String data = URLEncoder.encode("borrower_id","UTF-8") + "=" +
            URLEncoder.encode(BorrowerID,"UTF-8");
            data += "&" + URLEncoder.encode("book_id","UTF-8") + "=" +
            URLEncoder.encode(BookID,"UTF-8");

            URL url = new URL(Checker_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);
                break;
            }
            publishProgress(sb.toString());
            return  sb.toString();
        }catch (Exception ex){
            return new String("Error"+ ex.getMessage());
        }
    }

    return null;
    }

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

    }

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

        GlobalVariable.Checker_Result = result;
        Toast.makeText(context, GlobalVariable.Checker_Result, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        GlobalVariable.Checker_Result = values.toString();
    }
}

Global variable class:

public class GlobalVariable {
    public  static String  BorrowerID;
    public  static  String Checker_Result;
}

Booklist class:

public class BookList extends AppCompatActivity {

    ListView listBooks;

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


        listBooks = findViewById(R.id.listView);
        StrictMode.setThreadPolicy((new StrictMode.ThreadPolicy.Builder().permitNetwork().build()));
        collectData();
        CustomAdapter customAdapter = new CustomAdapter(this, bookId, booktittle, Quantity, Author);
        listBooks.setAdapter(customAdapter);

        listBooks.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView id = view.findViewById(R.id.txtBookID);

                Date currentDate = Calendar.getInstance().getTime();
                SimpleDateFormat SF = new SimpleDateFormat("yyyy-MM-dd");
                String currentsateFormat = SF.format(currentDate);

                backgroundWorkerReserve bw = new backgroundWorkerReserve(BookList.this);

                backWorkerReserveCheck bwChecker = new backWorkerReserveCheck(BookList.this);
                bwChecker.execute("Checking",GlobalVariable.BorrowerID,id.getText().toString());


                if (GlobalVariable.Checker_Result.equals("Has rows")){
                    Toast.makeText(BookList.this, "You already reserve this book", Toast.LENGTH_SHORT).show();
                }else {
                    String type = "Reserve";
                    bw.execute(type, GlobalVariable.BorrowerID, id.getText().toString(), currentsateFormat);
                }

                return false;
            }
        });
    }
}

but seems like GlobalVariable.BorrowerIDh has no value in my long click but when i toast it on my onpostExecute it has value

Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
  • Your question has answer here [How to get the result of OnPostExecute() to main activity](https://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a) – Mohamed Shannan Sep 09 '18 at 10:47

2 Answers2

0

Asynctasks doInBackground runs on different thread. So after bwChecker.execute() your asynctask doInBackground is called and your code after bwChecker.execute() will be executed before onPostExecute. For sending result back to activity you can use broadcastReceiver from onPostExecute.

EDIT

In your BookList

    public static final String BROADCAST_ACTION = "BROADCAST_ACTION";

       BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction() != null &&
                        intent.getAction().equals(BROADCAST_ACTION)) {
                    Bundle bundle = intent.getExtras();
                    if (bundle!=null){
                        String type = bundle.getString("CHECKER_RESULT");
                        if (type.equals("Has rows")){
                            Toast.makeText(BookList.this, "You already reserve this book", Toast.LENGTH_SHORT).show();
                        }
                        else {
// Not sure were you are setting value to `GlobalVariable.BorrowerID` as i didnt found it in code you have posted
                            bw.execute("Reserve", GlobalVariable.BorrowerID, id.getText().toString(), currentsateFormat);
                        }
                    }
                }
            }
        };


        @Override
        protected void onResume() {
            super.onResume();
            LocalBroadcastManager.getInstance(
                    BookList.this).registerReceiver(broadcastReceiver, new IntentFilter(BROADCAST_ACTION));
        }

        @Override
        protected void onPause() {
            super.onPause();
            LocalBroadcastManager.getInstance(BookList.this).unregisterReceiver(broadcastReceiver);
        }

In your onPostExecute

    Intent intent = new Intent(BookList.BROADCAST_ACTION);
    intent.putExtra("CHECKER_RESULT", result);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
prashant17
  • 1,520
  • 3
  • 14
  • 23
0

I would recommned you to create listener/callback like below

Step 1: create listener/callback

public interface OnProcessCallback{
  public void onComplete(String data);
}

Step 2: Modify AsyncTask constructor

OnProcessCallback callback;
backWorkerReserveCheck(Context ctx,OnProcessCallback callback){
    context = ctx;
    this.callback = callback;
}

Step 3: Modify onPostExecute

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    callback.onComplete(result);
    Toast.makeText(context, GlobalVariable.Checker_Result, Toast.LENGTH_SHORT).show();
}

Step final

backWorkerReserveCheck bwChecker = new backWorkerReserveCheck(BookList.this, new OnProcessCallback(){
  public void onComplete(String data){
   // do the stuff here
  }
});
Krishna Sharma
  • 2,828
  • 1
  • 12
  • 23