2

I am doing a project which containS a Custom List-view Adapter. In this list-view I have added data from a JSON feed using YouTube API. Now I want to add a search button in the top of the list-view. This will search the content in List-view. How can I do this?

Here is my code..

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

My listView Adapter is here....

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;


}
Amit Saha
  • 121
  • 1
  • 10

2 Answers2

0

Try this : - Add a search button in the top of listview : here

Community
  • 1
  • 1
Quang Doan
  • 632
  • 4
  • 12
0

Since you mentioned that you are using a ListView, i think the following might work for you.
in xml
just add a searchview on top your 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>

in your adapter
do the following changes in your adapter,implement the Filterable interface along with the getFilter() method

in your class Write a custom class that extends the android.widget.Filter and override these 2 methods and perform your Business logic inside it.

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

As an example of how to use it refer this

Aniruddha K.M
  • 7,361
  • 3
  • 43
  • 52