Dep
Dep

Reputation: 183

How to refresh textview based on user input? Multi-threading Issue

I am checking a value: borrow[0], based on which i need to refresh by TextView called message. all this is happening inside a method() which is called from button.setOnClickListener event in onCreateView() of my fragment.

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

This button can be clicked many times.

I understand from other forums that I need to refresh it in different lifecycle method. Can anyone advise which method I can use? coz my borrow[0] is only accessible in my method(), so need to find out a way - where to store so that can access it from "that lifecycle method". appreciate a sample code as I am not much familiar with lifecycle methods. Many thanks in advance.

Let me paste my entire method code:

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

MY button event:

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

My variable declaration:

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

Not sure after start thread, why remaining code is not called? I mostly see - "This book is already borrowed by you." message as the result even when borrow[0] = true. Not sure if its due to thread?

Upvotes: 0

Views: 85

Answers (2)

Reaz Murshed
Reaz Murshed

Reputation: 24211

Declare the TextView as a public variable in your Fragment class. Then get the view reference of the TextView inside onCreateView lifecycle method. Now the TextView can be easily accessed from the method() function you've got there. Here's an example code that might help you.

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

Check if your thread is returning null here.

obj1.getJSONObject("CheckoutResponse")

Upvotes: 0

Shree Krishna
Shree Krishna

Reputation: 8562

Recall your method in certain period of time, There is no any magical Lifecycle event to asynchronously refresh your 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.");
                    }    
}

Upvotes: 1

Related Questions