简体   繁体   English

如何使用片段保留活动之间的动态Arraylist元素(Android)

[英]How to preserve dynamic Arraylist elements between activities using fragment (Android)

When one activity in the fragment is launched, it successfully requests POST method ( with AsyncTask ) and Arraylist is populated. 启动片段中的一个活动时,它将成功请求POST方法(带有AsyncTask ),并填充Arraylist

After I move to other activity in the fragment and comeback, what previously was populated seems gone, but when I click back button, then suddenly it populates again ( I'm not sure whether it is being populated or just hidden data shows up ). 当我移到片段中的其他活动并恢复时,以前填充的内容似乎消失了,但是当我单击“后退”按钮时,突然又填充了它(我不确定是要填充它还是只是显示隐藏的数据)。 But again if I do the same work ( switching to other activity and come back ), then what previously was populated is gone and never come back. 但是同样,如果我做同样的工作(切换到其他活动然后再回来),那么以前填充的内容就消失了,再也不会回来。

I assume if it were to start from the first line of the code when I came back, then it should've populated but I think it didn't. 我假设如果它是从我回来时从代码的第一行开始的,那么它应该已经填充了,但我认为没有。 But I really want to make an easier interface for the users by setting the populated data always visible. 但是我真的想通过将填充的数据设置为始终可见来为用户提供一个更简单的界面。

Below is my code for "that" activity and also I include the code for the fragment controller. 以下是我的“ that”活动代码,还包括片段控制器的代码。

public class VideoCallFragment extends Fragment implements LifeCycleListener{
    private LinearLayout parentFragment;
    private ViewGroup.LayoutParams selfLayoutParams;
    private ArrayList<String> prgmNameList = new ArrayList<String>();
    private ArrayList<String> caseList = new ArrayList<String>();
    private ArrayList<String> dateList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_video_call, container, false);
        parentFragment = (LinearLayout) rootView.findViewById(R.id.ll_video_call);

        SharedPreferences settings = PreferenceManager
                .getDefaultSharedPreferences(getContext());
        String auth_token_string = settings.getString("token", ""/*default value*/);

        new soonClass().execute(auth_token_string);

        final ListView lv=(ListView) rootView.findViewById(R.id.listView_classroom);
        lv.setAdapter(new CustomAdapter(getActivity(), prgmNameList, dateList, caseList));

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String classroom = ((TextView) view.findViewById(R.id.lesson)).getText().toString();
                    lv.setVisibility(View.GONE);
                    Toast.makeText(getActivity(),classroom,Toast.LENGTH_SHORT).show();
                    classroom_enter(classroom);
                }
            }
        );
        return rootView;
    }

    class soonClass extends AsyncTask<String, String, String> {

        private Exception exception;
        protected void onPreExecute() {
        }

        protected String doInBackground(String... args) {
            String auth_token_string = args[0];

            try {
                URL url = new URL("myurl");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                String urlParameters = "token=" + auth_token_string ;

                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());

                dStream.writeBytes(urlParameters);
                dStream.flush();
                dStream.close();

                InputStream in = connection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(in,"iso-8859-1"),8);
                StringBuffer buffer = new StringBuffer();

                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append("\n");
                }
                reader.close();
                connection.disconnect();
                JSONObject jsonObj = null;

                jsonObj = new JSONObject(buffer.toString().trim());

                JSONArray classes = null;
                classes = jsonObj.getJSONArray("lessons");

                // looping through All Contacts
                for (int i = 0; i < classes.length(); i++) {
                    JSONObject c = classes.getJSONObject(i);

                    prgmNameList.add("lesson_" + c.getString("id"));
                    caseList.add(c.getString("course"));
                    dateList.add(c.getString("date"));
                }

                return "done";
            }
            catch(Exception e) {
                Log.e("ERROR", e.getMessage(), e);
                return null;
            }
        }

        protected void onPostExecute(String response) {
            Toast.makeText(getActivity(), "된다", Toast.LENGTH_SHORT).show();

            if(response == null) {
                response = "THERE WAS AN ERROR";
            }
            //progressBar.setVisibility(View.GONE);
            Log.i("INFO", response);
            //responseView.setText(response);
        }
    }

    public void classroom_enter(String room_name) {

        somefunction();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Allow volume to be controlled using volume keys
        getActivity().setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity2) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}

fragment activity code 片段活动代码

public class MainActivity2 extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {
    private static final int CASE_SECTION_EDIT_PROFILE = 1;
    private static final int CASE_SECTION_VIDEO_CALL = 2;
    private static final int CASE_SECTION_PAST_CLASS = 3;
    private static final int CASE_SECTION_SCHEDULE_CLASS = 4;
    private static final int CASE_FRAGMENT_EDIT_PROFILE = 0;
    private static final int CASE_FRAGMENT_VIDEO_CALL = 1;
    private static final int CASE_FRAGMENT_PAST_CLASS = 2;
    private static final int CASE_FRAGMENT_SCHEDULE_CLASS = 3;
    private static final String TAG = MainActivity2.class.getName();

    private NavigationDrawerFragment mNavigationDrawerFragment;
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();

        Fragment fragmentToLaunch = getFragmentToLaunch(position);

        fragmentManager.beginTransaction()
                .replace(R.id.container, fragmentToLaunch)
                .commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case CASE_SECTION_EDIT_PROFILE:
                mTitle = getString(R.string.title_section1);
                break;
            case CASE_SECTION_VIDEO_CALL:
                mTitle = getString(R.string.title_section2);
                break;
            case CASE_SECTION_PAST_CLASS:
                mTitle = getString(R.string.title_section3);
                break;
            case CASE_SECTION_SCHEDULE_CLASS:
                mTitle = getString(R.string.title_section4);
                break;
            default:
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    public Fragment getFragmentToLaunch(int position) {
        Fragment fragmentToLaunch = null;
        switch (position) {
            case CASE_FRAGMENT_EDIT_PROFILE:
                fragmentToLaunch = new EditProfileFragment();  // <!-- this is a class.
                break;
            case CASE_FRAGMENT_VIDEO_CALL:
                fragmentToLaunch = new VideoCallFragment();
                break;
            case CASE_FRAGMENT_PAST_CLASS:
                fragmentToLaunch = new ChatFragment();
                break;
            case CASE_FRAGMENT_SCHEDULE_CLASS:
                fragmentToLaunch = new FileTransferFragment();
                break;
            default:
                break;
        }

        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, position + 1);
        fragmentToLaunch.setArguments(args);

        return fragmentToLaunch;
    }
}

please give me any opinion about how to solve this issue!!! 请给我有关如何解决此问题的任何意见!!! (: (:

Call Asynctask in your fragment (VideoCallFragment) onResume() method 在片段(VideoCallFragment) onResume()方法中调用Asynctask

@Override
public void onResume() {
    super.onResume();
    new soonClass().execute(auth_token_string);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM