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
Related
This question already has answers here:
recyclerview No adapter attached; skipping layout
(38 answers)
Closed 2 years ago.
i'm building an application that connects to my Drupal API. Somehow i'm not getting any data display within my application. I don't see any errors in the code and the debugging online gives the follow error: E/RecyclerView: No adapter attached; skipping layout
Here is my MainActivity code:
package com.example.eindopdrachtcmsapi;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity implements ExampleAdapter.onItemClickListener {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_BODY = "body";
public static final String EXTRA_LINK = "link";
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://vistudio.be/api/portfolio";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject portfolio = response.getJSONObject(i);
String title = portfolio.getString("title");
String body = portfolio.getString("body");
String link = portfolio.getString("field_website_url");
mExampleList.add(new ExampleItem(title, body, link));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this, DetailActivity.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_TITLE, clickedItem.getTitle());
detailIntent.putExtra(EXTRA_BODY, clickedItem.getBody());
detailIntent.putExtra(EXTRA_LINK, clickedItem.getLink());
mExampleAdapter.setOnClickListener(MainActivity.this, new ExampleAdapter.onItemClickListener() {
#Override
public void onItemClick(int position) {
ExampleItem clickedItem = mExampleList.get(position);
String title = clickedItem.getTitle();
String Link = clickedItem.getLink();
Intent mSharingIntent = new Intent(Intent.ACTION_SEND);
mSharingIntent.setType("text/plain");
mSharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Vistudio");
mSharingIntent.putExtra(Intent.EXTRA_TEXT, title + " - "+ Link);
startActivity(Intent.createChooser(mSharingIntent, "Share"));
}
});
startActivity(detailIntent);
}
}
My Adapter code:
package com.example.eindopdrachtcmsapi;
import android.content.Context;
import android.graphics.PorterDuffColorFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.portfolioViewHolder>{
private Context mContext;
private ArrayList<ExampleItem> mExampleList;
private onItemClickListener mListener;
private onItemClickListener mListenerShare;
public interface onItemClickListener{
void onItemClick(int position);
}
public void setOnClickListener(onItemClickListener listener, onItemClickListener listenerShare){
mListener = listener;
mListenerShare = listenerShare;
}
public ExampleAdapter(Context context, ArrayList<ExampleItem> ExampleList) {
mContext = context;
mExampleList = ExampleList;
}
#Override
public portfolioViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.exampleitem, parent, false);
return new portfolioViewHolder(v);
}
#Override
public void onBindViewHolder(portfolioViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
String title = currentItem.getTitle();
String body = currentItem.getBody();
String link = currentItem.getLink();
holder.mTextViewTitle.setText(title);
holder.mTextViewBody.setText(body);
holder.mTextViewLink.setText(link);
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class portfolioViewHolder extends RecyclerView.ViewHolder{
public TextView mTextViewTitle;
public TextView mTextViewBody;
public TextView mTextViewLink;
public Button mButton;
public portfolioViewHolder(View itemView) {
super(itemView);
mTextViewTitle = itemView.findViewById(R.id.text_view_title);
mTextViewBody = itemView.findViewById(R.id.text_view_body);
mTextViewLink = itemView.findViewById(R.id.text_view_link);
mButton = itemView.findViewById(R.id.share);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListenerShare != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListenerShare.onItemClick(position);
}
}
}
});
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
});
}
}
}
first remove inside oncreate()
mRecyclerView.setAdapter(mExampleAdapter);
after this code
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
add this:-
mExampleAdapter.notifyDataSetChanged();
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();
}
}
Currently, I'm developing a media player, and I want hide a element when audio finishes. But when it happens, the app crash with this error: Attempt to invoke virtual method 'void android.widget.LinearLayout.setVisibility(int)' on a null object reference. Check my current code:
meplayer.java
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public LinearLayout menu_dialog;
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
RecyclerViewAdapter
package etes.xddda.music;
import android.app.Dialog;
import android.content.Context;
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;
meplayer media;
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);
media = new meplayer();
media.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);
}
}
}
fragmentList
package etes.xddda.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 ;
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(getContext(), 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);
}
}
MainActivity
package etes.xddda.music;
import android.annotation.SuppressLint;
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;
#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();
}
}
}
mList
package etes.xddda.music;
public class mList {
private String Name;
private String Author;
private String URL;
private int Photo;
public mList() {
}
public mList(String name, String phone, String url, int photo) {
Name = name;
Author = phone;
URL = url;
Photo = photo;
}
//Get User
public String getName() {
return Name;
}
public String getPhone() {
return Author;
}
public String getURL() {
return URL;
}
public int getPhoto() {
return Photo;
}
//Setter
public void setName(String name) {
Name = name;
}
public void setPhone(String phone) {
Author = phone;
}
public void setURL(String url) {
URL = url;
}
public void setPhoto(int photo) {
Photo = photo;
}
}
There are no errors in this script, the app just crash when audio finishes. The problem is related to line menu_dialog.setVisibility(View.GONE); and I have already defined menu_dialog in onCreate. So, can you help me?
P.S.: menu_dialog belongs to activity_main.xml
Thank you!
Remove the local variable menu_dialog that you have defined inside the OnCompletionListener:
package etes.xddda.music;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class meplayer extends Activity {
public static MediaPlayer mediaPlayer;
public LinearLayout menu_dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_dialog = findViewById(R.id.menu_dialog);
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//public LinearLayout menu_dialog; REMOVE THIS
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
menu_dialog.setVisibility(View.GONE);
}
});
mediaPlayer.start();
}
private void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I tried everything possible but couldn't try to figure out how to update images to glide whenever my json is updated
MY android app initally loads images from json using glide for firsttime after that it only load images from cache.It doesnot load images that are updated on server till i delete the app and reinstall it
I tried using diskCacheStrategy(DiskCacheStrategy.NONE) and .skipMemoryCache(true) but nothing happened
Glide.with(mContext).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.thumbnail);
This is my code GalleryAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import com.bumptech.glide.signature.StringSignature;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.model.Image;
/**
* Created by Sagunesh on 31/03/16.
*/
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
private List<Image> images;
private Context mContext;
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
}
}
public GalleryAdapter(Context context, List<Image> images) {
mContext = context;
this.images = images;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gallery_thumbnail, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.thumbnail);
}
#Override
public int getItemCount() {
return images.size();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private GalleryAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GalleryAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Here is the code of MainActivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.adapter.GalleryAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdView;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
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.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.android.gms.ads.AdRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.dailysolutions.sn.app.AppController;
import com.dailysolutions.sn.model.Image;
import com.google.android.gms.ads.InterstitialAd;
import java.util.ArrayList;
public class MainActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "https://www.freesabkuch.com/api_mehndi/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;
private AdView mAdView;
InterstitialAd interstitial;
// Our created menu to use
private Menu mymenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
checkConnectivity();
//advertisement
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function
displayInterstitial();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public void onResume() {
// Start or resume the game.
super.onResume();
displayInterstitial();
}
#Override
public void onStart() {
super.onStart();
displayInterstitial();
}
private void fetchImages() {
pDialog.setMessage("Downloading....");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
image.setName(object.getString("name"));
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTimestamp(object.getString("timestamp"));
images.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
#Override
public void onBackPressed() {
exit();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.home:
Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.share:
Toast.makeText(getApplicationContext(),"Share",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch(Exception e) {
//e.toString();
}
case R.id.trash:
Toast.makeText(getApplicationContext(),"Drawer Closed",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.logout:
exit();
}
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
tv_email.setText("Daily Solutions");
drawerLayout = (DrawerLayout)findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
private void checkConnectivity(){
if(ConnectionHelper.isConnectedOrConnecting(getApplicationContext())) {
hideErrorsBar(true);
}else {
//hideErrorsBar(false);
Intent Intent = new Intent(MainActivity.this,NoInternet.class);
startActivity(Intent);
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Add our menu
getMenuInflater().inflate(R.menu.menu_main, menu);
// We should save our menu so we can use it to reset our updater.
mymenu = menu;
//
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
// Do animation start
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
item.setActionView(iv);
new UpdateTask(this).execute();
return true;
}
return super.onOptionsItemSelected(item);
}
public void resetUpdating()
{
// Get our refresh item from the menu
MenuItem m = mymenu.findItem(R.id.action_refresh);
if(m.getActionView()!=null)
{
// Remove the animation.
m.getActionView().clearAnimation();
m.setActionView(null);
}
}
}
You can use Signature for invalidating cache and load image from network. Try
Glide.with(Fragment/context)
.load(imagePath)
.signature(new StringSignature(yourVersion))
.into(ImageView);
Just pass new StringSignature(System.currentTimeMillis()+"") to the signature so that it will load the image from network every time
You could also try setting Signatures
As per the glide documentation on caching
Try this
Glide.with(context)
.load(url) .
signature(new StringSignature(System.currentTimeMillis()))
.into(imageView);
Check here for more details
Well everyone thanks a lot for help :)
I resolved this problem by disabling cache of volley library that was causing the issue but anyway thanks for help :)
//disabling caching for url
AppController.getInstance().getRequestQueue().getCache().remove(url);
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