I am using fragment for the first time. I am trying to get List of videos from youtube present in my fragment. I am retrieving a youtube url from firebase and extract playlist id from it. This playlist id is passed as a parameter to fragment which would then list out all the videos present in the playist. i am successfully able to retrieve the playlist id in the fragment, but it changes to null in the url. Any help is appreciable.thanks in advance.
CollegeGallery.java
public CollegeImageGrid imagegrid;
private static final String TAG = "CollegeGallery";
public GridView grid_image, grid_video;
public DatabaseReference ref;
private String collegeid;
private TextView moreimages, morevideos;
private String playlistid;
public void setPlayid(String playlistid) {
this.playlistid = playlistid;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_gallery);
ref = FirebaseDatabase.getInstance().getReference("collegedata");
//this will get the data from previous intent
collegeid = getIntent().getStringExtra("gallery");
grid_image = findViewById(R.id.grid_image);
// grid_video = findViewById(R.id.grid_video); //for grid view of videos
moreimages = findViewById(R.id.more_images);
morevideos = findViewById(R.id.more_videos);
//a list of string will be passed to imagegrid object
ref.child(String.valueOf(collegeid)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//object of College class to get getImageurls() which has the list of urls
College clg = dataSnapshot.getValue(College.class);
//setting the list to imagegrid, passing url from this activity to imageview.
imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
//setting adapter to grid with the list of urls
grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
//extracting playlist id
String playid = getYoutubeVideoId(clg.getVideourls());
//fragment code
YoutubeVideoList yt = new YoutubeVideoList();
FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
tr.replace(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(CollegeGallery.this, "No images", Toast.LENGTH_SHORT).show();
}
});
moreimages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent image_in = new Intent(CollegeGallery.this,AllCollegeImages.class);
image_in.putExtra("image",collegeid);
startActivity(image_in);
}
});
//will take to activity with only playlist video list fragment
morevideos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CollegeGallery.this, CompleteVideoList.class));
}
});
}
//function to extract playlist id
public static String getYoutubeVideoId(String youtubeUrl) {
String video_id = "";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {
String expression = "^.*?(?:list)=(.*?)(?:&|$)";
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String groupIndex1 = matcher.group(1);
video_id = groupIndex1;
}
}
return video_id;
}
}
YoutubeVideoList.java(Fragment)
private static String ARG_Param1;
private static String id;
List<YoutubeVideoModel> vids;
Button btn;
YoutubeAdapter adapter;
RecyclerView recyclerView;
RecyclerView.LayoutManager manager;
String mparam1;
public YoutubeVideoList() {
}
//retrieving playlist id from the previous activity
public static YoutubeVideoList newInstance(String id) {
YoutubeVideoList yt = new YoutubeVideoList();
Bundle args = new Bundle();
args.putString(ARG_Param1, id);
yt.setArguments(args);
return yt;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mparam1 = getArguments().getString(ARG_Param1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_youtube_video_list, container, false);
}
#Override
public void onViewCreated(View container, Bundle savedInstanceState) {
super.onViewCreated(container, savedInstanceState);
recyclerView = container.findViewById(R.id.vidReclycer);
manager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(false);
id = mparam1;
//right here, id has the playlist id
System.out.println("this is the playlist id------------------->"+id);
String url = "https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyBmISPZAjsrku2_yKLcTW4Y6qq6aqlht-0&playlistId="+id+"&part=snippet&maxResults=36";
//even url has the value but the list is not shown and id changes to null
System.out.println(url);
RequestQueue queue = Volley.newRequestQueue(getContext());
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
vids = new ArrayList<>();
try {
JSONObject mainObject = new JSONObject(response);
JSONArray itemArray = (JSONArray) mainObject.get("items");
for (int i = 0; i < itemArray.length(); i++) {
String title = itemArray.getJSONObject(i).getJSONObject("snippet").getString("title");
String url = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("maxres").getString("url");
String vidid = itemArray.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
YoutubeVideoModel vid = new YoutubeVideoModel(title, url, vidid);
vids.add(vid);
}
adapter = new YoutubeAdapter(getContext(), vids);
recyclerView.setAdapter(adapter);
recyclerView.getAdapter().notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.e("Error in request", error.getMessage());
}
});
queue.add(request);
}
}
```this is the image of my logcat. It prints id and url as required, but then it changes to null
Got the answer. there was a problem in sharing data between activity and fragment. the value was being set null twice, one before and one after the function call(i dont know why but). then instead of calling newInstance() i used bundle, checked if it is null or not in fragment class and then set the value of id.
CollgeGallery.java
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//object of College class to get getImageurls() which has the list of urls
College clg = dataSnapshot.getValue(College.class);
String playid = getYoutubeVideoId(clg.getVideourls());
//setting the list to imagegrid, passing url from this activity to imageview.
imagegrid = new CollegeImageGrid(CollegeGallery.this,clg.getImageurls());
//setting adapter to grid with the list of urls
grid_image.setAdapter(imagegrid); //check error, getCount is null, crashes application.
//extracting playlist id
// String playid = getYoutubeVideoId(clg.getVideourls());
//fragment code
setPlayid(playid);
Bundle bun = new Bundle();
YoutubeVideoList firstfrag = new YoutubeVideoList();
bun.putString("test", playid);
firstfrag.setArguments(bun);
getSupportFragmentManager().beginTransaction().add(R.id.youtube_frag, firstfrag).commit();
// FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
// tr.add(R.id.youtube_frag, YoutubeVideoList.newInstance(playid)).commit();
}```
**YoutubeVideoList.java**
```#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = this.getArguments();
if(args != null){
id = args.getString("test");
}
}```
Thanks everyone for your help. :)
In your CollegeGallery.java in place of:
yt.newInstance(playid)
write this
YoutubeVideoList.newInstance(playid)
Also remove the static String id from your YoutubeVideoList fragment if it's useless
Related
I have a mind-boggling problem I can't seem to solve.
The data in my RecyclerView is not updating, and after an entire day of debugging, I can't find the problematic code. The API returns the correct data, and I parse the correct data in a wallItemList which I pass to the Adapter.
How It Should Behave
After changing the language setting to either one of the 2 (English or Dutch), the items in my Recyclerview should update with it and the title of the element should change to the translated string.
What I Have Tried
Creating a refresh function inside the adapter, and update the wallItemList manually by passing the created wallItemList from the MainActivity and calling notifyDataSetChanged()
Calling notifyDataSetChanged() before, in and after the OnClickListener in the MyRecyclerViewAdapter
Setting the item in onBindViewHolder in the MyRecyclerViewAdapter
Strangely enough, when logging the language of the wallItem just before adapter.setOnItemClickListener in populateRecyclerView(), the language is right. But when I get the string from the object in MyRecyclerViewAdapter's onBindViewHolder, it shows the wrong language.
Here is my MainActivity.java:
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private List<WallItem> WallItemList;
private RecyclerView mRecyclerView;
private MyRecyclerViewAdapter adapter;
private ProgressBar progressBar;
// LifeCycle variables
private String JSONResults = "";
final static private String JSON_KEY_RESULTS = "";
final static private String WALL_ITEM_LIST_KEY = "";
// SharedPrefences variables
private String APIUrlPreferenceString = "";
private String langPreferenceString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
// Setup shared preferences
setupSharedPreferences();
// Load the recyclerView
loadRecyclerView(savedInstanceState);
}
private void setLanguageSettings(String lang)
{
//create a string for country
String country = "";
if(lang.equals("en"))
{
country = "EN";
}
else if(lang.equals("nl"))
{
country = "NL";
}
//use constructor with country
Locale locale = new Locale(lang, country);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
private void setupSharedPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
APIUrlPreferenceString = sharedPreferences.getString(getString(R.string.pref_api_url_key), getString(R.string.pref_api_url_def_value));
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
// Language settings
if(sharedPreferences.getBoolean(getString(R.string.pref_lang_check_key), true))
{
// Use device settings
setLanguageSettings(Resources.getSystem().getConfiguration().locale.getLanguage());
langPreferenceString = Resources.getSystem().getConfiguration().locale.getLanguage();
}
else
{
// Use preference settings
setLanguageSettings(sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en)));
langPreferenceString = sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en));
}
}
private void loadRecyclerView(Bundle savedInstanceState)
{
// Lifecycle event to preserve data to prevent repeating API calls
if(savedInstanceState != null && savedInstanceState.containsKey(WALL_ITEM_LIST_KEY) && savedInstanceState.containsKey(JSON_KEY_RESULTS))
{
progressBar.setVisibility(View.GONE);
// Set again in order to preserve state on future rotations
JSONResults = savedInstanceState.getString(JSON_KEY_RESULTS);
// Set wallItemList again in order to preserve state on future rotations
WallItemList = savedInstanceState.getParcelableArrayList(WALL_ITEM_LIST_KEY);
populateRecyclerView();
}
else
{
// First execution
new DownloadTask().execute();
}
}
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean result;
String blindWallResults;
try {
// Error fix, because NetworkUtils.buildUrl returns null when failing
if(null == NetworkUtils.buildUrl(APIUrlPreferenceString))
return false;
// Get response from API
blindWallResults = NetworkUtils.getResponseFromHttpUrl(NetworkUtils.buildUrl(APIUrlPreferenceString));
// Send to parser
JSONResults = blindWallResults;
parseResult(blindWallResults);
result = true;
} catch (IOException e) {
e.printStackTrace();
result = false;
}
// When failed
return result;
}
#Override
protected void onPostExecute(Boolean result) {
progressBar.setVisibility(View.GONE);
// If succeeded
if (result) {
populateRecyclerView();
// Show toast when data has been loaded for the first time
Toast.makeText(MainActivity.this, getString(R.string.json_toast_data_loaded), Toast.LENGTH_SHORT).show();
} else {
// If failed make toast
Toast.makeText(MainActivity.this, getString(R.string.json_toast_data_failed), Toast.LENGTH_SHORT).show();
}
}
}
/**
* Populates recyclerView and adds OnItemClickListener
*/
private void populateRecyclerView()
{
WallItem w = WallItemList.get(0);
adapter = new MyRecyclerViewAdapter(MainActivity.this, WallItemList);
mRecyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(WallItem item) {
// Function to start new activity
Class detailActivity = DetailActivity.class;
// Create intent
Intent startDetailActivityIntent = new Intent(MainActivity.this, detailActivity);
// Add object to intent
startDetailActivityIntent.putExtra("detailWallItem", (Parcelable)item);
// Start activity
startActivity(startDetailActivityIntent);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save instances of existing objects
outState.putString(JSON_KEY_RESULTS, JSONResults);
outState.putParcelableArrayList(WALL_ITEM_LIST_KEY, (ArrayList<? extends Parcelable>) this.WallItemList);
}
/**
* Parses JSON result
*
* #param result
*/
private void parseResult(String result) {
WallItemList = new ArrayList<>();
try {
JSONArray mJsonArray = new JSONArray(result);
// Loop through JSON array
for (int i = 0; i < mJsonArray.length(); i++) {
// Get picture URI fragment from JSON
String pictureURIFragment = mJsonArray.getJSONObject(i)
.getJSONArray("images").getJSONObject(0)
.getString("url");
// Load images into String
JSONArray JSONImageArray = mJsonArray.getJSONObject(i)
.getJSONArray("images");
// Create array for wallItem
String[] imageArray = new String[JSONImageArray.length()];
// Loop through JSONArray
for(int x = 0; x < JSONImageArray.length(); x++)
{
String pictureURLFragment = JSONImageArray.getJSONObject(x).getString("url");
// Built picture
URL pictureURL = NetworkUtils.builtPictureUrl(pictureURLFragment.toLowerCase());
imageArray[x] = java.net.URLDecoder.decode(pictureURL.toString());
}
// Built picture
URL pictureURL = NetworkUtils.builtPictureUrl(pictureURIFragment.toLowerCase());
String cleanPictureUrl = java.net.URLDecoder.decode(pictureURL.toString());
// add wall item to the list
WallItem item = new WallItem();
// Set fields of wallItem
item.setThumbnail(cleanPictureUrl);
item.setTitle(mJsonArray.getJSONObject(i).getString("author"));
item.setPhotographer(mJsonArray.getJSONObject(i).getString("photographer"));
item.setAddress(mJsonArray.getJSONObject(i).getString("address"));
item.setMaterial(mJsonArray.getJSONObject(i).getJSONObject("material").getString(langPreferenceString));
item.setDescription(mJsonArray.getJSONObject(i).getJSONObject("description").getString(langPreferenceString));
item.setImgURLArray(imageArray);
// Add wallItem to list
WallItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.api_url_settings_item)
{
Intent startSettingsActivity = new Intent(this, SettingsActivity.class);
startActivity(startSettingsActivity);
return true;
}
return super.onOptionsItemSelected(item);
}
private void getDeviceLanguage()
{
Log.d("HERE", Locale.getDefault().getLanguage());
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(getString(R.string.pref_api_url_key)))
{
// Update String again
APIUrlPreferenceString = sharedPreferences.getString(getString(R.string.pref_api_url_key), getString(R.string.pref_api_url_def_value));
new DownloadTask().execute();
}
if(key.equals(getString(R.string.pref_lang_check_key)))
{
// 1. If true, use system language.
// 2. if System language != en or nl, use default language: en.
// 3. if false, make selectable
}
if(key.equals(getString(R.string.pref_lang_list_key)) || key.equals(getString(R.string.pref_lang_check_key)))
{
// Language settings
if(sharedPreferences.getBoolean(getString(R.string.pref_lang_check_key), true))
{
// Use device settings
setLanguageSettings(Resources.getSystem().getConfiguration().locale.getLanguage());
langPreferenceString = Resources.getSystem().getConfiguration().locale.getLanguage();
}
else
{
// Use preference settings
setLanguageSettings(sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en)));
langPreferenceString = sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en));
}
// Reload data after executing new Download task
new DownloadTask().execute();
this.recreate();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
}
}
Here is my MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
private List<WallItem> wallItemList;
private Context mContext;
private OnItemClickListener onItemClickListener;
public MyRecyclerViewAdapter(Context context, List<WallItem> wallItemList) {
this.wallItemList = wallItemList;
this.mContext = context;
WallItem w = wallItemList.get(0);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
final WallItem wallItem = wallItemList.get(i);
//Download image using picasso library
if (!TextUtils.isEmpty(wallItem.getThumbnail())) {
// Load image into imageView
Picasso.with(mContext).load(wallItem.getThumbnail())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
}
//Setting text view title
customViewHolder.textView.setText(Html.fromHtml(wallItem.getMaterial()));
// Set OnClickListener to wallItem
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(wallItem);
}
};
customViewHolder.imageView.setOnClickListener(listener);
customViewHolder.textView.setOnClickListener(listener);
}
// Overwrite to return
#Override
public int getItemCount() {
return (null != wallItemList ? wallItemList.size() : 0);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
protected TextView textView;
public CustomViewHolder(View view) {
super(view);
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView = (TextView) view.findViewById(R.id.title);
}
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
}
My apologies for posting all the code but I can't identify the crucial points and don't have enough experience to pinpoint where it's going wrong. If anyone could help you would it would be greatly appreciated!
I suggest you to initialize and set the adapter in onCreate() method with an empty array of WallItems.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(MainActivity.this, new ArrayList<WallItem>());
mRecyclerView.setAdapter(adapter);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
// Setup shared preferences
setupSharedPreferences();
// Load the recyclerView
loadRecyclerView(savedInstanceState);
}
To update the list of items, I normally have a setItems method inside my adapter that updates the list and calls notifyDataSetChanged()
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
...
public void setItems(List<WallItem> items) {
this.wallItemList = wallItemList;
notifyDataSetChanged();
}
}
Your populateRecyclerView method then should call the setItems method to update the new list of items.
private void populateRecyclerView()
{
WallItem w = WallItemList.get(0);
adapter.setItems(WallItemList);
adapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(WallItem item) {
// Function to start new activity
Class detailActivity = DetailActivity.class;
// Create intent
Intent startDetailActivityIntent = new Intent(MainActivity.this, detailActivity);
// Add object to intent
startDetailActivityIntent.putExtra("detailWallItem", (Parcelable)item);
// Start activity
startActivity(startDetailActivityIntent);
}
});
}
I didn't test, buy this is how I normally use RecyclerView.
PostListFragment is extended by other fragments in my app. I need the uid of the current user, but it always returns null. When I try to run my app, I always get the error:
FATAL EXCEPTION: main
Process: com.example.cleeg.squad, PID: 8524
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.cleeg.squad.fragments.PostListFragment.getUid(PostListFragment.java:162)
at com.example.cleeg.squad.fragments.MyPostsFragment.getQuery(MyPostsFragment.java:19)
at com.example.cleeg.squad.fragments.PostListFragment.onActivityCreated(PostListFragment.java:76)
I've tried to find out why this is online, but I just get more confused and I don't really know how to fix it.
The function getUid() is at the bottom of the code.
public abstract class PostListFragment extends Fragment {
private static final String TAG = "PostListFragment";
private DatabaseReference mDatabaseReference;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private LinearLayoutManager mManager;
public PostListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_posts, container, false);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mRecycler = (RecyclerView) rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set up Layout Manager, reverse layout
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Set up FirebaseRecyclerAdapter with the Query
Query postsQuery = getQuery(mDatabaseReference);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
final DatabaseReference postRef = getRef(position);
// Set click listener for the whole post view
final String postKey = postRef.getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Launch PostDetailActivity
Intent intent = new Intent(getActivity(), PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
startActivity(intent);
}
});
// Determine if the current user has liked this post and set UI accordingly
if (model.stars.containsKey(getUid())) {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_24);
} else {
viewHolder.starView.setImageResource(R.drawable.ic_toggle_star_outline_24);
}
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
#Override
public void onClick(View starView) {
// Need to write to both places the post is stored
DatabaseReference globalPostRef = mDatabaseReference.child("posts").child(postRef.getKey());
DatabaseReference userPostRef = mDatabaseReference.child("user-posts").child(model.uid).child(postRef.getKey());
// Run two transactions
onStarClicked(globalPostRef);
onStarClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
private void onStarClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.stars.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.starCount = p.starCount - 1;
p.stars.remove(getUid());
} else {
// Star the post and add self to stars
p.starCount = p.starCount + 1;
p.stars.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.cleanup();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public abstract Query getQuery(DatabaseReference databaseReference);
}
The crash is because of no user is linked, i.e., getCurrentUser() is null. Please make user you have the user before fetching the userid.
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
mUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
} else {
//login or register screen
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is authenticated and now you can access uesr's properties as followings
mUserID = user.getUid();
} else {
// User is authenticated. So, let's try to re-authenticate
AuthCredential credential = EmailAuthProvider
.getCredential("user#example.com", "password1234");
// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d(TAG, "User re-authenticated.");
}
});
}
You can get details on it in this firebase document: https://firebase.google.com/docs/auth/android/manage-users
When I click on an image in our project, another image gets loaded. It works fine, but when I go back to the previous activity, and click on the same image, it doesn't get loaded.
This is the first activity which opens when app is active. This page will show grid of pictures
public class GentsActivity extends Fragment implements AdapterView.OnItemClickListener {
//Web api url
public static final String DATA_URL = "PHP LINK HERE";
//Tag values to read from json
public static final String TAG_IMAGE_URL = "small_image_url";
//GridView Object
private GridView gridView;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private SwipeRefreshLayout swipeContainer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
View view= inflater.inflate(R.layout.activity_gents, container, false);
gridView = (GridView) view.findViewById(R.id.gridView);
getData();
//swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
images = new ArrayList<>();
//Calling the getData method
/*swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
//Toast.makeText(this,"refresh ",Toast.LENGTH_SHORT).show();
Intent mIntent= new Intent(SareeActivity.this,SareeActivity.class);
startActivity(mIntent);
swipeContainer.setRefreshing(false);
}
});*/
return view;
}
private void getData(){
//Showing a progress dialog while our app fetches the data from url
//final ProgressDialog loading = ProgressDialog.show(this, "Please wait,","Fetching data.",false,false);
//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
// loading.dismiss();
//Displaying our grid
showGrid(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}
private void showGrid(JSONArray jsonArray){
//Looping through all the elements of json array
for(int i = 0; i<jsonArray.length(); i++){
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);
// Log.d(TAG_IMAGE_URL,"JSON SHOW GRID"+obj);
//getting image url and title from json object
images.add(obj.getString(TAG_IMAGE_URL));
Log.d(TAG_IMAGE_URL,"JSON SHOW GRID"+images);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Creating GridViewAdapter Object
//Adding adapter to gridview
GridViewAdapter gridViewAdapter = new GridViewAdapter(getContext(),images);
gridView.setAdapter(gridViewAdapter);
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String prompt = (String)adapterView.getItemAtPosition(i);
Intent mIntent= new Intent(getActivity(),LoadPhotoGents.class);
mIntent.putExtra("s",prompt);
startActivity(mIntent);
}
}
When I click on a particular photo, that single photo will open. The code is given below
public class LoadPhotoGents extends AppCompatActivity {
private String data, path;
private ImageView ivi;
public static final String DATA_URL = "PHP LINK HERE";
private static int id=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_photo_gents);
data = getIntent().getExtras().getString("s");
path = data.replace(".JPG", "big.JPG");
//Toast.makeText(this, "Path:" + path, Toast.LENGTH_LONG).show();
ivi = (ImageView) findViewById(R.id.fullImage);
Picasso.with(LoadPhotoGents.this).load(path).into(ivi);
getData();
ImageViewTouch img = (ImageViewTouch) findViewById(R.id.fullImage);
img.setBackgroundColor(Color.parseColor("#000000"));
ivi.buildDrawingCache();
Bitmap bmap=ivi.getDrawingCache();
//img.setFitToScreen(true);
img.setImageBitmap(bmap);
}
private void getData(){
String url=DATA_URL+data.trim();
StringRequest stringRequest=new StringRequest(url,new Response.Listener<String>(){
#Override
public void onResponse(String response){
showJSON(response);
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name= "";
try{
JSONArray jsonArray=new JSONArray(response);
//JSONArray result= jsonObject.getJSONArray("result");
JSONObject datas=jsonArray.getJSONObject(0);
name=datas.getString("description");
}catch(JSONException e){
Toast.makeText(this,"inside getData: "+name,Toast.LENGTH_SHORT).show();
}
}
}
This will definitely help you to debug the issue. In your code I can see that you are loading the image directly using Picasso.with().load().into() problem with this method is you do not know what is happening at the background.
You can do two things. First use Callback when you load the image into the ImageView as below
Picasso.with(LoadPhotoGents.this).load(path).into(ivi, new Callback()
{
#Override
public void onSuccess()
{
Timber.d("Image Loaded Successfully");
}
#Override
public void onError()
{
Timber.d("Error Loading Image");
}
});
Above can be used to handle image loaded/not loaded scenario.
Now coming to the actual error while loading the image, you need to use a Picasso.Builder which has a listener which will help you know the actual error.
Build Picasso Builder as below
Picasso.Builder builder = new Picasso.Builder(mContext);
builder.listener(new Picasso.Listener()
{
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception)
{
Timber.d(exception.getMessage());
}
});
Picasso pic = builder.build();
To Load the image do the following
pic.load(path).into(ivi, new Callback()
{
#Override
public void onSuccess()
{
Timber.d("Image Loaded Successfully");
}
#Override
public void onError()
{
Timber.d("Image Load Error");
}
});
Ensure that path variable is not null or empty
Ok i have one list with movies and there i have some image, title, ratings, genres and year in one row for every item in listView. And now i'm trying to sort these movies by name, rating and year. I have followed this tutorial, but i have stucked here:
#Override
public void onClick(View view) {
if(view.getTag().equals(TAG_SORT_NAME)){
adapter.getItem();
}
if(view.getTag().equals(TAG_SORT_RATING)){
}
if(view.getTag().equals(TAG_SORT_YEAR)){
}
}
I don't know what should i passed there for getItem and in his tutorial he is using fragments and i'm not. Here is my activity:
public class ListaPreporuka extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener
, SortListener{
// Log tag
private static final String TAG = ListaPreporuka.class.getSimpleName();
// Movies json url
private static final String url = "http://www.nadji-ekipu.org/wp-content/uploads/2015/07/movies.txt";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
private CustomListAdapter adapter;
private static final String TAG_SORT_NAME = "sortName";
private static final String TAG_SORT_RATING = "sortRating";
private static final String TAG_SORT_YEAR = "sortYear";
private static String Year = "year";
private static String Rating = "rating";
private static String Title = "title";
private static String bitmap = "thumbnailUrl";
private static String opis = "opis";
private static String urlMovie = "url";
private MediaPlayer mp_off;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_preporuka);
// Toolbabr settings
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_horor_filmovi_ikonica);
Intent newActivity2=new Intent();
setResult(RESULT_OK, newActivity2);
mp_off = MediaPlayer.create(this, R.raw.button_click_off);
final MediaPlayer mp_on = MediaPlayer.create(this, R.raw.button_click_on);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setIcon(R.drawable.ic_horor_filmovi_ikonica);
pDialog.setMessage("Učitavanje...");
pDialog.setCancelable(false);
pDialog.show();
listView = (ListView) findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
if (AppStatus.getInstance(this).isOnline()) {
Log.v("Home", "############################You are online!!!!");
} else {
setContentView(R.layout.no_connection);
Toast t = Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT);
t.show();
Log.v("Home", "############################You are not online!!!!");
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String opisFilma = ((TextView) view.findViewById(R.id.opis))
.getText().toString();
String urlFilm = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String ocena = String.valueOf(movieList.get(position).getRating());
String godina = String.valueOf(movieList.get(position).getYear());
bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
Intent intent = new Intent(ListaPreporuka.this, MoviesSingleActivity.class);
intent.putExtra(Title, name);
intent.putExtra(opis, opisFilma);
intent.putExtra("images", bitmap);
intent.putExtra(Rating, ocena);
intent.putExtra(Year, godina);
intent.putExtra(urlMovie, urlFilm);
mp_on.start();
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
buildFAB();
}
private void buildFAB(){
// Declare icon for FAB
ImageView icon = new ImageView(this);
icon.setImageResource(R.drawable.ic_halloween);
// Build FAB
FloatingActionButton actionButton = new FloatingActionButton.Builder(this)
.setContentView(icon)
.build();
// Declare icons for SubAction Buttons
ImageView iconSortName = new ImageView(this);
iconSortName.setImageResource(R.drawable.ic_halloween);
ImageView iconSortRating = new ImageView(this);
iconSortRating.setImageResource(R.drawable.ic_halloween);
ImageView iconSortYear = new ImageView(this);
iconSortYear.setImageResource(R.drawable.ic_halloween);
// Set the background for all Sub buttons
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
// Build the Sub Buttons
SubActionButton buttonSortName = itemBuilder.setContentView(iconSortName).build();
SubActionButton buttonSortRating = itemBuilder.setContentView(iconSortRating).build();
SubActionButton buttonSortYear = itemBuilder.setContentView(iconSortYear).build();
buttonSortName.setTag(TAG_SORT_NAME);
buttonSortRating.setTag(TAG_SORT_RATING);
buttonSortYear.setTag(TAG_SORT_YEAR);
buttonSortName.setOnClickListener(this);
buttonSortRating.setOnClickListener(this);
buttonSortYear.setOnClickListener(this);
// add the sub buttons to the main floating action button
FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this)
.addSubActionView(buttonSortName)
.addSubActionView(buttonSortRating)
.addSubActionView(buttonSortYear)
.attachTo(actionButton)
.build();
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies(){
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
movieList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setOpis(obj.getString("opis"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
movie.setUrl(obj.getString("url"));
// Genre is json array
final JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == android.R.id.home) {
finish();
mp_off.start();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
mp_off.start();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
#Override
public void onClick(View view) {
if(view.getTag().equals(TAG_SORT_NAME)){
adapter.getItem();
}
if(view.getTag().equals(TAG_SORT_RATING)){
}
if(view.getTag().equals(TAG_SORT_YEAR)){
}
}
#Override
public void onSortByName() {
}
#Override
public void onSortByRating() {
}
#Override
public void onSortByYear() {
}
}
You should sort your movieList, assuming Movie contains genre String field, below is some quick example to sort it:
Comparator<Movie> comparator = new Comparator<Movie>() {
#Override
public int compare(Movie movie, Movie t1) {
return movie.genre.compareTo(t1.genre);
}
};
// ordered by genre
Collections.sort(movieList, comparator);
// Reverse order by genre
Collections.sort(movieList, Collections.reverseOrder(comparator));
I'm trying to pass the value in recyclerview item to another activity when we click the recyclerview item. Here I use the OnItemTouchListener.
I retrieve data from JSON and parse it into ArrayList. I save 5 parameters. Title, ID, Rating, ReleaseDate, urlPoster, but right now i only show 2 parameters, Title, and image from urlposter.
I want to pass the other parameters to another activity, but i can't find out how to do that.
There's another question similar like this (Values from RecyclerView item to other Activity), but he uses OnClick, not OnItemTouch, and he do that in the ViewHolder. I read somewhere in the internet that it's not the right thing to do.
Here's my code
public class Tab1 extends Fragment {
private static final String ARG_PAGE = "arg_page";
private static final String STATE_MOVIES = "state movies";
private TextView txtResponse;
private String passID;
// Progress dialog
private ProgressDialog pDialog;
//private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
private String urlJsonArry = "http://api.themoviedb.org/3/movie/popular?api_key=someapikeyhere";
private String urlJsonImg = "http://image.tmdb.org/t/p/w342";
// temporary string to show the parsed response
private String jsonResponse = "";
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
private ArrayList<Movies> movies = new ArrayList<Movies>();
public Tab1() {
// Required empty public constructor
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_MOVIES, movies);
}
public static Tab1 newInstance(int pageNumber){
Tab1 myFragment = new Tab1();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
}
/**
* Method to make json object request where json response starts wtih {
* */
private void makeJsonObjectRequest() {
showpDialog();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonArry, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
try {
JSONArray result = response.getJSONArray("results");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < result.length(); i++){
JSONObject jsonObject = result.getJSONObject(i);
String id = jsonObject.getString("id");
String originalTitle = jsonObject.getString("original_title");
String releaseDate = jsonObject.getString("release_date");
String rating = jsonObject.getString("vote_average");
String urlThumbnail = urlJsonImg + jsonObject.getString("poster_path");
//jsonResponse = "";
jsonResponse += "ID: " + id + "\n\n";
jsonResponse += "Title: " + originalTitle + "\n\n";
jsonResponse += "Release Date: " + releaseDate + "\n\n";
jsonResponse += "Rating: " + rating + "\n\n";
}
//Toast.makeText(getActivity(),"Response = "+jsonResponse,Toast.LENGTH_LONG).show();
parseResult(response);
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse);
//makeJsonArrayRequest();
// Calling the RecyclerView
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view_movie);
mRecyclerView.setHasFixedSize(true);
// The number of Columns
mLayoutManager = new GridLayoutManager(getActivity(),2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MovieAdapter(getActivity(),movies);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onMovieClick(View view, int position) {
Toast.makeText(getActivity(), "Kepencet " + position, Toast.LENGTH_SHORT).show();
**//what to do here?**
}
#Override
public void onMovieLongClick(View view, int position) {
Toast.makeText(getActivity(),"Kepencet Lama "+position,Toast.LENGTH_LONG).show();
}
}));
makeJsonObjectRequest();
if (savedInstanceState!=null){
movies=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
mAdapter.notifyDataSetChanged();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.tab_1, container, false);
return view;
}
private void parseResult(JSONObject response) {
try {
JSONArray arrayMovies = response.getJSONArray("results");
if (movies == null) {
movies = new ArrayList<Movies>();
}
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovies = arrayMovies.getJSONObject(i);
Movies item = new Movies();
item.setTitle(currentMovies.optString("original_title"));
item.setRating(currentMovies.optString("vote_average"));
item.setReleaseDate(currentMovies.optString("release_date"));
item.setId(currentMovies.optString("id"));
item.setUrlThumbnail(urlJsonImg+currentMovies.optString("poster_path"));
movies.add(item);
mAdapter.notifyDataSetChanged();
//Toast.makeText(getActivity(),"Movie : "+movies,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector mGestureDetector;
private ClickListener mClickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.mClickListener = clickListener;
mGestureDetector = 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.onMovieLongClick(child,recyclerView.getChildAdapterPosition(child));
}
super.onLongPress(e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
mClickListener.onMovieClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener{
public void onMovieClick(View view, int position);
public void onMovieLongClick(View view, int position);
}
}
any help would be appreciated. Thanks!
You need to add those other two values to a bundle in the intent. So something like this:
Intent intent = new Intent(getActivity(), YourNextActivity.class);
intent.putExtra("movie_id_key", movies.get(position).getId); //you can name the keys whatever you like
intent.putExtra("movie_rating_key", movies.get(position).getRating); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
intent.putExtra("movie_release_date_key", movies.get(position).getReleaseDate);
startActivity(intent)
And in your new activity just do this to retrieve:
String id = getIntent().getExtras().getString("movie_id_key");
Add them as extras in the intent with which you start the activity:
Intent intent = new Intent(currentActivity, targetActivity);
// Sree was right in his answer, it's putExtra, not putStringExtra. =(
intent.putExtra("title", title);
// repeat for ID, Rating, ReleaseDate, urlPoster
startActivity(intent);
then pull them out in the onCreate of the other activity with
Intent startingIntent = getIntent();
String title = startingIntent.getStringExtra("title"); // or whatever.
In response to the comment below:
I'm not 100% sure how you implemented it, but it looks like you have onclick handlers that pass a position and a view reference, right? Adapt it as you like, but basically...:
public void onClick(View v, int position){
Movie m = movies.get(position);
Intent intent = new Intent(v.getContext(), AnotherActivity.class);
intent.putExtra("my_movie_foo_key", m.getFoo());
intent.putExtra("my_movie_bar_key", m.getBar());
// etc.
v.getContext().startActivity(intent);
}
As long as you have a valid context reference (and they couldn't click on a view without a valid context), you can start an activity from wherever you like.