如何使用Youtube API在JSON Listview中添加搜索选项?

时间:2015-12-29 03:41:45

标签: android json youtube-api

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

这是我的代码..

@Override
public void onTabSelected(TabLayout.Tab tab) {

    pager.setCurrentItem(tab.getPosition());

}

我的listView适配器就在这里....

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

由于您提到您使用的是ListView,我认为以下内容可能对您有用 in xml
只需在listView

上添加一个searchview
<?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)

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