将字符串从Post Execute传递到全局变量

时间:2018-09-09 10:18:21

标签: android android-asynctask

我试图将onPostexecute上的结果传递给Global Variabless类,并在booklist类中获取值,以检查数据库中是否已有bookid和借款人id。 我的php正常工作。

BackgroundWorkerReserve类

/**
* 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();
    }
}

全局变量类

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

Booklist类:

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;
            }
        });
    }
}

但看起来像GlobalVariable.BorrowerIDh在我的长按中没有任何价值,但是当我在onpostExecute上烘烤它时就具有价值

2 个答案:

答案 0 :(得分:0)

Asynctasks doInBackground在不同的线程上运行。因此,在bwChecker.execute()之后,您的异步任务doInBackground被调用,并且bwChecker.execute()之后的代码将在onPostExecute.之前执行。要将结果发送回活动,您可以使用{ {1}}

编辑

在您的broadcastReceiver

onPostExecute.

在您的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);
        }

答案 1 :(得分:0)

我建议您像下面那样创建监听器/回调

第1步:创建监听器/回调

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

步骤2:修改AsyncTask构造函数

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

步骤3:修改onPostExecute

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

最终步骤

backWorkerReserveCheck bwChecker = new backWorkerReserveCheck(BookList.this, new OnProcessCallback(){
  public void onComplete(String data){
   // do the stuff here
  }
});