2015-12-29 40 views
2

我正在做一個包含自定義列表視圖適配器的項目。在這個列表視圖中,我使用YouTube API添加了來自JSON訂閱源的數據。現在我想在列表視圖的頂部添加一個搜索按鈕。這將搜索列表視圖中的內容。我怎樣才能做到這一點?如何使用Youtube API在JSON 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("ABCDEF") 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; 


} 
+0

什麼樣的代碼你試過到目前爲止的例子嗎?如果我們可以看到你的代碼更容易幫助你.. – Clay

+0

我編輯我的問題的代碼 –

+0

歡迎來到堆棧溢出。我在你的問題中解決了英文問題。如果您有可見的東西,請添加屏幕截圖。它會幫助別人更快地幫助你。 –

回答

0

試試這個: - 在列表視圖頂部添加一個搜索按鈕:here

+0

我的內容經常發生變化......所以我該怎麼做?在這些教程中,這不是描述 –

0

既然你提到你正在使用一個ListView,我覺得有以下可能會爲你工作。
在XML
只需添加在上面搜索查看您的ListView

<?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> 

在適配器
做您的適配器以下更改,實現過濾的接口與用getFilter沿()方法

你的班級 編寫一個擴展android.widget.Filter 的自定義類,並覆蓋這兩個方法並在其中執行業務邏輯。

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

至於如何使用它指this

+0

我無法理解.....我是一個初學者...可以請你描述整個過程。 –

+0

我也用ListView Adapter類編輯我的問題 –

相關問題