MyFragment
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
final View layoutSearch = inflater.inflate(R.layout.fragment_search, container, false);
mswipeRefreshLayout=(SwipeRefreshLayout) layoutSearch.findViewById(R.id.searchMoviesRefresh);
mswipeRefreshLayout.setOnRefreshListener(this);
textVolleyError = (TextView) layoutSearch.findViewById(R.id.textVolleyError);
listMovieHits = (RecyclerView) layoutSearch.findViewById(R.id.search_movies);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
search=(SearchView) layoutSearch.findViewById(R.id.searchView1);
search.setQueryHint("Start typing to search...");
buttonBarcode = (ImageButton) layoutSearch.findViewById(R.id.imageButton2);
buttonAudio = (ImageButton) layoutSearch.findViewById(R.id.imageButton1);
search.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
}
});search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
L.t(getActivity(), newText);
if (newText.length() > 3) {
listMovieHits.setVisibility(layoutSearch.getVisibility());
searchForMovies m = (searchForMovies) new searchForMovies().execute(newText);
} else {
listMovieHits.setVisibility(layoutSearch.INVISIBLE);
}
return false;
}
});
listMovieHits.setAdapter(mAdapterBoxOffice);
if (savedInstanceState != null) {
mlistMovies = savedInstanceState.getParcelableArrayList(STATE_MOVIES);
} else {
L.t(getActivity(), "executing task from the fragment");
/*new TaskLoadSearchMovies(this).execute();*/
}
/* mAdapterBoxOffice.setMovieList(filteredProductResults);
mAdapterBoxOffice.SetOnclickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
container.getContext().startActivity(new Intent(container.getContext(), Details_Activity.class));
}
});*/
return layoutSearch;
}
public void filterProductArray(String newText){
String sName;
filteredProductResults.clear();
for (int i=0; i<mlistMovies.size(); i++)
{
sName=mlistMovies.get(i).getTitle().toLowerCase();
if (sName.contains(newText.toLowerCase()))
{
filteredProductResults.add(mlistMovies.get(i));
}
}
}
class searchForMovies extends AsyncTask<String, Void, String>
{
Parser parser;
JSONArray listMovies;
String url=new String();
String textSearch;
ProgressDialog progressDialog;
@Override
protected void onPreExecute(){
super.onPreExecute();
listMovies=new JSONArray();
parser =new Parser();
progressDialog=new ProgressDialog(getActivity());
progressDialog.setCancelable(false);
progressDialog.setMessage("Searching....");
progressDialog.getWindow().setGravity(Gravity.CENTER);
progressDialog.show();
}
@Override
protected String doInBackground(String... params) {
url="http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey={MyID}="+params+"limit=30";
String returnMovieResult= getMovieList();
this.textSearch=params[0];
return returnMovieResult;
}
private String getMovieList() {
Movie tempMovie=new Movie();
String mathFound="N";
try{
JSONObject response = Requestor.sendRequestBoxOfficeMovies(requestQueue, url);
ArrayList<Movie> listMovies = Parser.parseMoviesJSON(response);
L.m(String.valueOf(listMovies));
}catch (Exception e){
e.printStackTrace();
return "error";
}
return ("Exception");
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result.equalsIgnoreCase("Exception Caught"))
{
Toast.makeText(getActivity(), "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
else
{
//calling this method to filter the search results from productResults and move them to
//filteredProductResults
filterProductArray(textSearch);
listMovieHits.setAdapter(mAdapterBoxOffice);
mAdapterBoxOffice.setFilteredMovies(mlistMovies);
progressDialog.dismiss();
}
}
}
AdapterClass
public class AdapterBoxOffice extends RecyclerView.Adapter<AdapterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
private ArrayList<Movie> mlistMovies = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd");
private int previousPosition=0;
AdapterView.OnItemClickListener mOnItemClickListener;
public AdapterBoxOffice(Context context) {
layoutInflater = LayoutInflater.from(context);
volleySingleton = VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movie> listMovies) {
this.mlistMovies = listMovies;
notifyDataSetChanged();
}
public void setFilteredMovies(ArrayList<Movie> filteredProductResults){
this.mlistMovies=filteredProductResults;
}
@Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_movie_box_office, parent, false);
ViewHolderBoxOffice viewHolder = new ViewHolderBoxOffice(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movie currentMovie = mlistMovies.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
Date movieReleaseDate = currentMovie.getReleaseDateTheater();
if (movieReleaseDate != null) {
String formmattedDate = dateFormat.format(movieReleaseDate);
holder.movieReleaseDate.setText(formmattedDate);
} else {
holder.movieReleaseDate.setText(Constants.NA);
}
int audienceScore=currentMovie.getAudienceScore();
if (audienceScore==-1){
holder.movieAudienceScore.setRating(0.0F);
holder.movieAudienceScore.setAlpha(0.5F);
}
else
{
holder.movieAudienceScore.setRating(currentMovie.getAudienceScore() / 20.0F);
holder.movieAudienceScore.setAlpha(1.0F);
}
if(position>previousPosition)
{
comeagain.materialdesign.anim.AnimationUtils.animate(holder, true);
}else {
comeagain.materialdesign.anim.AnimationUtils.animate(holder, false);
}
previousPosition=position;
String urlThumbnail = currentMovie.getUrlThumbnail();
loadImages(urlThumbnail, holder);
}
private void loadImages(String urlThumbnail, final ViewHolderBoxOffice holder) {
if (urlThumbnail != null) {
imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.movieThumbnail.setImageBitmap(response.getBitmap());
}
@Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
@Override
public int getItemCount() {
return mlistMovies.size();
}
class ViewHolderBoxOffice extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView movieThumbnail;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieAudienceScore;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
movieThumbnail = (ImageView) itemView.findViewById(R.id.movieThumbnail);
movieTitle = (TextView) itemView.findViewById(R.id.movieTitle);
movieReleaseDate = (TextView) itemView.findViewById(R.id.movieReleaseDate);
movieAudienceScore = (RatingBar) itemView.findViewById(R.id.movieAudienceScore);
}
}
logcat的
01-23 22:00:18.141 19563-19563/comeagain.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: comeagain.materialdesign, PID: 19563
java.lang.NullPointerException: Attempt to invoke virtual method 'void comeagain.materialdesign.adapters.AdapterBoxOffice.setFilteredMovies(java.util.ArrayList)' on a null object reference
at comeagain.materialdesign.fragments.FragmentSearch$searchForMovies.onPostExecute(FragmentSearch.java:270)
at comeagain.materialdesign.fragments.FragmentSearch$searchForMovies.onPostExecute(FragmentSearch.java:209)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我想在Json Api中实现搜索查询,问题是我得到了一个null异常。我不知道为什么filteredArray返回null,我真的不知道问题出在哪里,请帮我解决这个问题。