2014-09-21 2 views
1

저는 Android Studio를 처음 사용하고 있으며 간단한 Android보기를 사용하고 있습니다. 버튼 클릭은 foursquare API를 호출하고 내 위치 주변의 스타 벅스에 대한 백 카운트를 가져 와서 동일한 뷰에서 목록 상자의 어댑터로 설정하려고합니다. 내가 OnPostExecute()에 중단 점을 넣으면 나는 심지어에서안드로이드리스트 뷰가 데이터로 채워지지 않습니다

mFoursquareAdapter.notifyDataSetChanged(); 

전화, 나는 목록보기에 설정된 mFoursquare 어댑터가 mFoursquareAdapter 두 JSON 문자열 결과를 가지고 볼 수 있지만보기는하지 않습니다 결과로 새로 고침. 아래 코드를 게시했습니다. 아무도 내가 잘못하고있는 것을 지적하거나 이미 결과를 얻었으므로 변경해야 할 필요가 있으며이를 수행해야 할 필요가 있습니다 ... 귀하의 도움과 피드백은 대단히 감사하겠습니다! 감사

public class FoursquareInfoFragment extends android.app.Fragment { 
private ArrayAdapter<String> mFoursquareAdapter; 

public FoursquareInfoFragment() { 
} 

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

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    // Dummy data for the ListView. Here's the sample weekly forecast 
    String[] data = { 
      "Sample Foursquare Data", 
    }; 

    List<String> foursquareList = new ArrayList<String>(Arrays.asList(data)); 

    mFoursquareAdapter = new ArrayAdapter<String>(
      getActivity(), // the current context ie the activity 
      R.layout.fragment_my, // the name of the layout Id 
      R.id.textViewFoursquare, // the Id of the TextView to populate 
      foursquareList); 

    View rootView = inflater.inflate(R.layout.fragment_my, container, false); 
    //View resultsView = inflater.inflate(R.layout.results, container, false); 

    View resultsView = inflater.inflate(R.layout.fragment_my, container, false); 

    ListView listView = (ListView) resultsView.findViewById(R.id.listview_FoursquareInfo); 
    listView.setAdapter(mFoursquareAdapter); 

    Button btnGetFoursquareData = (Button) rootView.findViewById(R.id.btnFoursquare); 
    btnGetFoursquareData.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      FetchFoursquareDataTask fetch = new FetchFoursquareDataTask(); 
      fetch.execute("Starbucks"); 
     } 
    }); 

    return rootView; 
} 


public class FetchFoursquareDataTask extends AsyncTask<String, Void, String[]> { 
    private final String LOG_TAG = FetchFoursquareDataTask.class.getSimpleName(); 

    @Override 
    protected void onPostExecute(String[] result) { 
     if (result != null) { 
      mFoursquareAdapter.clear(); 
      for (String ItemStr : result) { 
       mFoursquareAdapter.add(ItemStr); 
      } 

      mFoursquareAdapter.notifyDataSetChanged(); 
     } 
    } 


    @Override 
    protected String[] doInBackground(String... params) { 

     // If there's no venue category, theres nothing to look up. Verify the size of the params. 
     if (params.length == 0) { 
      return null; 
     } 
     // These two need to be declared outside the try/catch 
     // so that they can be closed in the finally block. 
     HttpURLConnection urlConnection = null; 
     BufferedReader reader = null; 

     // Will contain the raw JSON response as a string. 
     String foursquareJsonStr = null; 

     try { 
      // Build Foursquare URI with Parameters 
      final String FOURSQUARE_BASE_URL = 
        "https://api.foursquare.com/v2/venues/search"; 
      final String client_id = "client_id"; 
      final String client_secret = "client_secret"; 
      final String v = "20130815"; 
      final String near = "Dunwoody, Ga"; 
      final String query = "Starbucks"; 
      final String limit = "2"; 

      Uri builtUri = Uri.parse(FOURSQUARE_BASE_URL).buildUpon() 
        .appendQueryParameter("client_id", client_id) 
        .appendQueryParameter("client_secret", client_secret) 
        .appendQueryParameter("v", v) 
        .appendQueryParameter("near", near) 
        .appendQueryParameter("query", query) 
        .appendQueryParameter("limit", limit) 
        .build(); 

      URL url = new URL(builtUri.toString()); 

      // Create the request to Foursquare, and open the connection 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.connect(); 

      // Read the input stream into a String 
      InputStream inputStream = urlConnection.getInputStream(); 
      StringBuffer buffer = new StringBuffer(); 
      if (inputStream == null) { 
       // Nothing to do. 
       return null; 
      } 
      reader = new BufferedReader(new InputStreamReader(inputStream)); 

      String line; 
      while ((line = reader.readLine()) != null) { 

       buffer.append(line + "\n"); 
      } 

      if (buffer.length() == 0) { 
       // Stream was empty. No point in parsing. 
       foursquareJsonStr = null; 
       return null; 
      } 
      foursquareJsonStr = buffer.toString(); 

      Log.v(LOG_TAG, "Foursquare JSON String: " + foursquareJsonStr); 
     } catch (IOException e) { 
      Log.e(LOG_TAG, "Error ", e); 
      // If the code didn't successfully get the fpursquare data, there's no point in attempting 
      // to parse it. 
      return null; 
     } finally { 
      if (urlConnection != null) { 
       urlConnection.disconnect(); 
      } 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (final IOException e) { 
        Log.e("PlaceholderFragment", "Error closing stream", e); 
       } 
      } 
     } 

     String[] list = new String[]{"", ""}; 
     try { 

      JSONObject foursquareJson = new JSONObject(foursquareJsonStr); 
      JSONObject responseObject = (JSONObject) foursquareJson.get("response"); 
      JSONArray foursquareArray = responseObject.getJSONArray("venues"); 
      list = new String[foursquareArray.length()]; 

      for (int i = 0; i < foursquareArray.length(); i++) { 

       list[i] = foursquareArray.get(i).toString(); 
      } 

      return list; 
     } catch (JSONException e) { 
      Log.e(LOG_TAG, e.getMessage(), e); 
      e.printStackTrace(); 
     } finally { 
      Log.e(LOG_TAG, "ba"); 
      return list; 
     } 

    } 

} 

}

+0

ListView를 만드는 방법에 대한 자습서를 확인하십시오. http://www.android-ios-tutorials.com/ 770/create-custom-listview-in-android/ – Houcine

+0

'Adapter'가 아닌'List'를 추가해야합니다. – ElefantPhace

답변

0

mFoursquareAdapter.add(ItemStr); 

foursquareList.add(ItemStr) 

해야하며, 당신은 (필드로) 제대로 foursquareList를 선언해야합니다. Adapter도 필드 변수로 선언해야합니다. 나중에 참조 할 필요가있는 경우를 대비하여

+0

안녕 ElefantPhace 개인 목록을 제안하고 선언했을 때 수행했습니다 foursquareList; 상단에 설정하고 OnCreateView 함수의 데이터를 설정합니다. foursquareList = new ArrayList (Arrays.asList (data)); 및 OnPostExecute있는 foursquareList.add (ItemStr) 언급 한 것처럼 여전히 목록 상자 내용으로 화면을 새로 고치지 않는다, 나는 두 항목이 있지만 중단 점 볼 수 있습니다. – user3294878

관련 문제