Android Loader:无法将数据加载到ListView

时间:2015-04-16 06:18:03

标签: android listview android-asynctask loader

问题是,我没有得到任何错误,除了数据没有加载到自定义ListView的textViews中,我得到的只是一个空白输出。在开始使用Loaders之前我没有遇到任何问题。

MSKFragment.java (片段类)

public class MSKFragment extends android.support.v4.app.Fragment implements LoaderManager.LoaderCallbacks<Cursor>
{
private ServiceAdapter mServiceAdapter;

public static final int SERVICE_LOADER = 0;

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle args)
{
    Uri serviceUri = ServiceContract.ServiceEntry.buildServiceUri(i);
    return new CursorLoader(getActivity(), serviceUri, null, null, null, null); 
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
    mServiceAdapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader)
{
    mServiceAdapter.swapCursor(null);
}

public MSKFragment()
{

}

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

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
    inflater.inflate(R.menu.menu_fragment_msk, menu);
}

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

    if (id == R.id.action_refresh)
    {
        //Moving functions to a helper class, so that when Activity starts the data can be displayed
        updateServices();
        return true;
    }

    return super.onOptionsItemSelected(item);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    mServiceAdapter = new ServiceAdapter(getActivity(), null, 0);

    View rootView = inflater.inflate(R.layout.fragment_msk, container, false);

    ListView listView = (ListView) rootView.findViewById(R.id.listViewMainService);

    listView.setAdapter(mServiceAdapter);

    return rootView;
}

@Override
public void onStart()
{
    super.onStart();
    //Refresh called and service updated when activity starts
    updateServices();
}

private void updateServices()
{
    FetchServicesTask serviceTask = new FetchServicesTask(getActivity());
    serviceTask.execute();
}

}

ServiceAdapter.java (自定义适配器类)

public class ServiceAdapter extends CursorAdapter
{
public ServiceAdapter(Context context, Cursor c, int flags)
{
    super(context, c, flags);
}

private String convertCursorRowToUXFormat(Cursor cursor) {
    // get row indices for our cursor
    int idx_name = cursor.getColumnIndex(ServiceContract.ServiceEntry.COLUMN_NAME);
    int idx_organizationName = cursor.getColumnIndex(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME);
    int idx_price = cursor.getColumnIndex(ServiceContract.ServiceEntry.COLUMN_PRICE);

    return cursor.getString(idx_name) + "-" + cursor.getString(idx_organizationName) +
            " - " + cursor.getString(idx_price);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
    View view = LayoutInflater.from(context).inflate(R.layout.list_item_main, parent, false);
    return view;
}

@Override
public void bindView(View view, Context context, Cursor cursor)
{
    TextView tv = (TextView)view;
    tv.setText(convertCursorRowToUXFormat(cursor));
}
}

FetchServicesTask.java (执行异步任务)

public class FetchServicesTask extends AsyncTask<String, Void, Void>

{

private final String LOG_TAG = FetchServicesTask.class.getSimpleName();

private final Context mContext;

private boolean DEBUG = true;

public FetchServicesTask(Context context )
{
    mContext = context;
}

private String[] getServicesDatafromJson(String serviceJsonStr) throws JSONException
{
    final String MSK_NAME = "name";
    final String MSK_PRICE = "price";
    final String MSK_ORG_NAME = "organizationName";
    final String MSK_POSTED_USER = "postedUser";
    final String MSK_PROFILE = "profile";

    int totalResults = 25;
    String resultStrs[] = new String[totalResults];

    try
    {
        JSONArray serviceArray = new JSONArray(serviceJsonStr);

        Vector<ContentValues> cVVector = new Vector<ContentValues>(serviceArray.length());

        for(int i=0;i<serviceArray.length();i++)
        {
            String name, organizationName, price;

            JSONObject serviceObject = serviceArray.getJSONObject(i);

            name =  serviceObject.getString(MSK_NAME);
            price = serviceObject.getString(MSK_PRICE);

            JSONObject postedUserObject = serviceObject.getJSONObject(MSK_POSTED_USER);
            JSONObject profileObject = postedUserObject.getJSONObject(MSK_PROFILE);

            organizationName = profileObject.getString(MSK_ORG_NAME);

            ContentValues serviceValues = new ContentValues();

            serviceValues.put(ServiceContract.ServiceEntry.COLUMN_NAME, name);
            serviceValues.put(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME, organizationName);
            serviceValues.put(ServiceContract.ServiceEntry.COLUMN_PRICE, price);

            cVVector.add(serviceValues);
        }

        int inserted = 0;

        if(cVVector.size()>0)
        {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            inserted = mContext.getContentResolver().bulkInsert(ServiceContract.ServiceEntry.CONTENT_URI, cvArray);
        }

        Log.d(LOG_TAG, "FetchServicesTask Complete. " + inserted + " Inserted");
    }

    catch(JSONException e)
    {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

/////////////////////////////// NETWORKING BOILER PLATE ///////////////////////////
@Override
protected Void doInBackground(String... params)
{
    if (params.length == 0)
    {
        return null;
    }

    HttpURLConnection urlConnection = null; //Streaming data using HTTP
    String serviceJsonStr = null; //raw JSON response
    BufferedReader reader = null; //read text from character i/p stream

    int pageNo = 1;
    int numResults = 5;

    try
    {
        //-------------------------CONNECTION--------------------//

        final String SERVICE_BASE_URL = "http://myservicekart.com/public/";
        final String SEARCH_BASE_URL = "http://myservicekart.com/public/search?";
        final String SEARCH_PARAM = "search";
        final String PAGE_PARAM = "pageno";


            /*Using a helper class UriBuilder for building and manipulating URI references*/

        Uri builtServiceUri = Uri.parse(SERVICE_BASE_URL);
        Uri builtSearchUri = Uri.parse(SEARCH_BASE_URL).buildUpon().
                appendQueryParameter(SEARCH_PARAM, "").
                appendQueryParameter(PAGE_PARAM, Integer.toString(pageNo)).
                build();

        URL searchUrl = new URL(builtSearchUri.toString());

        Log.v(LOG_TAG, "Built SearchUri" +builtSearchUri.toString());

        urlConnection = (HttpURLConnection) searchUrl.openConnection();

        urlConnection.setRequestMethod("GET");

        urlConnection.connect();

        //------------------------BUFFERING---------------------//

        InputStream inputStream = urlConnection.getInputStream();

        StringBuffer buffer = new StringBuffer();

        if(inputStream==null)
        {
            return null;
        }

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line = null;

        while((line = reader.readLine()) != null)
        {
            buffer.append(line + "\n");
        }

        if(buffer.length()==0)
        {
            return null;
        }
        serviceJsonStr = buffer.toString();
        getServicesDatafromJson(serviceJsonStr);
        Log.v(LOG_TAG, "Services JSON String: " +serviceJsonStr);
    }

    catch(IOException e)
    {
        Log.e(LOG_TAG, "Error cannot connect to URL", e);
        return null;
    }

    catch (JSONException e)
    {
        e.printStackTrace();
    }

    finally
    {
        if(urlConnection!=null)
        {
            urlConnection.disconnect();
        }

        if(reader!=null)
        {
            try
            {
                reader.close();
            }
            catch (final IOException e)
            {
                Log.e(LOG_TAG,"Error closing stream",e);
            }
        }
    }

    return null;
}
}

1 个答案:

答案 0 :(得分:3)

在onCreate中,您需要初始化您的加载器:

getLoaderManager().initLoader(SERVICE_LOADER , null, this);

// Or if you are using the support library, use this:
// getSupportLoaderManager().initLoader(SERVICE_LOADER , null, this);