2 ListFragment 内的刷新问题

发布于 2024-12-02 11:03:44 字数 6003 浏览 0 评论 0原文

我的 ListFragment 有两个问题: 我想在单击 XML 文件中定义的按钮后刷新 ListFragment。我最初在 TitlesFragment 的 AsyncTask 中加载 DataAdapter 的数据。

我还没有找到一种方法来为可以访问 AsyncTask 的按钮创建代码 - 并刷新我的 TitlesFragment

在不同的注释上:每次我更改手机的方向时,Listfragment 都会自行更新,这绝对不是所需的行为。

public class ClosestPlaces extends FragmentActivity {

private static KantinenListe kantinen;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_ACTION_BAR);        
    setContentView(R.layout.kantinen_results);

}   

/**
 * This is the "top-level" fragment, showing a list of items that the
 * user can pick.  Upon picking an item, it takes care of displaying the
 * data to the user as appropriate based on the currrent UI layout.
 */

public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;


    private class BuildKantinen extends AsyncTask<String, Integer, KantinenListe>   {

        private KantinenListe kantinen;


        @Override
        protected KantinenListe doInBackground(String... params) {
            try{

                Gson gson = new Gson();             
                // SOAP Test
                String NAMESPACE = "http://tempuri.org/";
                String METHOD_NAME = "fullSyncGPS";
                String SOAP_ACTION = "http://tempuri.org/IDatenService/fullSyncGPS";
                String URL = "http://webserviceURL?wsdl";

                SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);

                PropertyInfo pi = new PropertyInfo();
                request.addProperty("radius",10);
                request.addProperty("lat", "14.089201");
                request.addProperty("lng", "02.136459");
                request.addProperty("von", "01.09.2011");
                request.addProperty("bis", "01.09.2011");

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);        

                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);
                SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

                String resultData = result.toString(); 


                resultData = "{\"meineKantinen\":"+resultData+"}";
                this.kantinen = gson.fromJson(resultData, KantinenListe.class);
                Log.i("test", "blubber" );
            }
            catch(Exception e)
            {
                 e.printStackTrace();
            }
                return this.kantinen;

        }

        @Override
        protected void onPostExecute(KantinenListe result) {
            // populate the List with the data
            Log.i("test", "postexecute" );
            setListAdapter( new MenuAdapter(getActivity(), R.layout.simple_list_item_checkable_1, kantinen.getMeineKantinen()));
        }
    }


    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        new BuildKantinen().execute("test");                       

        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);            
    }

    /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
    void showDetails(int index) {
        mCurCheckPosition = index;

            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Log.i("Test",Integer.toString(index));
            Intent intent = new Intent();
            intent.setClass(getActivity(), BeAPartner.class);
            startActivity(intent);
    }
}

public static class MenuAdapter extends ArrayAdapter {

    private LayoutInflater mInflater;
    private List<Kantine> items;
    private Context context;

    public MenuAdapter(Context context, int textViewResourceId, List<Kantine> items) {
        super(context, textViewResourceId);
        mInflater = LayoutInflater.from(context);
        this.items = items;
        this.context = context;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.menu_row, parent, false);
            holder = new ViewHolder();
            holder.color = (TextView) convertView.findViewById(R.id.color);
            holder.title = (TextView) convertView.findViewById(R.id.detail);
            holder.subdetail = (TextView) convertView.findViewById(R.id.subdetail);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        // Fill in the actual story info
        Kantine s = items.get(position);

        s.setName( Html.fromHtml(s.getName()).toString() );
        if (s.getName().length() > 35)
            holder.title.setText(s.getName().substring(0, 32) + "...");
        else
            holder.title.setText(s.getName());

        Log.i("display", "Here I am");
        return convertView;
    }


 }
    static class ViewHolder {
        TextView color;
        TextView title;
        TextView subdetail;
    }   

I have two issues with my ListFragment:
I want to refresh the the ListFragment once I click a button which I define in the XML File.I initially load the Data of the DataAdapter within a AsyncTask in the TitlesFragment.

I have not found a way to create the code for the button which could access the AsyncTask - and refresh my TitlesFragment

On a different note: The Listfragment updates itself everytime I change the orientation of the phone, which is absolute not the desired behaviour.

public class ClosestPlaces extends FragmentActivity {

private static KantinenListe kantinen;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_ACTION_BAR);        
    setContentView(R.layout.kantinen_results);

}   

/**
 * This is the "top-level" fragment, showing a list of items that the
 * user can pick.  Upon picking an item, it takes care of displaying the
 * data to the user as appropriate based on the currrent UI layout.
 */

public static class TitlesFragment extends ListFragment {
    boolean mDualPane;
    int mCurCheckPosition = 0;


    private class BuildKantinen extends AsyncTask<String, Integer, KantinenListe>   {

        private KantinenListe kantinen;


        @Override
        protected KantinenListe doInBackground(String... params) {
            try{

                Gson gson = new Gson();             
                // SOAP Test
                String NAMESPACE = "http://tempuri.org/";
                String METHOD_NAME = "fullSyncGPS";
                String SOAP_ACTION = "http://tempuri.org/IDatenService/fullSyncGPS";
                String URL = "http://webserviceURL?wsdl";

                SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);

                PropertyInfo pi = new PropertyInfo();
                request.addProperty("radius",10);
                request.addProperty("lat", "14.089201");
                request.addProperty("lng", "02.136459");
                request.addProperty("von", "01.09.2011");
                request.addProperty("bis", "01.09.2011");

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                envelope.setOutputSoapObject(request);        

                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.call(SOAP_ACTION, envelope);
                SoapPrimitive result = (SoapPrimitive)envelope.getResponse();

                String resultData = result.toString(); 


                resultData = "{\"meineKantinen\":"+resultData+"}";
                this.kantinen = gson.fromJson(resultData, KantinenListe.class);
                Log.i("test", "blubber" );
            }
            catch(Exception e)
            {
                 e.printStackTrace();
            }
                return this.kantinen;

        }

        @Override
        protected void onPostExecute(KantinenListe result) {
            // populate the List with the data
            Log.i("test", "postexecute" );
            setListAdapter( new MenuAdapter(getActivity(), R.layout.simple_list_item_checkable_1, kantinen.getMeineKantinen()));
        }
    }


    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        new BuildKantinen().execute("test");                       

        if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails(position);            
    }

    /**
     * Helper function to show the details of a selected item, either by
     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */
    void showDetails(int index) {
        mCurCheckPosition = index;

            // Otherwise we need to launch a new activity to display
            // the dialog fragment with selected text.
            Log.i("Test",Integer.toString(index));
            Intent intent = new Intent();
            intent.setClass(getActivity(), BeAPartner.class);
            startActivity(intent);
    }
}

public static class MenuAdapter extends ArrayAdapter {

    private LayoutInflater mInflater;
    private List<Kantine> items;
    private Context context;

    public MenuAdapter(Context context, int textViewResourceId, List<Kantine> items) {
        super(context, textViewResourceId);
        mInflater = LayoutInflater.from(context);
        this.items = items;
        this.context = context;
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.menu_row, parent, false);
            holder = new ViewHolder();
            holder.color = (TextView) convertView.findViewById(R.id.color);
            holder.title = (TextView) convertView.findViewById(R.id.detail);
            holder.subdetail = (TextView) convertView.findViewById(R.id.subdetail);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        // Fill in the actual story info
        Kantine s = items.get(position);

        s.setName( Html.fromHtml(s.getName()).toString() );
        if (s.getName().length() > 35)
            holder.title.setText(s.getName().substring(0, 32) + "...");
        else
            holder.title.setText(s.getName());

        Log.i("display", "Here I am");
        return convertView;
    }


 }
    static class ViewHolder {
        TextView color;
        TextView title;
        TextView subdetail;
    }   

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

征﹌骨岁月お 2024-12-09 11:03:44

要阻止 Activity 重新启动,您只需在运行片段的 Activity 上设置 android:configChanges 属性即可。

    android:configChanges="orientation"

设置告诉系统不要仅仅为了改变方向而在方向改变时重新启动活动。

对于按钮,使用属性 android:onClick="myFunction" 在 XML 中设置点击侦听器。然后在你的片段中定义这个函数:

    public void myFunction(View v)
    {
             new myAsync.execute('test');       
    }

Well to stop the activity from being restarted you can just set android:configChanges attribute on the activity that is running the fragment.

    android:configChanges="orientation"

Setting that tells the system to not restart the activity on an orientation change just to change the orientation.

As for the button, set your click listener in XML by using the attribute android:onClick="myFunction". Then in your fragment define this function:

    public void myFunction(View v)
    {
             new myAsync.execute('test');       
    }
旧人哭 2024-12-09 11:03:44

当您更改手机方向时,它会重新启动活动。任何需要持久保存的内容都需要保存在 onSaveInstanceState(Bundle savingInstanceState) 中,并使用 onRestoreInstanceState(Bundle savingInstanceState) 进行恢复。

至于单击按钮时更新数据,请尝试在适配器上调用notifyDataSetChanged()。如果这不起作用,您可能只需要再次运行异步任务。

When you change the phone orientation, it restarts the activity. Anything you need to be persistent you'll need to save in onSaveInstanceState(Bundle savedInstanceState) and restore with onRestoreInstanceState(Bundle savedInstanceState).

As far as updating the data when clicking a button, try calling notifyDataSetChanged() on the adapter. If that doesn't work, you'll likely just have to run your asynctask again.

眼波传意 2024-12-09 11:03:44

好吧,我认为最好的做法是在新答案中发布可能的解决方案 - 出于可读性的明显原因:

public void reload(View v)
{
    if (getSupportFragmentManager().findFragmentById(R.id.titles) != null) { 
            Fragment titles = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.titles);
            //recreate the fragment
            titles.onActivityCreated(null);
    }
}

完全按照我想要的方式(重新加载数据)!但是......我认为这个解决方案的内存占用可能很糟糕。

Ok, I thought it's best practice to post a possible solution in a new answer - for the obvious reasons of readability:

public void reload(View v)
{
    if (getSupportFragmentManager().findFragmentById(R.id.titles) != null) { 
            Fragment titles = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.titles);
            //recreate the fragment
            titles.onActivityCreated(null);
    }
}

Does exactly what I want ( reload the data )! However ... I think the memory footprint of this solution might be bad.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文