2015-04-16 36 views
1

問題是,除了數據未在自定義ListView的textView中加載,我沒有收到任何錯誤,我得到的只是一個空白輸出。在開始使用Loaders之前,我沒有任何問題。Android Loader:無法將數據加載到ListView

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; 
} 
} 
+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); 
+0

我想這個解決方案可能會有所幫助。但是在Fragment actiivty中添加此代碼時,在添加片段時,主活動中出現錯誤。方法FragmentTransaction.add(Fragment,String)不適用 (參數不匹配; int不能轉換爲Fragment) 方法FragmentTransaction。(錯誤:(54,21)錯誤:找不到適合的方法add(int,MSKFragment) 方法FragmentTransaction。 add(int,Fragment)不適用 (參數不匹配; MSKFragment不能轉換爲片段)] – George

+0

這是一個不同的問題,您可能試圖在代碼中同時使用支持Fragment和普通片段。檢查您正在使用的所有代碼是否正在運行。例如,如果您使用支持片段,請確保您也使用getSupportFragmentManager()。事實上,它可能是你需要使用getSupportLoadManager(),而不是我在我的答案中發佈的代碼片段。 – Knossos

+0

感謝您的寶貴意見,我現在正在努力 – George

相關問題