选项卡更改或滑动时,AsyncProcess不更新TextView

时间:2015-07-02 14:19:40

标签: android android-fragments android-activity android-asynctask

我认为我与this problem有类似的问题,但是我的标签使用了不同的布局。

我使用Google的SlidingTabLayout / Strip来制作可跳转的标签布局。每个选项卡都是一个包含TextView的Fragment,每个TextView都通过AsyncRetriever进程更新。

目前,它是这样的:

+------------------------+
+ TAB 1  | TAB 2 | TAB 3 +
+------------------------+
+                        +
+                        +

最初,每个标签加载正常。选项卡1最初填充,然后当我滑动到选项卡2和3时,它们也加载正常。有趣的问题是当我尝试将新数据注入数据库,然后在我的应用程序上观察数据刷新时。

例如,我更新了数据库中Tab 1的内容。如果我当前在标签1上并选择标签3,则返回标签1,我会看到所反映的更改。

但是,如果我选择Tab 2,那么返回选项卡1,我从未看到更改(直到我点击Tab 3)。相反的问题也是如此。此外,如果我转到Tab 1或3然后回到2,我永远不会在Tab 2中进行任何更新更新。基本上,我认为每当我刷卡时我的视图刷新都会有问题,而且不知何故Tab 2是死区。

这是我的MainActivity课程:

public class MainActivity extends ActionBarActivity {
    Toolbar toolbar;
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence titles[]={"MAIN","INVENTORY","ATTRIBUTES"};
    int num_tabs = titles.length;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Creating The Toolbar and setting it as the Toolbar for the activity
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);


        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter =  new ViewPagerAdapter(getSupportFragmentManager(),titles,num_tabs,MainActivity.this);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

和我的ViewPagerAdapter

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
    int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
    Activity mainActivity; // track the activity

    // Build a Constructor and assign the passed Values to appropriate values in the class
    public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb, Activity a) {
        super(fm);

        this.mainActivity = a;
        this.Titles = mTitles;
        this.NumbOfTabs = mNumbOfTabsumb;

    }

    //This method return the fragment for the every position in the View Pager
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                MainFragment tab1 = new MainFragment();
                return tab1;
            case 1:
                InventoryFragment tab2 = new InventoryFragment();
                return tab2;
            case 2:
                AttributesFragment tab3 = new AttributesFragment();
                return tab3;
        }
        return null;
    }

    // This method return the titles for the Tabs in the Tab Strip

    @Override
    public CharSequence getPageTitle(int position) {
        return Titles[position];
    }

    // This method return the Number of tabs for the tabs Strip

    @Override
    public int getCount() {
        return NumbOfTabs;
    }
}

以及我的一个片段的例子(此时它们基本相同):

public class MainFragment extends Fragment implements RetrieveData.Callback {
    TextView mResult;
    RetrieveData mAsyncRetriever;


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.main_tab,container,false);
        mResult = (TextView)v.findViewById(R.id.txtRoomDescription);
        return v;
    }

    @Override
    public void onResume() {
        //  Keep a reference to the AsyncTask so we can properly
        //  cancel it when our lifecycle events dictate so.
        super.onResume();
        mAsyncRetriever = new RetrieveData(this);
        //mAsyncRetriever.execute("get_room.php","1");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            mAsyncRetriever.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "get_room.php","1");
        else
            mAsyncRetriever.execute("get_room.php", "1");

    }

    @Override
    public void onPause() {
        super.onPause();
        //  If we have a pending data load going on, kill it.
        if (mAsyncRetriever != null) {
            mAsyncRetriever.cancel(true);
            mAsyncRetriever = null;
        }
    }

    @Override
    public void onDataLoaded(String[] result) {
        //  Only pulling the first result provided
        mResult.setText(result[0]);

        //  The RetrieveData is done, get rid of our ref
        mAsyncRetriever = null;
    }
}

最后,我的RetrieveData班级:

public class RetrieveData extends AsyncTask<String, String, String[]> {
    // provide results via interface
    public interface Callback {
        public void onDataLoaded(String[] result);
    }

    private Callback mCb;

    public RetrieveData(Callback cb) {
        mCb = cb;
    }

    protected String[] doInBackground(String... urls) {
        String result = "";
        String[] op = new String[2];// "";
        op[0] = "";
        op[1] = "";

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("id","1"));

        try {
            String postString = "/scripts/" + urls[0];
            if (urls[0] == "get_room.php")
                postString += "?room_id=" + urls[1];

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(postString);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            //is.close();
            result += sb.toString();

            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); ++i) {
                JSONObject json_data = jArray.getJSONObject(i);
                //Log.i("info", "id: " + json_data.getInt("id") +
                //                "name: " + json_data.getString("name") +
                //                "desc: " + json_data.getString("desc")
                //);

                if (urls[0] == "get_room.php") {
                    op[0] += "id [" + json_data.getInt("id") + "]\n" +
                            "name [" + json_data.getString("name") + "]\n" +
                            "desc [" + json_data.getString("desc") + "]\n";


                } else if (urls[0] == "get_inventory.php") {
                    op[0] += "id [" + json_data.getInt("id") + "]\n" +
                            "item name [" + json_data.getString("name") + "]\n" +
                            "item description [" + json_data.getString("description") + "]\n\n";

                } else {
                    op[0] += "id [" + json_data.getInt("id") + "]\n" +
                            "username [" + json_data.getString("username") + "]\n" +
                            "status [" + json_data.getString("status") + "]\n";
                }
                //System.out.println(op);
            }

        } catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }

        return op;
    }


    @Override
    protected void onPostExecute(String[] result) {
        // update textbox
        mCb.onDataLoaded(result);
        return;
    }

0 个答案:

没有答案