-1

I would like to run my doinbackground() on a UI thread, However i am getting a cannot resolve runOnUiThread error. I need to do this because there is too much load on my main thread

Here is my activity:

public class valance extends Fragment {


Button get,add;
ListView list;
SimpleAdapter ADAhere;
ProgressBar progressBar;
Connection connect;
String ConnectionResult = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_valance, container, false);

    list = (ListView)rootView.findViewById(R.id.raill);
    add = (Button)rootView.findViewById(R.id.btn_add);
    progressBar = (ProgressBar)rootView.findViewById(R.id.PB_Getting);
    progressBar.setVisibility(View.GONE);

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(getActivity(),Add_valance.class);
            startActivity(i);
        }
    });


    new GetValence().execute();





    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {



        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            /** To change selected state view */
            view.setSelected(true);
            HashMap<String, Object> obj = (HashMap<String, Object>) ADAhere.getItem(position);
            String SlectedName = (String) obj.get("NAME");
            String SlectedPrice = (String) obj.get("PRICE");
            String SlectedSize = (String) obj.get("SIZE");
            String SlectedRange = (String) obj.get("RANGE");
            String SlectedSupp = (String) obj.get("SUPPLIER");
           // Toast.makeText(getActivity().getApplicationContext(), SlectedName, Toast.LENGTH_SHORT).show();

            final Dialog dialog = new Dialog(getActivity());
            dialog.getWindow();
            //dialog.setTitle("Confirm your Vote");
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.diaglog);

            final TextView VName = (TextView) dialog.findViewById(R.id.Name);
            final TextView VRange = (TextView) dialog.findViewById(R.id.Range);
            final TextView VSUPPLIER = (TextView) dialog.findViewById(R.id.Supplier);
            final TextView VSIZE = (TextView) dialog.findViewById(R.id.Size);
            final TextView VPrice = (TextView) dialog.findViewById(R.id.Price);


            VName.setText(SlectedName);
            VRange.setText(SlectedRange);
            VSUPPLIER.setText(SlectedSupp);
            VSIZE.setText(SlectedSize);
            VPrice.setText(SlectedPrice);
            dialog.show();
            Button cancelBtn = (Button) dialog.findViewById(R.id.cancel_btn);
            cancelBtn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    dialog.dismiss();
                }
            });

            dialog.show();

        }
    });




    return rootView;
}

public class GetValence extends AsyncTask<String, Integer, List<Map<String, String>>> {
    Connection connect;
    String ConnectionResult = "";
    Boolean isSuccess = false;

    public List<Map<String, String>> doInBackground(String... params) {

        List<Map<String, String>> data = null;
        data = new ArrayList<>();

        try {
            ConnectionHelper conStr = new ConnectionHelper();
            connect = conStr.connectionclass();        // Connect to database
            if (connect == null) {
                ConnectionResult = "Check Your Internet Access!";
            } else {
                // Change below query according to your own database.
                String query = "select * from cc_valence";
                Statement stmt = connect.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                while (rs.next()) {
                    Map<String, String> datanum = new HashMap<String, String>();
                    datanum.put("NAME", rs.getString("VALENCE_NAME"));

                    datanum.put("PRICE", rs.getString("VALENCE_UNIT_PRICE"));

                    datanum.put("RANGE", rs.getString("VALENCE_RANGE"));

                    datanum.put("SUPPLIER", rs.getString("VALENCE_SUPPLIER"));

                    datanum.put("SIZE", rs.getString("VALENCE_SIZE"));
                    data.add(datanum);
                }


                ConnectionResult = " successful";
                isSuccess = true;
                connect.close();
            }
        } catch (Exception ex) {
            isSuccess = false;
            ConnectionResult = ex.getMessage();
        }

        return data;
    }

    public void onPostExecute(List<Map<String, String>> result) {
        String[] fromwhere = {"NAME", "PRICE", "SIZE", "RANGE", "SUPPLIER"};

        int[] viewswhere = {R.id.Name_txtView, R.id.price_txtView, R.id.size_txtView};

        ADAhere = new SimpleAdapter(getActivity(), result, R.layout.list_valence, fromwhere, viewswhere);

        list.setAdapter(ADAhere);
    }

}

I have read somewhere that AsyncTask work on a different thread but the doinbackground does not so it is causing some major lag because i am over working my main thread so i was wondering if i can implement UI threads but i have never used it before so i am a bit blank on how to do this even after watching tutorials

Mohammedis271
  • 185
  • 1
  • 14

3 Answers3

0

If you are using runOnUiThread in fragment then try with below code,

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Code 
    }
});
Sagar Zala
  • 4,854
  • 9
  • 34
  • 62
  • By my `data.add(datanum);` in my `doinbackground` i get a variable is declared in an inner class and needs to be delcared final and when i delcare my data as final i get an unknown class error – Mohammedis271 Jul 21 '18 at 18:00
0

runOnUiThread() is part of Activity (see docs) therefore if you want to use it in your Fragment, you need to obtain fragment's activity object first, with use of getActivity() method.

getActivity().runOnUiThread(runnable);
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

I don't see runOnUiThread anything in your question, but that aside, a few points:

  • The doInBackground routine in an AsyncTask does not run on the UI thread, that is the point of using it. It runs on a background thread so you can do longer operations there without blocking the UI thread.
  • The onPreExecute and onPostExecute methods in the AsyncTask do run on the UI thread, so that is where you would update views or interact with the UI
  • You stated in your question "I would like to run my doinbackground() on a UI thread" so I think you are misunderstanding the difference between the UI thread (the one processing the UI) and other background threads (non-UI threads, where you want to run your longer operations). Maybe some of the answers here will help clarify.
Tyler V
  • 9,694
  • 3
  • 26
  • 52