androidlistviewandroid-studioandroid-runonuithread

ListView refreshing by runOnUiThread(run) not working


So im quite new to Android Studio and app development in general and i had this issue for a while, with no luck of fixing it. I've figured that someone here might provide some ideas for fixing this.. Issue: The refreshing of ListView on UI thread (as suggested here) does not work for me. Here's the declaration of 'Runnable run' (in MainActivity.java):

        public Runnable run;
        // ...
        run = new Runnable() {
        public void run() {
            ArrayList<String> temp1 = (ArrayList<String>) arrayList_1.clone();

            View v = getLayoutInflater().inflate(R.layout.fragment_main, null);

            lv_1 = (ListView) v.findViewById(R.id.listViewMe);

            lv_1.setAdapter(adapter_1);

            arrayList_1.clear();

            arrayList_1.addAll(temp1);

            adapter_1.notifyDataSetChanged();

            lv_1.invalidateViews();
            lv_1.refreshDrawableState();

            Log.e("gig", "DONE REFRESHING");
        }
    };

I call the method here:

@Override
public boolean onNavigationItemSelected(MenuItem item)
{
    int id = item.getItemId();

    Fragment fragment = null;

    if (id == R.id.nav_main) {
        fragment = new FragmentMain();
    } if (id == R.id.nav_history) {
        fragment = new FragmentHistory();
    }

    if (fragment != null)
    {
        FragmentTransaction localFragmentTransaction = getSupportFragmentManager().beginTransaction();
        localFragmentTransaction.replace(R.id.screen_area, fragment);
        localFragmentTransaction.commit();

        runOnUiThread(run); // here
    }

    ((DrawerLayout) findViewById(R.id.drawer_layout)).closeDrawer(GravityCompat.START);
    return true;
}

Now for the part that's confusing me: it works when i add a new item to the ListView via this method:

public void addDebtToOther(String name, String money)
{
    String full = name + ", " + money + " EUR";

    lv_1 = (ListView) findViewById(R.id.listViewMe);

    if (lv_1!=null) {
        lv_1.setAdapter(adapter_1);

        arrayList_1.add(full);
        adapter_1.notifyDataSetChanged();
    } else {
        Log.e("gig", "ListView error, lv is NULL");
    }
}

That's about it, any help would be really apriciated!


Solution

  • Ok so after about a week of head-banging, with the help of @Eric i've figured it out. Turns out i needed to call the run() method in my fragment's .onStart(), like this:

        @Override
        public void onStart() {
        super.onStart();
    
        ((MainActivity)getContext()).run.run();
        }
    

    Thanks again Eric!