如何根据用户输入刷新文本视图?多线程问题



我正在检查一个值:borrow[0] ,在此基础上我需要刷新TextView称为message 。 所有这些都发生在一个method()内,该在我的片段onCreateView()中从事件中调用button.setOnClickListener

if (borrow[0]) {
    Log.i("inside borrow", borrow[0] +"");
    message.setText("You have successfully borrowed the book. Due date is" + dueDate[0].substring(0, Math.min(dueDate[0].length(), 10)));
}
if (!borrow[0]){
    Log.i("inside borrow", borrow[0] +"");
    message.setText("This book is already borrowed by you.");
}

此按钮可以多次单击。

我从其他论坛了解到我需要以不同的生命周期方法刷新它。谁能建议我可以使用哪种方法?因为我的borrow[0]只能在我的method()中访问,所以需要找到一种方法 - 存储在哪里,以便可以从"该生命周期方法"访问它。欣赏示例代码,因为我不太熟悉生命周期方法。提前非常感谢。

让我粘贴我的整个方法代码:

public void borrowItem(String patronId, final String itemId) {
        final int DEFAULT_TIMEOUT = 200000 * 1000000000;
        String str;
//        final boolean[] borrow = new boolean[1];
//        final String[] dueDate = new String[1];
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(DEFAULT_TIMEOUT);
        progress.setMessage("Please Wait...");
        progress.setIndeterminate(false);
        progress.setCancelable(false);
        progress.show();
//        final String[] names = new String[4];
        final CountDownLatch latch = new CountDownLatch(1);
        Thread t = new Thread() {
            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000000); //Timeout Limit
                HttpResponse response;
                try {
                    HttpPost post = new HttpPost("http://...........");
                    JSONObject json = new JSONObject();
                    try {
                        json.put("itemID", itemId);
                        json.put("userID", sharedpreferences.getString("PatronID", null));
                        json.put("sessionID", sharedpreferences.getString("PatronIdKey", null));
                        Log.i("CVPL --> sessionid", sharedpreferences.getString("PatronIdKey", null));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    StringEntity se = new StringEntity(json.toString());
                    Log.i("CVPL --> json", json.toString());
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);
//                    Toast.makeText(getActivity().getApplicationContext(), "XML File:" + response , Toast.LENGTH_LONG).show();
                            /*Checking response */
                    if (response != null) {
                        HttpEntity entity = response.getEntity();
                        String result = EntityUtils.toString(entity);
//                        Log.i("CVPL - AccFrag", result);
                        progress.dismiss();
                        final CountDownLatch latch = new CountDownLatch(1);
                        final String[] names = new String[4];
                        JSONArray mArray, mArray1, mArray2;
//                        int totalCount=0;
//                        int avail=0;
                        String value, title, publisher;
                        try {
                            JSONObject obj = new JSONObject(result);
                            //Results
                            if (obj.getJSONObject("Results") != null) {
                                JSONObject obj1 = obj.getJSONObject("Results");
                                //LookupTitleInfoResponse
                                if (obj1.getJSONObject("CheckoutResponse") != null) {
                                    JSONObject obj2 = obj1.getJSONObject("CheckoutResponse");
//                                    Log.i("obj2.getString(dueDate)", obj2.getString("dueDate"));
                                    //TitleInfo
                                    if (!obj2.getString("dueDate").equals("null")) {
                                        JSONObject obj3 = obj2.getJSONObject("dueDate");
                                        value = obj3.getString("value");
//                                    if(value != null)
                                        Log.i("due date:", value.substring(0, Math.min(value.length(), 10)));
//                                                Toast.makeText(getActivity().getApplicationContext(), "Due Date:" + value , Toast.LENGTH_LONG).show();
//                                                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//                                                    builder.setMessage("You have successfully borrowed the book. Due date is" + value).create().show();
                                        borrow[0] = true;
                                        dueDate[0] = value;
                                        Log.i("borrow", borrow[0] + "");
                                    } else {
//                                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
//                                        builder.setMessage("This book is already borrowed by you.").create().show();
                                        borrow[0] = false;
                                        Log.i("borrow", borrow[0] + "");
                                    }
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
//                        replaceFragment(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();

        Log.i("borrow after thread", borrow[0] + "");
        if (borrow[0]) {
            Log.i("inside borrow", borrow[0] +"");
            message.setText("You have successfully borrowed the book. Due date is" + dueDate[0].substring(0, Math.min(dueDate[0].length(), 10)));
        }
        if (!borrow[0]){
            Log.i("inside borrow", borrow[0] +"");
            message.setText("This book is already borrowed by you.");
        }
    }

我的按钮事件:

  borrowBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.checkout_button) {
                    if (first_time_check()== true) {
//                        getAccInfo(sharedpreferences.getString("PatronIdKey", null), getArguments().getString("barcode"));
                        borrowItem(sharedpreferences.getString("PatronIdKey", null), getArguments().getString("barcode"));
                        Log.i("after borrow", borrow[0] + "");
                        if (borrow[0]) {
                            Log.i("inside borrow", borrow[0] +"");
                            message.setText("You have successfully borrowed the book. Due date is: " + dueDate[0].substring(0, Math.min(dueDate[0].length(), 10)));
                        }
                        if (!borrow[0]){
                            Log.i("inside borrow", borrow[0] +"");
                            message.setText("This book is already borrowed by you.");
                        }
                    }
                }
            }
        });

我的变量声明:

public class Checkout extends Fragment {
    final boolean[] borrow = new boolean[1];
    final String[] dueDate = new String[1];

启动线程后不确定,为什么不调用剩余代码?我主要看到 - "这本书已经被你借了。不确定是否由于线程?

在某个时间段内回想一下您的方法,没有任何神奇的生命周期事件可以异步刷新您的TextViews

 CountDownTimer t = new CountDownTimer(MAX_VALUE , 10000) {
        // This is called every 10 seconds interval.
        public void onTick(long millisUntilFinished) {
            refreshViews();
        }
        public void onFinish() {       
            start();
        }
     }.start();
public void refreshViews(){
                if (first_time_check()== true) {
                    borrowItem(sharedpreferences.getString("PatronIdKey", null), getArguments().getString("barcode"));
                    Log.i("after borrow", borrow[0] + "");
                    if (borrow[0]) {
                        Log.i("inside borrow", borrow[0] +"");
                        message.setText("You have successfully borrowed the book. Due date is: " + dueDate[0].substring(0, Math.min(dueDate[0].length(), 10)));
                    }
                    if (!borrow[0]){
                        Log.i("inside borrow", borrow[0] +"");
                        message.setText("This book is already borrowed by you.");
                    }    
}

TextView声明为 Fragment 类中的公共变量。然后在生命周期方法中获取onCreateView TextView的视图引用。现在,可以从您那里的method()功能轻松访问TextView。下面是一个可能对你有所帮助的示例代码。

public class MyFragment extends Fragment {
  private TextView message;
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.your_fragment_layout, container, false);
    message = (TextView) v.findViewById(R.id.message);
    // Here's your button.setOnClickListener
  }
  private void method() {
    if (borrow[0]) {
      Log.i("inside borrow", borrow[0] +"");
      message.setText("You have successfully borrowed the book. Due date is" + dueDate[0].substring(0, Math.min(dueDate[0].length(), 10)));
    } else {
      Log.i("inside borrow", borrow[0] +"");
      message.setText("This book is already borrowed by you.");
    }
  }
}

在此处检查您的线程是否返回 null。

obj1.getJSONObject("CheckoutResponse")

最新更新