I have fragment with Asynctask class which needs to Re-Run the Asynctask from my Recyclerview adapter class.
Note : I want re run asynctask inside of viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() { in onBindViewHolder and when use this line.
new maghalat.GetContacts().execute(); //maghalt is name of fragment contain GetContacts asynctask function
Give me red line under this line without any suggestion
this is my adapter :
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<jsonContent> jcontent;
public DataAdapter(Context context, List<jsonContent> jcontent) {
this.context=context;
this.jcontent=jcontent;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view ;
if(i == R.layout.card_row) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
}else {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.button_card, viewGroup, false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder,int i) {
if(i == jcontent.size()) {
viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//try This
((maghalat )context).asyncRun();
}
});
viewHolder.buttonprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
});
viewHolder.go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.pages.setText(Integer.toString(jcontent.get(i-1).pages));
}
else {
viewHolder.title.setText(jcontent.get(i).title);
Picasso.with(context).load(jcontent.get(i).imgurl).resize(300, 400).into(viewHolder.imageView);
}
}
#Override
public int getItemCount() {
return jcontent.size()+1;
}
#Override
public int getItemViewType(int position) {
return (position == jcontent.size()) ? R.layout.button_card : R.layout.card_row;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,pages;
private ImageView imageView;
private Button buttonnext,buttonprev,go;
private CardView cardView;
private EditText editText;
public ViewHolder(final View view) {
super(view);
title = (TextView)view.findViewById(R.id.post_title);
imageView=(ImageView)view.findViewById(R.id.img);
buttonnext =(Button)view.findViewById(R.id.next);
buttonprev=(Button)view.findViewById(R.id.prev);
go=(Button)view.findViewById(R.id.go);
editText=(EditText)view.findViewById(R.id.et_go_page);
cardView=(CardView)view.findViewById(R.id.cvv);
pages=(TextView)view.findViewById(R.id.number_pages);
}
}
}
this is my fragment :
public class maghalat extends Fragment {
private RecyclerView recyclerView;
private DataAdapter adapter;
private View myFragmentView;
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private int numpage=0;
public int sag;
private String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(sag)+"/?json=get_posts";
List<jsonContent> listcontent=new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
if(isNetworkConnected()) {
asyncRun();
}else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
return myFragmentView;
}
public void asyncRun(){
new GetContacts().execute();
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
sag=numpage+1;
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(),listcontent);
recyclerView.setAdapter(adapter);
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private Context context;
List<jsonContent> jcontent;
private maghalat fragment;
public DataAdapter(Context context, List<jsonContent> jcontent, maghalat frag) {
this.context=context;
this.jcontent=jcontent;
this.fragment = frag;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view ;
if(i == R.layout.card_row) {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
}else {
view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.button_card, viewGroup, false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder,int i) {
if(i == jcontent.size()) {
viewHolder.buttonnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//try This
(fragment).asyncRun();
}
});
viewHolder.buttonprev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "pre", Toast.LENGTH_SHORT).show();
}
});
viewHolder.go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
viewHolder.pages.setText(Integer.toString(jcontent.get(i-1).pages));
}
else {
viewHolder.title.setText(jcontent.get(i).title);
Picasso.with(context).load(jcontent.get(i).imgurl).resize(300, 400).into(viewHolder.imageView);
}
}
#Override
public int getItemCount() {
return jcontent.size()+1;
}
#Override
public int getItemViewType(int position) {
return (position == jcontent.size()) ? R.layout.button_card : R.layout.card_row;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView title,pages;
private ImageView imageView;
private Button buttonnext,buttonprev,go;
private CardView cardView;
private EditText editText;
public ViewHolder(final View view) {
super(view);
title = (TextView)view.findViewById(R.id.post_title);
imageView=(ImageView)view.findViewById(R.id.img);
buttonnext =(Button)view.findViewById(R.id.next);
buttonprev=(Button)view.findViewById(R.id.prev);
go=(Button)view.findViewById(R.id.go);
editText=(EditText)view.findViewById(R.id.et_go_page);
cardView=(CardView)view.findViewById(R.id.cvv);
pages=(TextView)view.findViewById(R.id.number_pages);
}
}
}
Your Fragment
public class maghalat extends Fragment {
private RecyclerView recyclerView;
private DataAdapter adapter;
private View myFragmentView;
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private int numpage=0;
public int sag;
private String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(sag)+"/?json=get_posts";
List<jsonContent> listcontent=new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
if(isNetworkConnected()) {
asyncRun();
}else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
return myFragmentView;
}
public void asyncRun(){
new GetContacts().execute();
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
sag=numpage+1;
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(),listcontent,maghalat.this);
recyclerView.setAdapter(adapter);
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}
Related
UserAdapter.java :
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> {
private List<Users> usersList;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private Context mContext;
public class UsersViewHolder extends RecyclerView.ViewHolder {
public TextView txtUsername, txtCreatedAt;
public NetworkImageView imgUser;
public ImageButton btnMsg, btnDel;
public UsersViewHolder(View view) {
super(view);
txtUsername = (TextView) view.findViewById(R.id.txt_username);
txtCreatedAt = (TextView) view.findViewById(R.id.txt_created_at);
imgUser = (NetworkImageView) view.findViewById(R.id.img_user);
btnMsg = (ImageButton) view.findViewById(R.id.btn_msg);
btnDel = (ImageButton) view.findViewById(R.id.btn_delete);
}
}
public UsersAdapter(Context context, List<Users> usersList) {
mContext = context;
this.usersList = usersList;
}
#Override
public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_row, parent, false);
return new UsersViewHolder(itemView);
}
#Override
public void onBindViewHolder(UsersViewHolder holder, int position) {
Users users = usersList.get(position);
holder.txtUsername.setText(users.getUserName() + " " + users.getUserSurname());
holder.txtCreatedAt.setText(users.getCreatedAt());
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
holder.imgUser.setImageUrl(users.getUserImgPath(), imageLoader);
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return usersList.size();
}
}
AppliersActivity :
public class AppliersActivity extends AppCompatActivity {
private static final String TAG = AppliersActivity.class.getSimpleName();
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog pDialog;
private String uid, api_key, adId;
private List<Users> usersList = new ArrayList<>();
private RecyclerView recyclerView;
private UsersAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appliers);
definitions();
getAppliers();
}
private void definitions() {
adId = getIntent().getStringExtra("adId");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
uid = user.get("uid");
api_key = user.get("api_key");
recyclerView = (RecyclerView) findViewById(R.id.appliers_recycler_view);
mAdapter = new UsersAdapter(getApplicationContext(), usersList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new OnTouchActionListener() {
#Override
public void onLeftSwipe(View view, int position) {
}
#Override
public void onRightSwipe(View view, int position) {
}
#Override
public void onClick(View view, int position) {
String adId = usersList.get(position).getUserId();
}
}));
}
public static interface OnTouchActionListener {
public void onLeftSwipe(View view, int position);
public void onRightSwipe(View view, int position);
public void onClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private OnTouchActionListener mOnTouchActionListener;
private GestureDetectorCompat mGestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, OnTouchActionListener onTouchActionListener) {
mOnTouchActionListener = onTouchActionListener;
mGestureDetector = new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchActionListener != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchActionListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
private void getAppliers() {
// Tag used to cancel the request
String tag_string_req = "req_appliers";
pDialog.setMessage("Lütfen Bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.GET,
ApiRoutes.URL_JOB_APPLIERS+ "/" + adId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Appliers Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
usersList.clear();
mAdapter.notifyDataSetChanged();
JSONArray usersArray = jObj.getJSONArray("appliers");
Users users;
for (int i = 0; i < usersArray.length(); i++) {
JSONObject jsonobject = usersArray.getJSONObject(i);
users = new Users(jsonobject.getString("uid"), jsonobject.getString("name"), jsonobject.getString("surname"), ApiRoutes.FOLDER_IMG + "/" + jsonobject.getString("uid") + "/profile_img.png", jsonobject.getString("created_at"));
usersList.add(users);
}
mAdapter.notifyDataSetChanged();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "User Ads Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", api_key);
return headers;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I have two imagebutton on recyclerviewer' s rows. I want to add click event for each row. I sent the applicationcontext to an adapter from activity. And i added to onclicklistener event in adapter class. But it does not show toast on the screen. How can i solve this problem ?
You don't call show() method of Toast in your adapter class.
Change it as following
holder.btnMsg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Clicked", Toast.LENGTH_SHORT).show();
}
});
I'm working on an amusement park record information in which I have made a recyclerview that loads data from a MySQL database. Recyclerview is contained in a Fragment. Following is my mainactivity code:
public class TicketSoldFragment extends Fragment {
Button press;
String url="http://10.0.2.2/data/ticketsold_show_swing.php";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_ticketsold,container,false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final RecyclerView rv=(RecyclerView)view.findViewById(R.id.recyclerview_ticketsold);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.setItemAnimator(new DefaultItemAnimator());
Context c=getActivity().getApplicationContext();
press=(Button)view.findViewById(R.id.buttonplease);
press.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Downloader d=new Downloader(getActivity().getApplicationContext(),url,rv);
d.execute();
}
});
}
}
This is my Downloader Code:
public class Downloader extends AsyncTask<Void,Integer,String> {
Context c;
String stringURL;
RecyclerView rv;
ProgressDialog pd;
public Downloader(Context c, String stringURL, RecyclerView rv) {
this.c= c;
this.stringURL = stringURL;
this.rv = rv;
}
#Override
protected String doInBackground(Void... params) {
String data=this.downloadData();
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
pd.dismiss();
if(data!=null) {
Parser p=new Parser(c,data,rv);
p.execute();
}
else {
Toast.makeText(c,"Unable to download",Toast.LENGTH_SHORT).show();
}
}
private String downloadData() {
InputStream is=null;
String line=null;
try {
URL url=new URL(stringURL);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
if(br!=null) {
while((line=br.readLine())!=null) {
sb.append(line+"\n");
}
}
else {
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Download Data");
pd.setMessage("Downloading...Please Wait!");
pd.show();
}
}
This is my Parser:
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
String data;
RecyclerView rv;
ProgressDialog pd;
ArrayList<String> swings=new ArrayList<>();
MyAdapter adapter;
public Parser(Context c, String data, RecyclerView rv) {
this.c = c;
this.data = data;
this.rv = rv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse Data");
pd.setMessage("Parsing...Please wait!");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
pd.dismiss();
if(integer==1) {
adapter=new MyAdapter(c,swings);
rv.setAdapter(adapter );
}
else {
Toast.makeText(c,"Unable to parse data",Toast.LENGTH_SHORT).show();
}
}
private int parse() {
try {
JSONArray ja=new JSONArray(data);
JSONObject jo=null;
swings.clear();
for(int i=0;i<ja.length();i++) {
jo=ja.getJSONObject(i);
String name=jo.getString("name");
swings.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
now problem is when im sending Fragment context from TicketSoldFragment to Downloader constructor, there is an error and i cant figure it out.
this is my Adapter:
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<String> swings;
public MyAdapter(Context c,ArrayList<String>swings){
this.c=c;
this.swings=swings;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_ticketsold,parent,false);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.nameTxt.setText(swings.get(position));
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
Toast.makeText(c,swings.get(pos),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return swings.size();
}
}
and my holder:
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTxt;
ItemClickListener itemClickListener;
public MyHolder(View itemView) {
super(itemView);
nameTxt= (TextView) itemView.findViewById(R.id.swing_name_ticket_sold_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(getLayoutPosition());
}
}
without knowing the error you get I can assume it is related to the getApplicationContext() - getActivity() is the right context, so it should be
Downloader d = new Downloader(getActivity(), url, rv);
The Application Context can be used for Data Access but not for UI and you are doing this in your code.
I'm working on an amusement park record application that receives data from MySQL database and displays on recyclerview in android but im unable to download it from database.
This is my Adapter
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
ArrayList<String> swing;
public MyAdapter(Context c,ArrayList<String>swing){
this.c=c;
this.swing=swing;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_ticketsold,parent,false);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.nameTxt.setText(swing.get(position));
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(int pos) {
Toast.makeText(c,swing.get(pos),Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return swing.size();
}
}
this is my holder:
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTxt;
ItemClickListener itemClickListener;
public MyHolder(View itemView) {
super(itemView);
nameTxt= (TextView) itemView.findViewById(R.id.swing_name_ticket_sold_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener ic)
{
this.itemClickListener=ic;
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(getLayoutPosition());
}
}
This is the fragment containing the recyclerview:
public class TicketSoldFragment extends Fragment {
Button press;
String url="http:// 10.0.2.2/data/ticketsold_show_swing.php";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_ticketsold,container,false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final RecyclerView rv=(RecyclerView)view.findViewById(R.id.recyclerview_ticketsold);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.setItemAnimator(new DefaultItemAnimator());
Context c=getActivity().getApplicationContext();
press=(Button)view.findViewById(R.id.buttonplease);
press.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Downloader d=new Downloader(getActivity(),url,rv);
d.execute();
}
});
}
}
this is downloader:
public class Downloader extends AsyncTask<Void,Integer,String> {
Context c;
String stringURL;
RecyclerView rv;
ProgressDialog pd;
public Downloader(Context c, String stringURL, RecyclerView rv) {
this.c= c;
this.stringURL = stringURL;
this.rv = rv;
}
#Override
protected String doInBackground(Void... params) {
String data=this.downloadData();
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
pd.dismiss();
if(data!=null)
{
Parser p=new Parser(c,data,rv);
p.execute();
}
else {
Toast.makeText(c,"Unable to download",Toast.LENGTH_SHORT).show();
}
}
private String downloadData()
{
InputStream is=null;
String line=null;
try
{
URL url=new URL(stringURL);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is=new BufferedInputStream(con.getInputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
if(br!=null)
{
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
}
else {
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(is!=null)
{
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Download Data");
pd.setMessage("Downloading...Please Wait!");
pd.show();
}
}
and Parser:
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
String data;
RecyclerView rv;
ProgressDialog pd;
ArrayList<String> swings=new ArrayList<>();
MyAdapter adapter;
public Parser(Context c, String data, RecyclerView rv) {
this.c = c;
this.data = data;
this.rv = rv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Parse Data");
pd.setMessage("Parsing...Please wait!");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
pd.dismiss();
if(integer==1)
{
adapter=new MyAdapter(c,swings);
rv.setAdapter(adapter );
}
else
{
Toast.makeText(c,"Unable to parse data",Toast.LENGTH_SHORT).show();
}
}
private int parse()
{
try{
JSONArray ja=new JSONArray(data);
JSONObject jo=null;
swings.clear();
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String name=jo.getString("name");
swings.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
when i run this, the Toast "Unable to download" appears...so my data is not downloaded at all! and there is an error in logcat "no network" and sendUserActionEvent() mView == null
From a JSON array that I am parsing, I want to send a particular object value (using intent putExtra) to another activity. I have read this this question
and the accepted answer but I don't want to send all the values, in my case I only want to send the news_id as an integer to NewsDetails.class.
And I tried using the accepted answer to do it but I got stuck.
MainActivity
public class MainActivity extends AppCompatActivity{
private final String TAG = "MainActivity";
//Creating a list of newss
private List<NewsItems> mNewsItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.news_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the newslist
mNewsItemsList = new ArrayList<>();
adapter = new NewsAdapter(mNewsItemsList, this);
recyclerView.setAdapter(adapter);
//Caling method to get data
getData();
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_news));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigNews.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
NewsItems newsItem = new NewsItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
newsItem.setNews_title(jsonObject.getString(ConfigNews.TAG_NEWS_TITLE));
newsItem.setNews_excerpt(jsonObject.getString(ConfigNews.TAG_NEWS_EXCERPT));
newsItem.setNewsId(jsonObject.getInt(ConfigNews.TAG_NEWS_ID));
} catch (JSONException w) {
w.printStackTrace();
}
mNewsItemsList.add(newsItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
}
NewsItems class
public class NewsItems {
private String news_title;
private String news_excerpt;
private int news_id;
public String getNews_title() {
return news_title;
}
public void setNews_title(String news_title) {
this.news_title = news_title;
}
public String getNews_excerpt() {
return news_excerpt;
}
public void setNews_excerpt(String news_excerpt) {
this.news_excerpt = news_excerpt;
}
public int getNews_id() {
return news_id;
}
public void setNews_id(int news_id) {
this.news_id = news_id;
}
}
NewsAdapter
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private ImageLoader imageLoader;
private Context mContext;
//List of newss
private List<NewsItems> mNewsItems;
private final int VIEW_ITEM = 0;
private final int VIEW_PROG = 1;
private int lastPosition = -1;
public NewsAdapter(List<NewsItems> newsItems, Context context) {
super();
//Getting all newss
this.mNewsItems = newsItems;
this.mContext = context;
}
#Override
public int getItemViewType(int position) {
if (isPositionItem(position))
return VIEW_ITEM;
return VIEW_PROG;
}
private boolean isPositionItem(int position) {
return position != getItemCount()-1;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
if (viewType == VIEW_ITEM) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_summ, parent, false);
return new TextViewHolder(v, mContext);
} else if (viewType == VIEW_PROG){
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recyclerfooter, parent, false);
return new ProgressViewHolder(v);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
#Override
public int getItemCount(){
//Return the number of items in the data set
return mNewsItems.size();
}
public static class TextViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView newsTitle,newsExcerpt, newsId;
public ImageButton imageButton;
public NewsItems dNewsItems;
private Context context;
public TextViewHolder (final View newsView, final Context context) {
super(newsView);
this.context = context;
newsTitle = (TextView) newsView.findViewById(R.id.news_title);
newsExcerpt = (TextView) newsView.findViewById(R.id.news_excerpt);
newsId = (TextView) newsView.findViewById(R.id.news_id);
newsExcerpt.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
Bundle bundle = new Bundle();
bundle.putSerializable("PostId", //This is where I got confused);
}
}
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
Button loadButton;
ProgressBar progressBar;
public ProgressViewHolder(View footerView){
super(footerView);
loadButton = (Button) footerView.findViewById(R.id.reload_button);
progressBar = (ProgressBar) footerView.findViewById(R.id.progress_load);
loadButton.setOnClickListener(this);
if(NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
progressBar.setVisibility(View.VISIBLE);
} else if (!NetworkCheck.isAvailableAndConnected(footerView.getContext())) {
loadButton.setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
if (v.getId() == loadButton.getId()) {
//
}
}
}
}
You can send single value also instead of complete object like this -
#Override
public void onClick(View v) {
if (v.getId() == newsExcerpt.getId()) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",<your_news_id_here>);
startActivity(intent);
}
}
}
In your case, remove onClick(View v) and change your onBindViewHolder() to setOnClickListener() on newsExcerpt like this -
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof TextViewHolder) {
NewsItems newsList = mNewsItems.get(position);
((TextViewHolder) holder).newsTitle.setText(newsList.getNews_title());
((TextViewHolder) holder).newsExcerpt.setText(newsList.getNews_excerpt());
((TextViewHolder) holder).newsId.setText(String.valueOf(newsList.getNewsId()));
((TextViewHolder) holder).newsExcerpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, NewsDetails.class);
intent.putExtra("PostId",newsList.getNewsId()); //Any getter of your class you want
startActivity(intent);
});
} else {
((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
((ProgressViewHolder) holder).loadButton.setText(R.string.reload);
}
}
I don't want to send all the values
You dont' have to send all, It's up to you and your needs.
Intent i = new Intent(context, DestActivity.class);
i.putExtra(KEY_NEWS_ID, news_id );
On the other end:
int news_id = getIntent().getIntExtra(KEY_NEWS_ID, defaultValue);
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)
I want to implement search query in Json Api, the problem is that the I am getting a null exception . I do not know why the filteredArray is returning null, I really do not know where is the problem, Please help me solve this issue.