0

я реализовал ListView с помощью Volley Library Из этого урока Custom Volley ListViewFilter Android Поиск с помощью панели действий

После этого я реализовал SearchView и поиска Результат деятельности как этот

BaseActivity

import android.app.AlertDialog; 
import android.app.SearchManager; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.graphics.Color; 
import android.graphics.drawable.ColorDrawable; 
import android.os.Bundle; 
import android.provider.MediaStore; 
import android.support.v4.app.ActionBarDrawerToggle; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarActivity; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.FrameLayout; 
import android.widget.ListView; 
import android.widget.SearchView; 

import com.enventpc_03.nav11.adapters.NavigationDrawerListAdapter; 
import com.enventpc_03.nav11.adater.CustomListAdapter; 
import com.enventpc_03.nav11.models.Items; 

import java.util.ArrayList; 

/** 
* @author dipenp 
*   <p> 
*   This activity will add Navigation Drawer for our application and all the code related to navigation drawer. 
*   We are going to extend all our other activites from this BaseActivity so that every activity will have Navigation Drawer in it. 
*   This activity layout contain one frame layout in which we will add our child activity layout. 
*/ 
public class BaseActivity extends ActionBarActivity { 
    protected static final int CAMERA_REQUEST = 0; 
    protected static final int RESULT_LOAD_IMAGE = 1; 
    public CustomListAdapter adapter; 
    /** 
    * Static variable for selected item position. Which can be used in child activity to know which item is selected from the list. 
    */ 
    protected static int position; 
    /** 
    * This flag is used just to check that launcher activity is called first time 
    * so that we can open appropriate Activity on launch and make list item position selected accordingly. 
    */ 
    private static boolean isLaunch = true; 
    /** 
    * Frame layout: Which is going to be used as parent layout for child activity layout. 
    * This layout is protected so that child activity can access this 
    */ 
    protected FrameLayout frameLayout; 
    /** 
    * ListView to add navigation drawer item in it. 
    * We have made it protected to access it in child class. We will just use it in child class to make item selected according to activity opened. 
    */ 

    protected ListView mDrawerList; 
    /** 
    * List item array for navigation drawer items. 
    */ 
    protected String[] listArray = {"Home"}; 
    protected ArrayList<Items> _items; 
    /** 
    * Base layout node of this Activity. 
    */ 
    private DrawerLayout mDrawerLayout; 

    /** 
    * Drawer listner class for drawer open, close etc. 
    */ 
    private ActionBarDrawerToggle actionBarDrawerToggle; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.navigation_drawer_base_layout); 
     frameLayout = (FrameLayout) findViewById(R.id.content_frame); 
     mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); 
     mDrawerList = (ListView) findViewById(R.id.left_drawer); 
    // handleIntent(getIntent()); 

     // set a custom shadow that overlays the main content when the drawer opens 
     //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); 

     _items = new ArrayList<Items>(); 
     _items.add(new Items("Home", R.drawable.ic_home1)); 

     _items.add(new Items("Exit", R.drawable.ic_exit1)); 

//  //Adding header on list view 
//  View header = (View)getLayoutInflater().inflate(R.layout.list_view_header_layout, null); 
//  mDrawerList.addHeaderView(header); 

     // set up the drawer's list view with items and click listener 
     mDrawerList.setAdapter(new NavigationDrawerListAdapter(this, _items)); 
     mDrawerList.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
            int position, long id) { 

       openActivity(position); 
      } 
     }); 

     // Change Action Bar Background Color "may be not works" 
     getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff8c00"))); 

     // enable ActionBar app icon to behave as action to toggle nav drawer 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setHomeButtonEnabled(true); 
     getSupportActionBar().setHomeAsUpIndicator(R.drawable.action); 



     // ActionBarDrawerToggle ties together the the proper interactions between the sliding drawer and the action bar app icon 
     actionBarDrawerToggle = new ActionBarDrawerToggle(
       this,      /* host Activity */ 
       mDrawerLayout,    /* DrawerLayout object */ 
       R.drawable.ic_nirvan,  /* nav drawer image to replace 'Up' caret */ 
       R.string.open_drawer,  /* "open drawer" description for accessibility */ 
       R.string.close_drawer)  /* "close drawer" description for accessibility */ 

    /*mDrawerToggle = new ActionBarDrawerToggle(
      getActivity(), 
      mDrawerLayout, 
      R.string.navigation_drawer_open, 
      R.string.navigation_drawer_close 
) 
    * */ { 
      @Override 
      public void onDrawerClosed(View drawerView) { 
//    getSupportActionBar().setTitle(listArray[position]); 
       invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
       super.onDrawerClosed(drawerView); 
      } 

      @Override 
      public void onDrawerOpened(View drawerView) { 
       getSupportActionBar().setTitle(getString(R.string.app_name)); 
       invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() 
       super.onDrawerOpened(drawerView); 
      } 

      @Override 
      public void onDrawerSlide(View drawerView, float slideOffset) { 
       super.onDrawerSlide(drawerView, slideOffset); 
      } 

      @Override 
      public void onDrawerStateChanged(int newState) { 
       super.onDrawerStateChanged(newState); 
      } 
     }; 
     mDrawerLayout.setDrawerListener(actionBarDrawerToggle); 


     /** 
     * As we are calling BaseActivity from manifest file and this base activity is intended just to add navigation drawer in our app. 
     * We have to open some activity with layout on launch. So we are checking if this BaseActivity is called first time then we are opening our first activity. 
     * */ 
     if (isLaunch) { 
      /** 
      *Setting this flag false so that next time it will not open our first activity. 
      *We have to use this flag because we are using this BaseActivity as parent activity to our other activity. 
      *In this case this base activity will always be call when any child activity will launch. 
      */ 
      isLaunch = false; 
      openActivity(0); 
     } 
    } 



// 
    /** 
    * @param position Launching activity when any list item is clicked. 
    */ 
    protected void openActivity(int position) { 

     /** 
     * We can set title & itemChecked here but as this BaseActivity is parent for other activity, 
     * So whenever any activity is going to launch this BaseActivity is also going to be called and 
     * it will reset this value because of initialization in onCreate method. 
     * So that we are setting this in child activity. 
     */ 

     mDrawerLayout.closeDrawer(mDrawerList); 
     BaseActivity.position = position; //Setting currently selected position in this field so that it will be available in our child activities. 

     switch (position) { 
      case 0: 
       startActivity(new Intent(this, Login.class)); 
       break; 

         .setNegativeButton("No", new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 

           dialog.cancel(); 
          } 
         }); 

       AlertDialog alertDialog = alertDialogBuilder.create(); 
       alertDialog.show(); 

       break; 

      default: 

       break; 
     } 

//  Toast.makeText(this, "Selected Item Position::"+position, Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 

     MenuInflater inflater = getMenuInflater(); 
     // Inflate menu to add items to action bar if it is present. 
     inflater.inflate(R.menu.main, menu); 

     SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
     SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView(); 
     search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); 
     search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 
      @Override 
      public boolean onQueryTextSubmit(String query) { 
       return false; 
      } 

      @Override public boolean onQueryTextChange(String newText) 
      { 
       PerfromSearch(newText); 
       return false; 
      } 

     }); 
     return true; 
    } 

    void PerfromSearch(String query) { 

     adapter.filter(query); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 

     // The action bar home/up action should open or close the drawer. 
     // ActionBarDrawerToggle will take care of this. 
     if (actionBarDrawerToggle.onOptionsItemSelected(item)) { 
      return true; 
     } 

     switch (item.getItemId()) { 
      case R.id.action_settings: 
       return true; 

      default: 
       return super.onOptionsItemSelected(item); 
     } 
    } 

    /* Called whenever we call invalidateOptionsMenu() */ 
    @Override 
    public boolean onPrepareOptionsMenu(Menu menu) { 
     // If the nav drawer is open, hide action items related to the content view 
     boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); 
     menu.findItem(R.id.action_settings).setVisible(!drawerOpen); 
     return super.onPrepareOptionsMenu(menu); 
    } 




} 

другой Мероприятие, в котором представлен список волейбола

import android.app.ProgressDialog; 
import android.app.SearchManager; 
import android.content.Intent; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.android.volley.Response; 
import com.android.volley.VolleyError; 
import com.android.volley.VolleyLog; 
import com.android.volley.toolbox.JsonArrayRequest; 
import com.enventpc_03.nav11.adater.CustomListAdapter; 
import com.enventpc_03.nav11.app.AppController; 
import com.enventpc_03.nav11.model.Movie; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.List; 

public class SearchPeople extends BaseActivity { 
    // Log tag 
    private static final String TAG = SearchPeople.class.getSimpleName(); 

    // Movies json url 
    // Movies json url 
    private static String url = "http://myulr/demo.php"; 

    private static String Title = "title"; 

    private ProgressDialog pDialog; 
    private List<Movie> movieList = new ArrayList<Movie>(); 
    private ListView listView; 
    private CustomListAdapter adapter; 
    public static final String BITMAP_ID = "id"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     getLayoutInflater().inflate(R.layout.activity_search, frameLayout); 

     listView = (ListView) findViewById(R.id.list); 
     adapter = new CustomListAdapter(this, movieList); 
     listView.setAdapter(adapter); 

     //For searchResultActivity 
     Intent intent = getIntent(); 
     if (Intent.ACTION_SEARCH.equals(intent.getAction())) { 
      String query = intent.getStringExtra(SearchManager.QUERY); 
      doMySearch(query); 
     } 






     pDialog = new ProgressDialog(this); 
     // Showing progress dialog before making http request 
     pDialog.setMessage("Loading..."); 
     pDialog.show(); 

//  // changing action bar color 
//  getActionBar().setBackgroundDrawable(
//    new ColorDrawable(Color.parseColor("#1b1b1b"))); 

     // Creating volley request obj 
     JsonArrayRequest movieReq = new JsonArrayRequest(url, 
       new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         Log.d(TAG, response.toString()); 
         hidePDialog(); 

         // Parsing json 
         for (int i = 0; i < response.length(); i++) { 

          try { 
           JSONObject obj = response.getJSONObject(i); 
           Movie movie = new Movie(); 
           movie.setTitle(obj.getString("fullname")); 


           movie.setYear(obj.getInt("id") 

           // adding movie to movies array 
           movieList.add(movie); 

          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 


         } 

         // notifying list adapter about data changes 
         // so that it renders the list view with updated data 
         adapter.notifyDataSetChanged(); 
        } 
       }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       VolleyLog.d(TAG, "Error: " + error.getMessage()); 
       hidePDialog(); 

      } 
     }); 

     // Adding request to request queue 
     AppController.getInstance().addToRequestQueue(movieReq); 

     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
       // your code 
       // TODO Auto-generated method stub 
       String name = ((TextView) view.findViewById(R.id.title)).getText().toString(); 
       String location = ((TextView) view.findViewById(R.id.rating)).getText().toString(); 
       String description = ((TextView) view.findViewById(R.id.genre)).getText().toString(); 

       bitmap = ((Movie) movieList.get(position)).getThumbnailUrl(); 
       Intent intent = new Intent(SearchPeople.this, Details.class); 
       intent.putExtra(Title, name); 
       intent.putExtra(Location, location); 
       intent.putExtra(Description, description); 
       intent.putExtra("images", bitmap); 


       startActivity(intent); 

      } 
     }); 
    } 


    private void doMySearch(String query) 
    { 

     Log.d("Event",query); 
     Toast.makeText(SearchPeople.this,query,Toast.LENGTH_SHORT).show(); 


    } 
    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     hidePDialog(); 
    } 

    private void hidePDialog() { 
     if (pDialog != null) { 
      pDialog.dismiss(); 
      pDialog = null; 
     } 
    } 

    public void onBackPressed() { 
     Intent myIntent = new Intent(SearchPeople.this, UploadActivity.class); 
     myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack 
     startActivity(myIntent); 
     finish(); 
     return; 
    } 


} 

Теперь после поиска он переходит к searchresultactivity Но я не понимаю, как напечатать здесь наш отфильтрованный результат поиска в соответствии с запросом.

+0

проверка ниже ответ –

ответ

1

Не нужно создавать сложные условия.

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 

    MenuInflater inflater = getMenuInflater(); 
    // Inflate menu to add items to action bar if it is present. 
    inflater.inflate(R.menu.main, menu); 

    SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
    SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView(); 
    search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); 
    search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { 
     @Override 
     public boolean onQueryTextSubmit(String query) { 
      return false; 
     } 

     @Override 
     public boolean onQueryTextChange(String newText) { 
       PerfromSearch(newText); 
      return false; 
     } 
    }); 
    return true; 
} 

void PerfromSearch(String query) { 

    adapter.filter(query); 
} 

Ваш адаптер:

public class CustomListAdapter extends BaseAdapter { 
    private Activity activity; 
    private LayoutInflater inflater; 
    private List<Movie> movieItems; 
    private List<Movie> movieItemSearched = null; 
    ImageLoader imageLoader = AppController.getInstance().getImageLoader(); 

    public CustomListAdapter(Activity activity, List<Movie> movieItems) { 
     this.activity = activity; 
     this.movieItems = movieItems; 
     this.movieItemSearched = new ArrayList<Movie>(); 
     this.movieItemSearched.addAll(movieItems); 
    } 

    @Override 
    public int getCount() { 
     return movieItems.size(); 
    } 

    @Override 
    public Object getItem(int location) { 
     return movieItems.get(location); 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

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

     if (inflater == null) 
      inflater = (LayoutInflater) activity 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     if (convertView == null) 
      convertView = inflater.inflate(R.layout.list_row, null); 

     if (imageLoader == null) 
      imageLoader = AppController.getInstance().getImageLoader(); 
     NetworkImageView thumbNail = (NetworkImageView) convertView 
       .findViewById(R.id.thumbnail); 
     TextView title = (TextView) convertView.findViewById(R.id.title); 
     TextView rating = (TextView) convertView.findViewById(R.id.rating); 
     TextView genre = (TextView) convertView.findViewById(R.id.genre); 
     TextView year = (TextView) convertView.findViewById(R.id.releaseYear); 

     // getting movie data for the row 
     Movie m = movieItems.get(position); 

     // thumbnail image 
     thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader); 

     // title 
     title.setText(m.getTitle()); 

     // rating 
     rating.setText("Rating: " + String.valueOf(m.getRating())); 

     // genre 
     String genreStr = ""; 
     for (String str : m.getGenre()) { 
      genreStr += str + ", "; 
     } 
     genreStr = genreStr.length() > 0 ? genreStr.substring(0, 
       genreStr.length() - 2) : genreStr; 
     genre.setText(genreStr); 

     // release year 
     year.setText(String.valueOf(m.getYear())); 

     return convertView; 
    } 

    // Filter Class 
    public void filter(String charText) { 
     charText = charText.toLowerCase(Locale.getDefault()); 
     movieItems.clear(); 
     if (charText.length() == 0) { 
      movieItems.addAll(movieItemSearched); 
     } else { 
      for (Movie wp : movieItemSearched) { 
       if (wp.getTitle().toLowerCase(Locale.getDefault()) 
         .contains(charText)) { 
        movieItems.add(wp); 
       } 
      } 
     } 
     notifyDataSetChanged(); 
    } 

} 
Смежные вопросы