使用带有httpconnection的片段的最佳方法是什么?

时间:2013-02-04 10:36:22

标签: android android-fragments httpconnection android-fragmentactivity

我正在重构一个使用AsyncTask对Web服务进行HTTP调用的应用程序。

现在使用一个简单的Activity,当我需要以这种方式使用AsyncTask调用服务时:

  private class MyAsyncTask extends AsyncTask {<String, Void, Boolean>
    private ProgressDialog progressDialog;


    private xmlHandler handler;

    @ Override
    protected void OnPreExecute () {
    progressDialog = new ProgressDialog (home.This);
    progressDialog
    . SetMessage (getString (R.string.home_loadinfo_attendere));
    progressDialog.setCancelable (false);
    progressDialog.show ();
    }

    @ Override
    protected Boolean doInBackground (String... params) {
    try {
    xmlHandler handler = new XmlHandler();
    return Service
    . GetInstance ()
    . CallService (
    ServiceType.GETINFO,
    Home.This, handler, null);
    } Catch (Exception e) {
    e.printStackTrace ();
    return false;
    }
    }

    @ Override
    protected void OnPostExecute (Boolean success) {
    progressDialog.dismiss ();

    String message = null;
    if (success | | (handler == null))
    message = getString (R.string.server_result_msg500);
    else {
    switch (handler.getStatusCode ()) {
    case 200:
    doStuffWithHandler(handler);
    return;
    case 500:
    message = getString (R.string.server_result_msg500);
    break;
    case 520:
    message = getString (R.string.server_result_msg520);
    break;
    default:
    message = getString (R.string.server_result_msg500);
    break;

    }
    }

    if (message! = null) {

    AlertDialog.Builder builder = new AlertDialog.Builder (home.This);
    builder.setTitle (R.string.home_loadinfo_error_title)
    . SetMessage (message)
    . SetCancelable (true)
    . SetNegativeButton (R.string.close_title,
    new DialogInterface.OnClickListener () {
    @ Override
    public void onClick (DialogInterface dialog,
    int id) {
    dialog.cancel ();

    }
    });
    AlertDialog alert = builder.create ();
    Alert.show ();
    }
    }
    }

 doStuffWithHandler(handler){

// populate interface with data from service

 }

我想要使用Android兼容性库和FragmentActivity这样做。我读了一些关于加载器的内容但是我不明白我怎么能以同样的方式使用它们。你能告诉我这是否正确(FragmentActivity,Fragment和Loader)以及如何实现它也解决了我的例子?

2 个答案:

答案 0 :(得分:0)

您可以像在Activity中一样使用Fragment中的Asynctask,但很少有变化,例如:

 progressDialog = new ProgressDialog (home.This);

更改为:

progressDialog = new ProgressDialog (getApplication());



 return Service
    . GetInstance ()
    . CallService (
    ServiceType.GETINFO,
    Home.This, handler, null);

更改为:

return Service
. GetInstance ()
. CallService (
ServiceType.GETINFO,
getApplication(), handler, null);

在Fragment中实现Asynctask的任何特殊功能。 我想你需要阅读更多有关Fragment本身的内容。

答案 1 :(得分:0)

您可以创建一个Loader,如下所示:

public abstract class MyLoader extends AsyncTaskLoader<String> {
public MyLoader(Context context) {
    super(context);
}

private String result;
protected String error;

@Override
public final String loadInBackground() {
    try {
        error = null;
        // Load your data from the server using HTTP
        ...
        result = ...
        ...
        return result;
    }
    catch (Exception e) {
        Logger.e("ResourceLoader", "Loading resource failed.", e);
        error = e.getMessage();
    }
    return null;
}

@Override
protected void onStartLoading() {
    if (!TextUtils.isEmpty(error)) {
        deliverResult(result);
    }

    if (takeContentChanged()) {
        forceLoad();
    }
}

@Override
public void deliverResult(String data) {
    if (isReset()) {
        return;
    }

    result = data;

    if (isStarted()) {
        try {
            super.deliverResult(data);
        }
        catch(Exception e) { 
            Log.e("ResourceLoader", "Caught exception while delivering result.", e);
        }
    }
}

public String getError() {
    return error;
}
}

在Fragment中,您可以初始化此加载器:

public class MyLoaderFragment extends Fragment implements LoaderCallbacks<String> {
....
....
String message;

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

    setRetainInstance(true);
        ....
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getLoaderManager().initLoader(0, getArguments(), this);
}

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    return new MyLoader(getActivity());
}

@Override
public void onLoadFinished(Loader<String> loader, String result) {
    // Here you have the result in 'result'.
    message = result;
    ...
}
....
}

而不是只返回一个简单的'String'结果,你可以返回任何你喜欢的对象。只需相应地调整MyLoader和LoaderCallbacks实现。