填充 listview API 调用

Posted

技术标签:

【中文标题】填充 listview API 调用【英文标题】:Populating listview API call 【发布时间】:2016-03-21 11:27:36 【问题描述】:

我是 android 新手,正在尝试弄清楚如何将 searchActivity 中的搜索关键字字符串“tag”传递到 SearchResult 中的 API URL,以显示在 SearchResult 的列表视图中。

我在填充列表视图时遇到问题 - 我的设置或适配器中是否缺少某些内容?

SearchActivity.java

public class SearchActivity extends Activity 
private static final String TAG = SearchActivity.class.getName();

private ArrayList<Photo> photos;
private PhotosAdapter photosAdapter;

EditText mSearch;
String searchedTag;
Button goSearch;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);

    mSearch = (EditText) findViewById(R.id.searchField);
    goSearch = (Button) findViewById(R.id.gosearch);

    goSearch.setOnClickListener(new View.OnClickListener() 

        public void onClick(View v) 

            Intent result = new Intent(SearchActivity.this, SearchResult.class );
            result.putExtra ( "searchkey", mSearch.getText().toString() );
            startActivity(result);


        
    );





@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_search, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);

SearchResult.java

 public class SearchResult extends Activity 

private ArrayList<Photo> photosSearch;
private PhotoAdapterSearch photosAdapterSearch;


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_result);

    Intent myintent = getIntent();
    String tag = myintent.getStringExtra("searchkey");


    getTags(tag);


private void getTags(String tag) 



    photosSearch = new ArrayList<Photo>();

    // Create adapter
    photosAdapterSearch = new PhotoAdapterSearch(this, photosSearch);

    ListView listViewResult = (ListView) findViewById(R.id.listViewResult);
    // Set the adapter
    listViewResult.setAdapter(photosAdapterSearch);

    String TAGGED_IMAGES_URL = "https://api.instagram.com/v1/tags/"+tag+"/media/recent?access_token=55408742.1677ed0.ad911fb2100340d9807ab22162e58dc1";

    new AsycnGet().execute(TAGGED_IMAGES_URL);




public class AsycnGet extends AsyncTask<String, Void, String> 
    @Override
    protected String doInBackground(String... params) 
        try 
            URL url = new URL(params[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            StringBuilder builder = new StringBuilder("");

            while ((line = reader.readLine()) != null)
                builder.append(line);

            return builder.toString();
         catch (MalformedURLException e) 
            e.printStackTrace();
         catch (IOException e) 
            e.printStackTrace();
        

        return "";
    

    @Override
    protected void onPostExecute(String s) 
        if (s != null && s != "") 
            try 
                JSONObject response = (JSONObject) new JSONTokener(s).nextValue();
                JSONArray photosJSON = response.getJSONArray("data");
                for (int i = 0; i < photosJSON.length(); i++) 
                    JSONObject photoJSON = photosJSON.getJSONObject(i);
                    Photo photosearch = new Photo();

                    photosearch.imageUrl = photoJSON.getJSONObject("images").getJSONObject("standard_resolution").getString("url");
                    photosearch.imageHeight = photoJSON.getJSONObject("images").getJSONObject("standard_resolution").getInt("height");


                    photosSearch.add(photosearch);
                

             catch (JSONException e) 
                e.printStackTrace();
            

        
    



@Override
public boolean onCreateOptionsMenu(Menu menu) 

    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 


    int id = item.getItemId();

    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);


PhotoAdapterSearch.Java 公共类 PhotoAdapterSearch 扩展 ArrayAdapter

public PhotoAdapterSearch(Context context, List<Photo> photos) 
    super(context, android.R.layout.simple_expandable_list_item_1, photos);



@Override
public View getView(final int position, View convertView, ViewGroup parent) 

    //get photo at position
    final Photo photo = getItem(position);


    if (convertView == null) 
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.image_search, null, false);
    



    ImageView myImageViewsearch = (ImageView) convertView.findViewById(R.id.imagesearch);

    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    myImageViewsearch.getLayoutParams().height = displayMetrics.widthPixels;


    myImageViewsearch.setImageResource(0);
    // insert the image using picasso
    int ratio = photo.imageWidth / photo.imageHeight;
    int width = getContext().getResources().getDisplayMetrics().widthPixels;
    int height = width / Math.max(1, ratio);
    Picasso.with(getContext()).load(photo.imageUrl).resize(0, height).placeholder(R.drawable.placeholder).into(myImageViewsearch);


    return convertView;


【问题讨论】:

您能发布您的 PhotoAdapterSearch 代码吗? 另外,您可能想在将照片添加到数组后尝试在onPostExecute 中调用photosAdapterSearch.notifyDatasetChanged() 当我添加 notifyDataSetChanged() 时应用停止 抛出了什么异常? 【参考方案1】:

您给适配器一个空列表,它会构建 0 个项目的 ListView。 如果您希望适配器重建列表(例如当您将项目下载到数组时),您应该调用 adapter.notifyDataSetChanged(); (我可能会打错确切的名字)

如果您也提供适配器的来源,也许会有所帮助。

【讨论】:

添加这个会导致应用崩溃

以上是关于填充 listview API 调用的主要内容,如果未能解决你的问题,请参考以下文章

通过自定义listView同时选择和搜索不起作用

按特定值对 ListView 或 ListView.ItemTemplate 进行排序

Listview 没有被填充,getView() 没有被调用

listview.setSelection()

ListView添加节点

从 AsyncTask 填充 ListView 的 Android 小部件