Android ListView不会填充

时间:2015-04-21 09:37:47

标签: android listview loader

这是我做的简单的Android项目。跑步时我没有收到任何警告或错误。但是ListView没有填充。我不明白出了什么问题。

因为我没有'了解确切问题的位置并复制粘贴所有代码都没有帮助,这是我的项目代码库:https://bitbucket.org/geejo/msk-v2

任何形式的帮助将不胜感激

MSKFragment.java

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

public static final int SERVICE_LOADER = 0;

private static final String[] SERVICE_COLUMNS =
        {
                ServiceContract.ServiceEntry.TABLE_NAME,
                ServiceContract.ServiceEntry._ID,
                ServiceContract.ServiceEntry.COLUMN_NAME,
                ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME,
                ServiceContract.ServiceEntry.COLUMN_PRICE
        };


public static final int COL_ID = 0;
public static final int COL_NAME = 1;
public static final int COL_ORG_NAME = 2;
public static final int COL_PRICE = 3;

public MSKFragment()
{

}

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    getLoaderManager().initLoader(SERVICE_LOADER, null, this);
}

@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();
}

//Calling FetchServiceTask and executing it.
private void updateServices()
{
    FetchServicesTask serviceTask = new FetchServicesTask(getActivity());
    serviceTask.execute();
}

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

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

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

}

FetchServices.java (AsyncTasks)

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;
            int price;

            JSONObject serviceObject = serviceArray.getJSONObject(i);

            name =  serviceObject.getString(MSK_NAME);
            price = serviceObject.getInt(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;
}
}

ServiceAdapter.java

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

private String convertCursorRowToUXFormat(Cursor cursor)
{

    return cursor.getString(MSKFragment.COL_NAME) + "-" + cursor.getString(MSKFragment.COL_ORG_NAME) +
            " - " + cursor.getInt(MSKFragment.COL_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));
}
}

1 个答案:

答案 0 :(得分:0)

ServiceAdapter.java 中的方法 newView()更改为:

public View newView(Context context, Cursor cursor, ViewGroup parent){
View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
return view;}