I created a listView which is updated on click on item in Reycleview within same page.
Date fetch is working,json data is getting and updated in adpater,but new items is extended with previous data in listview
Layout
First row is RecycleView and Below is Listview, Listview should be update when click on item above in recycleview
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sharanjit.fitness.R;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
public class AllExercise extends AppCompatActivity {
ListView list;
ProgressDialog dialog;
Context context;
GetJSONData getJSONData;
String[] name = {"Abdominals","Arms","Back","Chest","Shoulders","Legs","Cardio"};
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
AllExerciseAdapter adapter;
ArrayList<Exercise> arrayList;
boolean first=true;
int pos=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allexercises);
dialog=new ProgressDialog(this);
context=getApplicationContext();
getJSONData=new GetJSONData();
arrayList=new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter();
mRecyclerView.setAdapter(mAdapter);
new FetchData().execute();
list = (ListView) findViewById(R.id.exercise_list);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(AllExercise.this,ExerciseView.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==16908332)
{
finish();
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(View v) {
super(v);
imageView = (ImageView)v.findViewById(R.id.imageView11);
}
}
public MyAdapter() {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.exercise_item, parent, false);
final ViewHolder vh = new ViewHolder(v);
vh.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pos=vh.getAdapterPosition();
first=false;
new FetchData().execute();
}
});
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ViewHolder viewHolder=holder;
viewHolder.imageView.setImageResource(Constants.exercise_images[position]);
}
#Override
public int getItemCount() {
return 7;
}
}
public class AllExerciseAdapter extends ArrayAdapter {
final private Context cx;
final private int pos;
AllExerciseAdapter(Context cx,int pos) {
super(cx, R.layout.allexercise_list_item, arrayList);
this.cx = cx;
this.pos=pos;
}
#Override
public View getView(int position, View vw, ViewGroup group) {
vw = View.inflate(cx, R.layout.allexercise_list_item, null);
ImageView imageView=(ImageView)vw.findViewById(R.id.imageView11);
TextView title=(TextView)vw.findViewById(R.id.textView14);
TextView cat=(TextView)vw.findViewById(R.id.textView13);
title.setText(arrayList.get(position).names);
cat.setText(arrayList.get(position).category);
if(position==0)
Log.e("MS",title.getText().toString());
return vw;
}
}
private class FetchData extends AsyncTask<String,String,String>
{
String url="";
String data="";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("In Progress...");
dialog.setCancelable(false);
dialog.show();
url="http://www.searchdata.in/fitness/get-exercises.php";
try {
data = URLEncoder.encode("category", "UTF-8") + "=" + URLEncoder.encode(name[pos], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
String s= getJSONData.getData(url,data);
return s;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}
}
}
private class Exercise
{
public String names;
public String decription;
public String category;
public String imagePath;
}
}
Just Change your onPostExecute method by below code.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
arrayList=new ArrayList<>();
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
list.setAdapter(adapter);
/*if(!first)
{
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}*/
}
You need to make a small change in your code -
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged(); // No needed to do for first time
}
else {
list.setAdapter(adapter); // Need to call only once.
adapter.notifyDataSetChanged();// Here you need to call it to reflect changes
}
One more change you need to do in onPostExecute -
try {
JSONArray array=new JSONArray(s);
arraList.clear(); //Add this line
for(int i=0;i<array.length();i++)
Hope it will help :)
This Line Is working for the code:-
adapter = new AllExerciseAdapter(context,arrayList);
adapter.setNotifyOnChange(true); // <-----
list.setAdapter(adapter);
Related
So far I can't find an article that explains how to handle scraping infinite scrolling page in Android Studio's Java. Maybe I'm not good at searching or else.
I'm doing a news app project that will display news using web scraping technique, and can also fetch data from the next page.
More on here : How to crawl a website with multiple pages using java
But, now I'm facing a new problem because one of my news source using infinite scrolling method for their site -> https://www.gameinformer.com/news
So, is there any way I can fetch the news data from this website's load more button ?
In case anyone need my code, here it is :
GameInformer's main activity :
package com.example.user.newsapp;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
public class News_GameInformer extends AppCompatActivity {
Toolbar toolbar;
private ProgressDialog mProgressDialog;
private String url = "https://www.gameinformer.com/news";
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private CardView cardView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news__game_informer);
new Description().execute();
toolbar = findViewById(R.id.toolbar_news_gameinformer);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private class Description extends AsyncTask<Void,Void,Void> {
String desc;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(News_GameInformer.this);
mProgressDialog.setTitle("Connecting to GameInformer.com");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document mNewsDocument = Jsoup.connect(url).get();
Elements mElementDataSize = mNewsDocument.select("article[class=node teaser node--type-article node--promoted node--view-mode-teaser]");
int mElementSize = mElementDataSize.size();
for (int i=0;i<mElementSize;i++) {
Elements mElementNewsTitle = mNewsDocument.select("h2[class=page-title]").select("span").eq(i);
String mNewsTitle = mElementNewsTitle.text();
Elements mElementNewsDesc = mNewsDocument.select("div[class=field field--name-field-promo-summary field--type-string field--label-hidden field__item]").eq(i);
String mNewsDesc = mElementNewsDesc.text();
Elements mElementNewsDate = mNewsDocument.select("div[class=node__submitted author-details]").select("span[class=field field--name-created field--type-created field--label-hidden]").eq(i);
String mNewsDate = mElementNewsDate.text();
mNewsTitleList.add(mNewsTitle);
mNewsDescList.add(mNewsDesc);
mNewsDateList.add(mNewsDate);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
RecyclerView mRecyclerView = findViewById(R.id.act_recyclerview_gi_news);
gameinformer_DataAdapter mDataAdapter = new gameinformer_DataAdapter(News_GameInformer.this, mNewsTitleList, mNewsDescList, mNewsDateList, cardView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mDataAdapter);
mProgressDialog.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.gamezone) {
Intent i = new Intent(getApplicationContext(),News_GameZone.class);
startActivity(i);
} else if (id==R.id.gameinformer) {
Intent i = new Intent(getApplicationContext(),News_GameInformer.class);
startActivity(i);
} else if (id==R.id.gamespot) {
Intent i = new Intent(getApplicationContext(),News_GameSpot.class);
startActivity(i);
} else if (id==R.id.pcgamer) {
Intent i = new Intent(getApplicationContext(),News_PCGamer.class);
startActivity(i);
} else if (id==android.R.id.home) {
finish();
} else if (id==R.id.menuinfo) {
Intent i = new Intent(getApplicationContext(),Info.class);
startActivity(i);
} else if (id==R.id.menupeople) {
Intent i = new Intent(getApplicationContext(),People.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Data Adapter's code :
package com.example.user.newsapp;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class gameinformer_DataAdapter extends RecyclerView.Adapter<gameinformer_DataAdapter.MyViewHolder> {
private ArrayList<String> mNewsTitleList = new ArrayList<>();
private ArrayList<String> mNewsDescList = new ArrayList<>();
private ArrayList<String> mNewsDateList = new ArrayList<>();
private Activity mActivity;
private int lastPosition=-1;
private CardView cardView;
public gameinformer_DataAdapter (News_GameInformer activity, ArrayList<String> mNewsTitleList, ArrayList<String> mNewsDescList, ArrayList<String> mNewsDateList, CardView cardView) {
this.mActivity = activity;
this.mNewsTitleList = mNewsTitleList;
this.mNewsDescList = mNewsDescList;
this.mNewsDateList = mNewsDateList;
this.cardView = cardView;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView gameinformer_news_title, gameinformer_news_desc, gameinformer_news_date;
private CardView cardView_layout;
public MyViewHolder(View view) {
super(view);
gameinformer_news_title = view.findViewById(R.id.row_gi_news_title);
gameinformer_news_desc = view.findViewById(R.id.row_gi_news_desc);
gameinformer_news_date = view.findViewById(R.id.row_gi_news_date);
cardView_layout = view.findViewById(R.id.gi_cardview);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gameinformer_row_data,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.gameinformer_news_title.setText(mNewsTitleList.get(position));
holder.gameinformer_news_desc.setText(mNewsDescList.get(position));
holder.gameinformer_news_date.setText(mNewsDateList.get(position));
holder.cardView_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String title = mNewsTitleList.get(position);
Intent i = new Intent(mActivity, News_GameInformer_Webview.class);
i.putExtra("keytitle",title);
mActivity.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mNewsTitleList.size();
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm spending the last 5 days trying solve this problem. I really do not have any idea about how to solve it. I'm getting Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference. Check my code:
RecyclerView.java
package etes.xdda.music;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
Context mContext;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(Context mContext, List<mList> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void onClick(View view) {
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(mContext).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(mContext);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = (TextView) myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = (TextView) myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = (ImageView) myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private TextView tv_url;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = (TextView) itemView.findViewById(R.id.name_list);
tv_author = (TextView) itemView.findViewById(R.id.author_list);
img = (ImageView) itemView.findViewById(R.id.img_contact);
}
}
}
Note that I'm invoking MainActivity.java in this part:
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
MainActivity a = new MainActivity();
a.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
MainActivity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
And here's my MainActivity.java
package etes.xdda.music;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
private String player_status = "playing";
private ImageButton player_img;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
meplayer.pauseAudio();
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
meplayer.startAudio();
player_status = "playing";
}
}
});
//menu_dialog.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0,0,0,0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
updateLayout();
}
});
mediaPlayer.start();
}
private static void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
And the part of code that is giving crash is this:
private void updateLayout() {
try {
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
#edit: I have added this piece of code, I don't know if can help
fragmentList.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "https://pastebin.com/raw/fG3zd40U";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
MainActivity activity;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = (RecyclerView) v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(activity, lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
Please, help me, I have no more ideas about what I should do. Thank you
Just taking a look at your code, it looks like you are doing many things wrong. Such as this line
MainActivity a = new MainActivity();
You can't instantiate lifecycle components like Services, Activities, Fragments etc this way. Android provides you these components when you call start methods etc. The activity that is created as a result of the above line doesn't go through the lifecycle calls that an activity that is started via using startActivity. As a result, the setContentView of the activity is never called and you get this error. You have to remove this line and implement this properly and the error will go away.
Also just to add, you are actually creating a new instance of the activity when one is already running when you need to call the methods on the old instance that was started.
Edit: Try like this.
MainActivity activity;
List<mList> mData;
Dialog myDialog;
private MediaPlayer mediaPlayer;
private int playbackPosition=0;
private LinearLayout menu_dialog;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
And then
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,100);
}
});
Also remove static from the main activity functions
I'm working on an employee attendance attendance applicaion, for that I'm listing employee namelist from my MySQL database to android RecyclerView. Everything is working fine. But what I actually wanted is, I want to update my attendance table with the CheckBox values, my table contains 3 columns id,emp_id,emp_attn, If the checkbox is checked for an employee, the app should post it as checked ! So how can i identify each checkbox in my recyclerview,
MyAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Created by Akshay N Shaju on 10/20/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private List<Listitems> listitemses;
private Context context;
public MyAdapter(List<Listitems> listitemses, Context context) {
this.listitemses = listitemses;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Listitems listitem = listitemses.get(position);
holder.CbHead.setText(listitem.getHead());
holder.textViewDesc.setText(listitem.getDesc());
holder.CbHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,listitem.getHead(), Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return listitemses.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public CheckBox CbHead;
public TextView textViewDesc;
public LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
CbHead = (CheckBox) itemView.findViewById(R.id.CbHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDisc);
linearLayout = (LinearLayout) itemView.findViewById(R.id.LinearLyout1);
}
}
}
MainActivity.java
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "https://xxxxxxx.com/sample.json";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<Listitems> listitemses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listitemses = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("employee");
for(int i=0; i<array.length(); i++){
JSONObject o = array.getJSONObject(i);
Listitems item = new Listitems(
o.getString("name"),
o.getString("id"),
o.getString("image")
);
listitemses.add(item);
}
adapter = new MyAdapter(listitemses,getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
ListItems.java
/**
* Created by Akshay N Shaju on 10/20/2017.
*/
public class Listitems {
private String head;
private String desc;
private String imageurl;
public Listitems(String head, String desc, String imageurl) {
this.head = head;
this.desc = desc;
this.imageurl = imageurl;
}
public String getHead() {
return head;
}
public String getDesc() {
return desc;
}
public String getImageurl() {
return imageurl;
}
}
Here in my adapter I tried an onClick Listner, which toast the employee name when checked and it worked ! but how can I get all the checkbox status and post it to my database table when save button clicked.
Store the state in your ListItem, whenever the state of the CheckBox changes:
public class Listitems {
...
public bool isChecked;
...
}
Instead of onClick, listen to the state change instead:
holder.CbHead.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listitem.isChecked = isChecked
}
});
Finally when binding, make sure to reflect the checked state of the CheckBox:
holder.CbHead.setText(listitem.getHead());
holder.CbHead.setChecked(listitem.isChecked)
You are using a recycler view so while the CheckBox is still on screen it will hold your "checked" state. However once it scrolls off screen, it will be recycled. Hence you need to store the state somewhere, your own ListItem is the best bet
i am working of live search with MySQL, JSON. its working fine with local array values. but not working with MySQL. my concern is when user start typing it has to search from data base and show it in listview. bellow is my Adapter for search
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.R;
import zesteve.com.myapplication.Search;
import zesteve.com.myapplication.VendProfileActivity;
/**
* Created by Ravi Shankar on 6/22/2017.
*/
public class SearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Search> vendersearchlist = null;
private ArrayList<Search> arraylist;
public SearchAdapter(Context context,
List<Search> vendersearchlist) {
mContext = context;
this.vendersearchlist = vendersearchlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Search>();
this.arraylist.addAll(vendersearchlist);
}
public class ViewHolder {
TextView id;
TextView vname;
}
#Override
public int getCount() {
return vendersearchlist.size();
}
#Override
public Search getItem(int position) {
return vendersearchlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.search_item_list, null);
// Locate the TextViews in listview_item.xml
//holder.id = (TextView) view.findViewById(R.id.id);
holder.vname = (TextView) view.findViewById(R.id.autoCompleteTextView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(Search.get(position).getRank());
holder.vname.setText(vendersearchlist.get(position).getVname());
// Listen for ListView Item Click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, VendProfileActivity.class);
// Pass all data rank
intent.putExtra("Vend_Id",
(vendersearchlist.get(position).getId()));
// Pass all data country
intent.putExtra("Vend_Name",
(vendersearchlist.get(position).getVname()));
// Pass all data population
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
vendersearchlist.clear();
if (charText.length() == 0) {
vendersearchlist.addAll(arraylist);
} else {
for (Search sl : arraylist) {
if (sl.getVname().toLowerCase(Locale.getDefault())
.contains(charText)) {
vendersearchlist.add(sl);
}
}
}
notifyDataSetChanged();
}
}
AND POJO
public class Search {
private int id;
private String vname;
public Search(int id, String vname) {
this.id = id;
this.vname = vname;
}
public int getId() {
return this.id;
}
public String getVname() {
return this.vname;
}
}
And my SearchActivity.java
import android.content.res.Resources;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import zesteve.com.myapplication.adapter.SearchAdapter;
import zesteve.com.myapplication.adapter.VenderAdapter;
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
private EditText Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
int[] id;
String[] vname;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
listview = (ListView) findViewById(R.id.listview);
Vendname = (EditText) findViewById(R.id.searchitem);
Vendname.setHint("Search "+catname+" in "+city);
//fetch data from server in json
String vsearch = Vendname.getText().toString();
prepareVender(vsearch);
// Pass results to ListViewAdapter Class
adapter = new SearchAdapter(this, vendersearchlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Locate the EditText in listview_main.xml
Vendname.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = Vendname.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void prepareVender(String sText){
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/vend_list.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object= array.getJSONObject(i);
Search vender = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(vender);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(sText);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Please comment if you have any doubts.
if Somebody looking for same Solution. bellow is my code
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
SearchView Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
ArrayList<Search> filteredSearchResults = new ArrayList<Search>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
progressDialog = new ProgressDialog(Search_vender.this);
progressDialog.setCancelable(false);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
//Toast.makeText(Search_vender.this,catid + city,Toast.LENGTH_LONG).show();
listview = (ListView) findViewById(R.id.listview);
Vendname = (SearchView) findViewById(R.id.searchitem);
Vendname.setQueryHint("Search "+catname+" in "+city);
Vendname.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
//Toast.makeText(Search_vender.this, String.valueOf(hasFocus),Toast.LENGTH_SHORT).show();
}
});
Vendname.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.length() > 2){
listview.setVisibility(View.VISIBLE);
GetDataVender gv = (GetDataVender) new GetDataVender().execute(newText);
}else{
listview.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
public void filterSearchArray(String newText){
String pName;
filteredSearchResults.clear();
for (int i = 0; i < vendersearchlist.size(); i++)
{
pName = vendersearchlist.get(i).getVname().toLowerCase();
if ( pName.contains(newText.toLowerCase()))
{
filteredSearchResults.add(vendersearchlist.get(i));
}
}
}
class GetDataVender extends AsyncTask<String, Void, String>{
String textsearch;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading Please Wait...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/autosearch.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
this.textsearch = strings[0];
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
Search catagory = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(catagory);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equalsIgnoreCase("Exception Caught")){
Toast.makeText(Search_vender.this, "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
hideDialog();
}else{
filterSearchArray(textsearch);
listview.setAdapter(new SearchAdapter(Search_vender.this,filteredSearchResults));
hideDialog();
}
//hideDialog();
//adapter.notifyDataSetChanged();
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
it works when user stat search from second character.
I am using Sugar ORM to implement Data Persistence in my app. I am displaying my database contents in a RecyclerView. The problem is SugarORM doesn't have loaders so there is no way to refresh the RecyclerView with fresh data after adding/deleting an entry to the database. I have worked around the issue for phones by reinitializing my Adapter in OnResume() and displaying it in the Recycler View. But for Tablets, the logic isn't working because the Fragment never goes to OnPause.
I need to update my the RecyclerView in my FavouritesFragment when I remove an entry in my DetailsFragment
Here's the Github link https://github.com/Hackertronix/Project-Motion/tree/Stage_2
Here's the code for both fragments
FavoritesFragment.java
package com.execube.genesis.views.fragments;
import android.app.ActivityOptions;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.utils.API;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Prateek Phoenix on 6/7/2016.
*/
public class FavouritesFragment extends Fragment {
public static final String TAG= "FAVOURITES";
private static final String FAVOURITE_MOVIES_ARRAY = "favourite_movies";
private List<Movie> mMovies=new ArrayList<>();
private RecyclerView mFavouritesRecyclerView;
ArrayList<Movie> moviesArrayList;
private FavouritesAdapter mAdapter;
private TabLayout mTabLayout;
public FavouritesFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreate()");
super.onCreate(savedInstanceState);
}
#Override
public void onPause() {
Log.v(TAG,"OnPause() Called");
super.onPause();
}
#Override
public void onResume() {
/* Sugar ORM does not have a Loader
so to refresh the recyclerview adapter I am reinitializing it*/
Log.v(TAG,"OnResume() Called");
mMovies=Movie.listAll(Movie.class);
mAdapter=new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
super.onResume();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreateView()");
View view = inflater.inflate(R.layout.fragment_favourites,container,false);
mFavouritesRecyclerView=(RecyclerView)view.findViewById(R.id.favourites_recyclerview);
if(savedInstanceState!=null&&savedInstanceState.containsKey(FAVOURITE_MOVIES_ARRAY))
{
Log.v(TAG,"Restoring State");
mMovies=savedInstanceState.getParcelableArrayList(FAVOURITE_MOVIES_ARRAY);
}
else {
mMovies= Movie.listAll(Movie.class);
}
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mFavouritesRecyclerView.setLayoutManager(new
GridLayoutManager(getActivity(), 2));
}
else{
mFavouritesRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
}
mAdapter= new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
return view;
}
private class FavouritesHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private ImageView mPosterImageView;
private Movie mMovie;
public FavouritesHolder(View itemView) {
super(itemView);
mPosterImageView=(ImageView)itemView.findViewById(R.id.poster);
itemView.setOnClickListener(this);
}
public void bind(Movie movie)
{
mMovie=movie;
Picasso mPicasso= Picasso.with(getActivity());
mPicasso.setIndicatorsEnabled(true);
mPicasso.load(API.IMAGE_URL+API.IMAGE_SIZE_500+mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mPosterImageView);
}
#Override
public void onClick(View v) {
ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(getActivity(),mPosterImageView,"posterImage");
((openDetailsListener)getActivity()).openDetails(mMovie,options);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
moviesArrayList=new ArrayList<>(mMovies);
Log.v(TAG,"Saving State");
outState.putParcelableArrayList(FAVOURITE_MOVIES_ARRAY,moviesArrayList);
super.onSaveInstanceState(outState);
}
private class FavouritesAdapter extends RecyclerView.Adapter<FavouritesHolder>
{
#Override
public FavouritesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.movie_item,parent,false);
return new FavouritesHolder(view);
}
#Override
public void onBindViewHolder(FavouritesHolder holder, int position) {
Movie movie= mMovies.get(position);
holder.bind(movie);
}
#Override
public int getItemCount() {
return mMovies.size();
}
}
public interface openDetailsListener{
void openDetails(Movie movie,ActivityOptions options);
}
}
DetailsFragment.java
package com.execube.genesis.views.fragments;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.model.Review;
import com.execube.genesis.model.Trailer;
import com.execube.genesis.utils.API;
import com.execube.genesis.utils.JSONParser;
import com.execube.genesis.utils.OkHttpHandler;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
import static com.execube.genesis.R.drawable.ic_favorite_black_24dp;
/**
* Created by Prateek Phoenix on 4/30/2016.
*/
public class DetailsFragment extends Fragment {
private static final String TAG = "DETAILS";
private static final int DEFAULT_NUM_COLORS = 5;
private Movie mMovie;
private Movie entry,tempMovie;
private List<Movie> movie;
public Intent intent;
private TextView mDetailTitle;
private TextView mReleaseDate;
private TextView mOverview;
private TextView mOverviewHeader;
private TextView mReviesHeader;
private TextView mTrailersHeader;
private ImageView mBackdrop;
private Toolbar mToolbar;
private RatingBar mRatingBar;
private ArrayList<Review> mReviews=new ArrayList<>();
private ArrayList<Trailer> mTrailers=new ArrayList<>();
public static final String MOVIE_REVIEWS_ARRAY ="movie_details";
private static final String MOVIE_TRAILERS_ARRAY = "movie_reviews";
private Typeface fontBold;
private Typeface fontMediumLight;
private Typeface fontMedium;
private RecyclerView mReviewRecyclerView;
private RecyclerView mTrailerRecyclerView;
private ProgressBar mReviewsProgressbar;
private ProgressBar mTrailersProgressbar;
private CoordinatorLayout mCoordinatorLayout;
private CardView mReviewsCardView;
private FloatingActionButton mFloatingActionButton;
private ReviewsAdapter mReviewAdapter;
private int NumOfReviews;
private TrailersAdapter mTrailerAdapter;
private String id;
private boolean isFav;
public DetailsFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.v(TAG,"Saving state in onSaveInstanceState");
outState.putParcelableArrayList(MOVIE_REVIEWS_ARRAY,mReviews);
outState.putParcelableArrayList(MOVIE_TRAILERS_ARRAY,mTrailers);
super.onSaveInstanceState(outState);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
mBackdrop = (ImageView) view.findViewById(R.id.details_poster);
mDetailTitle = (TextView) view.findViewById(R.id.detail_title_text);
mReleaseDate = (TextView) view.findViewById(R.id.release_date);
mOverview = (TextView) view.findViewById(R.id.overview);
mOverviewHeader = (TextView) view.findViewById(R.id.overview_header);
mReviesHeader=(TextView)view.findViewById(R.id.review_header);
mTrailersHeader=(TextView)view.findViewById(R.id.trailer_header);
mRatingBar = (RatingBar) view.findViewById(R.id.movie_rating);
mCoordinatorLayout=(CoordinatorLayout)view.findViewById(R.id.coordinator_layout);
mReviewRecyclerView= (RecyclerView)view.findViewById(R.id.review_recycler_view);
mTrailerRecyclerView=(RecyclerView)view.findViewById(R.id.trailer_recycler_view);
mReviewsProgressbar=(ProgressBar)view.findViewById(R.id.reviews_progressbar);
mTrailersProgressbar=(ProgressBar)view.findViewById(R.id.trailers_progressbar);
mFloatingActionButton=(FloatingActionButton)view.findViewById(R.id.fab);
mReviewsCardView= (CardView) view.findViewById(R.id.reviews_card);
intent = getActivity().getIntent();
Bundle bundle=getArguments();
mMovie=bundle.getParcelable("PARCEL");
tempMovie=mMovie;
id = String.valueOf(mMovie.getMovieId());
checkFav();
mFloatingActionButton.show();
assert mMovie != null;
//PREPPING THE URL FOR QUERY
String reviewQueryUrl = API.MOVIES_BASE_URL + id + "/reviews" + API.API_KEY;
String trailerQueryUrl = API.MOVIES_BASE_URL + id + "/videos" + API.API_KEY;
mDetailTitle.setText(mMovie.getTitle());
mReleaseDate.setText(mMovie.getReleaseDate());
mRatingBar.setProgress((int) mMovie.getVoteAverage());
mOverview.setText(mMovie.getOverview());
if (Build.VERSION.SDK_INT != 21) {
fontBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Bold.ttf");
fontMedium = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Medium.ttf");
fontMediumLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Book_.ttf");
mDetailTitle.setTypeface(fontBold);
mReleaseDate.setTypeface(fontMedium);
mOverview.setTypeface(fontMediumLight);
mOverviewHeader.setTypeface(fontBold);
mReviesHeader.setTypeface(fontBold);
mTrailersHeader.setTypeface(fontBold);
}
//FETCHING JSON HERE
if(savedInstanceState!=null&&savedInstanceState.containsKey(MOVIE_REVIEWS_ARRAY))
{
Log.v(TAG,"Restoring from bundle");
mReviews=savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_ARRAY);
mTrailers=savedInstanceState.getParcelableArrayList(MOVIE_TRAILERS_ARRAY);
mReviewsProgressbar.setVisibility(View.GONE);
mTrailersProgressbar.setVisibility(View.GONE);
}
else {
OkHttpHandler reviewsHandler = new OkHttpHandler(reviewQueryUrl, reviewsCallback);
reviewsHandler.fetchData();
OkHttpHandler trailersHandler= new OkHttpHandler(trailerQueryUrl, trailersCallback);
trailersHandler.fetchData();
}
Picasso.with(getActivity()).load(API.IMAGE_URL + API.IMAGE_SIZE_500 + mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mBackdrop);
getActivity().startPostponedEnterTransition();
mReviewRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mReviewAdapter= new ReviewsAdapter();
mReviewRecyclerView.setAdapter(mReviewAdapter);
LinearLayoutManager layoutmanager= new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
mTrailerRecyclerView.setLayoutManager(layoutmanager);
mTrailerAdapter= new TrailersAdapter();
mTrailerRecyclerView.setAdapter(mTrailerAdapter);
return view;
}
private void checkFav() {
movie=new ArrayList<>();
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()==0)
{
Log.v(TAG,"Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
}
else {
Log.v(TAG,"NOT Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()>0)
{
entry = movie.get(0);
entry.delete();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie removed from Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
else
{
entry = tempMovie;
entry.save();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie added to Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
});
}
//OKHTTP CALLBACK FOR NETWORK CALL
private okhttp3.Callback reviewsCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String JSONData= response.body().string();
JSONObject jsonObject = new JSONObject(JSONData);
NumOfReviews = jsonObject.getInt("total_results");
JSONParser parser = new JSONParser();
Log.v(TAG,JSONData);
mReviews=parser.parseReviews(JSONData);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mReviewAdapter!=null)
{
mReviewsProgressbar.setVisibility(View.GONE);
mReviewAdapter.notifyDataSetChanged();
}
}
});
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (NumOfReviews==0)
{
mReviewsCardView.setVisibility(View.INVISIBLE);
}
}
});
}
};
private okhttp3.Callback trailersCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String json1= response.body().string();
JSONParser parser= new JSONParser();
Log.v(TAG, json1);
mTrailers = parser.parseTrailers(json1);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mTrailerAdapter!=null)
{
mTrailersProgressbar.setVisibility(View.GONE);
mTrailerAdapter.notifyDataSetChanged();
}
}
});
}
};
private class ReviewViewHolder extends RecyclerView.ViewHolder{
private TextView mAuthorText;
private TextView mReviewText;
private Review mReview;
public ReviewViewHolder(View itemView) {
super(itemView);
mAuthorText= (TextView) itemView.findViewById(R.id.author_textview);
mReviewText= (TextView) itemView.findViewById(R.id.review_textview);
}
public void bind(Review review)
{
mReview= review;
mAuthorText.setText(mReview.getAuthor());
mReviewText.setText(mReview.getContent());
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
{
mAuthorText.setTypeface(fontBold);
mReviewText.setTypeface(fontMediumLight);
}
}
}
private class ReviewsAdapter extends RecyclerView.Adapter<ReviewViewHolder>{
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.review_item,parent,false);
return new ReviewViewHolder(view);
}
#Override
public void onBindViewHolder(ReviewViewHolder holder, int position) {
Review review= mReviews.get(position);
holder.bind(review);
}
#Override
public int getItemCount() {
if(mReviews==null)
{ return 0;}
else
{return mReviews.size();}
}
}
private class TrailerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mTrailerThumbnail;
private Trailer mTrailer;
public TrailerViewHolder(View itemView) {
super(itemView);
mTrailerThumbnail=(ImageView)itemView.findViewById(R.id.trailer_thumbnail);
itemView.setOnClickListener(this);
}
public void bind(Trailer trailer)
{
mTrailer=trailer;
Picasso picasso =Picasso.with(getActivity());
picasso.setIndicatorsEnabled(true);
picasso.load(API.YOUTUBE_THUMBNAIL_URL+mTrailer.getKey()+API.THUMBNAIL_QUALITY)
.into(mTrailerThumbnail);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(API.YOUTUBE_TRAILER_URL+mTrailer.getKey()));
startActivity(intent);
}
}
private class TrailersAdapter extends RecyclerView.Adapter<TrailerViewHolder>
{
#Override
public TrailerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.trailer_item,parent,false);
return new TrailerViewHolder(view);
}
#Override
public void onBindViewHolder(TrailerViewHolder holder, int position) {
Trailer trailer= mTrailers.get(position);
holder.bind(trailer);
}
#Override
public int getItemCount() {
return mTrailers.size();
}
}
}
You can use an Interface to communicate between Fragments (Here's a question I asked an year ago and the accepted answer was really easy to understand).
Then, you need to call mAdapter.notifyDataSetChanged() in your callBack method.
I propose one way to solve this.
class TabletActivity extends Activity implements DetailFragment.Callback {
public void onCreate(Bundle savedInstanceState){
//Initialise fragments
}
void onItemDelete(){
// find the Master Fragment using FragmentManager;
MasterFragment f = (MasterFragment) getFragmentManager().findFragmentById();
if (f != null){
f.somethingHasChanged();
}
}
}
class DetailFragment extends Fragment {
private Callback callback;
public onAttach(Context context){
this.callback = (Context) context;
}
public void onViewCreated(View v, Bundle b){
Button b;
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
callback.onItemDelete();
}
)
}
public interface Callback {
void onItemDelete();
}
}
class MasterFragment extends Fragment {
public void somethingHasChanged(){
adapter.notifyDatasetChanged();
}
}
DetailFragment is where we initiate the changes, MasterFragment is consuming the changes. That communication is don't via the Activity. I personally don't recommend notifyAdapterChanges in OnResume() as you proposed because there is no guarantee that onResume will be call right after the changes in you data has been made.
Read more at:
https://developer.android.com/training/basics/fragments/communicating.html