【问题标题】:Android listview not getting populated with dataAndroid列表视图没有填充数据
【发布时间】:2014-11-15 06:25:45
【问题描述】:

我是 Android Studio 的新手,我正在处理一个简单的 android 视图。单击按钮会调用foursquare API,并在我解析的位置周围获取星巴克的反馈结果,并尝试将其设置为同一视图上列表框的适配器。如果我在 OnPostExecute() 中放置一个断点,我看到我为 listview 设置的 mFoursquare 适配器在 mFoursquareAdapter 中有两个 json 字符串结果,我什至调用了

mFoursquareAdapter.notifyDataSetChanged();

在其中,但视图不会刷新结果。我已经发布了下面的代码。任何人都可以指出我做错了什么或需要改变,因为我已经有了结果并且需要完成这项工作......非常感谢您的帮助和反馈!谢谢

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;
        }

    }

}

}

【问题讨论】:

标签: java android android-fragments android-studio


【解决方案1】:

这个

mFoursquareAdapter.add(ItemStr);

应该是

foursquareList.add(ItemStr)

您需要正确声明foursquareList(作为字段)。 您还应该将您的 Adapter 声明为字段变量,以防您以后需要引用它

【讨论】:

  • 嗨 ElefantPhace 我按照你的建议做了并声明了私有 ListfoursquareList;在顶部并将其设置为 OnCreateView 函数中的数据,将其设置为foursquareList = new ArrayList(Arrays.asList(data));在 OnPostExecute 中,就像你提到的foursquareList.add(ItemStr) 但它仍然没有用列表框内容刷新屏幕,我可以在断点上看到它有两个项目,但没有用
猜你喜欢
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多