2 Обновление проблем в ListFragment

У меня есть две проблемы с ListFragment: Я хочу освежить ListFragment, как только я нажимаю кнопку, которую я определяю в XML-файле. Я первоначально загружаю Данные DataAdapter в AsyncTask в TitlesFragment.

Я не нашел способа создать код для кнопки, которая могла бы получить доступ к AsyncTask - и обновить мой фрагмент

На другом примечании: 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;
    }   
-121--854462- Новый (std:: nothrow) в сравнении с новым в блоке try/catch Я провел некоторое исследование после изучения нового, в отличие от malloc (), к которому я привык, не возвращает NULL для неудачных распределений, и обнаружил, что существуют два различных способа проверки того, удалось ли новому или...

Я провел некоторое исследование, изучив new , в отличие от malloc () , к которому я привык, не возвращает NULL для неудачных распределений, и обнаружил, что существуют два различных способа проверки того, удалось ли новое или нет.

try
{
    ptr = new int[1024];
}
catch(std::bad_alloc& exc)
{
    assert();
};

и

ptr = new (std::nothrow) int[1024];
if(ptr == NULL) 
    assert();

Я верю, что два пути достижения одной и той же цели, (исправьте меня, если я ошибаюсь, конечно!), так что мой вопрос заключается в следующем:

, что является лучшим вариантом для проверки успеха нового , полностью основанного на удобочитаемости, ремонтопригодности и производительности, игнорируя де-факто соглашение о программировании c++.

39
задан Anne Quinn 1 September 2011 в 23:15
поделиться