如何使用Youtube API在JSON列表视图中添加搜索选项



我正在做一个包含自定义列表视图适配器的项目。在这个列表视图中,我使用YouTube API添加了来自JSON提要的数据。现在我想在列表视图的顶部添加一个搜索按钮。这将在列表视图中搜索内容。我该怎么做?

这是我的密码。。

public class MainActivity extends ActionBarActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
private AdView mAdView;
private InterstitialAd interstitial;
private long lastPressedTime;
static String imgURL = "url";
static String VIDEO_ID = "videoId";
static String TITLE = "title";
static String THUMBNAILS = "img";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.listview_main);
    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();
    AdView mAdView = new AdView(this);
    mAdView.setAdSize(AdSize.SMART_BANNER);
    // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
    // values/strings.xml.
    mAdView = (AdView) findViewById(R.id.ad_view);

    // Create an ad request. Check logcat output for the hashed device ID to
    // get test ads on a physical device. e.g.
    // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice("CF2B5D5C45BA785670BBCAEA9269EA35")
            .build();
    // Start loading the ad in the background.
    mAdView.loadAd(adRequest);

}


// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("বাংলা নাটক ২০১৫");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }
    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        String query = "bangla natok 2015";
        query = query.replace(" ", "+");
        try {
            query = URLEncoder.encode(query, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&order=viewCount&q=bangla+natok+2015+full&maxResults=50&key=AIzaSyCojCp66RLS9OY8hOwnW0UWLNdC56z24Os");
        try {
            // Locate the array name in JSON
            JSONArray jsonarray = jsonobject.getJSONArray("items");
            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                JSONObject jsonObjId = jsonobject.getJSONObject("id");
                map.put("videoId", jsonObjId.getString("videoId"));
                JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
                map.put("title", jsonObjSnippet.getString("title"));
                //map.put("description", jsonObjSnippet.getString("description"));
                // map.put("flag", jsonobject.getString("flag"));
                JSONObject jsonObjThumbnail = jsonObjSnippet.getJSONObject("thumbnails");
                String imgURL = jsonObjThumbnail.getJSONObject("high").getString("url");
                map.put("url",imgURL);

                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(MainActivity.this, arraylist);
        // Set the adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent)
{
    int i = 0;
    boolean bool = true;
    if (paramKeyEvent.getKeyCode() == 4) {
        switch (paramKeyEvent.getAction())
        {
            case 0:
                if (paramKeyEvent.getDownTime() - this.lastPressedTime >= 3000L)
                {
                    Toast.makeText(getApplicationContext(), "Press Back To Exit", 0).show();
                    this.interstitial = new InterstitialAd(this);
                    this.interstitial.setAdUnitId("ca-app-pub-4265785833148880/6768099054");
                    AdRequest localAdRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("CF2B5D5C45BA785670BBCAEA9269EA35").build();
                    this.interstitial.loadAd(localAdRequest);
                    this.interstitial.setAdListener(new AdListener()
                    {
                        private void displayInterstitial()
                        {
                            if (MainActivity.this.interstitial.isLoaded()) {
                                MainActivity.this.interstitial.show();
                            }
                        }
                        public void onAdLoaded()
                        {
                            displayInterstitial();
                        }
                    });
                    this.lastPressedTime = paramKeyEvent.getEventTime();
                }
                else
                {
                    finish();
                }
                bool = true;
        }
    }
    return bool;
}
@Override
public boolean onCreateOptionsMenu(Menu paramMenu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, paramMenu);
    return true;
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
    switch (paramMenuItem.getItemId())
    {
        default:
            super.onOptionsItemSelected(paramMenuItem);
        case R.id.rate_app:
            Toast.makeText(getApplicationContext(), "Rate This App", Toast.LENGTH_SHORT).show();
            super.onOptionsItemSelected(paramMenuItem);
            startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=com.nextappsbd.banglanatok2015")));
            break;
        case R.id.share_app:
            Intent localIntent = new Intent("android.intent.action.SEND");
            localIntent.setType("text/plain");
            localIntent.putExtra("android.intent.extra.TEXT", "Enjoy This Apps https://play.google.com/store/apps/details?id=com.nextappsbd.banglanatok2015");
            startActivity(Intent.createChooser(localIntent, "Share This App Using"));
            break;
        case R.id.check_update:
            Toast.makeText(getApplicationContext(), "Update This App", Toast.LENGTH_SHORT).show();
            startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=com.nextappsbd.banglanatok2015")));
            break;
        case R.id.exit:
            finish();
            System.exit(0);
    }
    return true;
}

我的listView适配器在这里。。。。

public class ListViewAdapter extends BaseAdapter {
// Declare Variables
MainActivity main;
private PublisherInterstitialAd mPublisherInterstitialAd;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
                       ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);
}

@Override
public int getCount() {
    return data.size();
}
@Override
public Object getItem(int position) {
    return null;
}
@Override
public long getItemId(int position) {
    return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView rank;
    TextView country;
    TextView population;
    ImageView flag;
    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.listview_item, parent, false);
    // Get the position
    resultp = data.get(position);
    // Locate the TextViews in listview_item.xml
    //rank = (TextView) itemView.findViewById(R.id.rank);
    country = (TextView) itemView.findViewById(R.id.country);
    // population = (TextView) itemView.findViewById(R.id.population);
    // Locate the ImageView in listview_item.xml
    flag = (ImageView) itemView.findViewById(R.id.flag);
    // Capture position and set results to the TextViews
    // rank.setText(resultp.get(MainActivity.VIDEO_ID));
    country.setText(resultp.get(MainActivity.TITLE));
    // population.setText(resultp.get(MainActivity.DESCRIPTION));
    // Capture position and set results to the ImageView
    // Passes flag images URL into ImageLoader.class
    imageLoader.DisplayImage(resultp.get(MainActivity.imgURL), flag);
    // Capture ListView item click
    mPublisherInterstitialAd = new PublisherInterstitialAd(context);
    mPublisherInterstitialAd.setAdUnitId("ca-app-pub-4265785833148880/6768099054");
    mPublisherInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            requestNewInterstitial();
        }
    });
    requestNewInterstitial();
    itemView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, PlayerViewDemoActivity.class);
                intent.putExtra("videoId", resultp.get(MainActivity.VIDEO_ID));
                context.startActivity(intent);
                mPublisherInterstitialAd.isLoaded();
                mPublisherInterstitialAd.show();

            requestNewInterstitial();
        }
    });
    return itemView;

}

试试这个:-在列表视图的顶部添加一个搜索按钮:此处

  • 在列表视图中搜索内容:此链接

由于您提到您正在使用ListView,我认为以下内容可能适用于您
在xml中
只需在列表顶部添加一个搜索视图即可查看

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_label"
    android:hint="@string/search_hint" >
</searchable>

在适配器中
在适配器中进行以下更改,实现Filterable接口和getFilter()方法

在您的班级编写一个自定义类来扩展android.widget.Filter并覆盖这两种方法,并在其中执行您的业务逻辑。

FilterResults performFiltering(CharSequence constraint) and 
void publishResults(CharSequence constraint,FilterResults results)

作为如何使用它的示例,请参阅此

相关内容

  • 没有找到相关文章