I have recently created a chatting application, which gets crash due to these lines :-
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
t_username.setText(user.getUsername());
if (user.getImageURL().equals("No image")){
profile_image.setImageResource(R.drawable.profile_img);
} else {
//change this
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I don't understand why this crashes my application.
MainActivity.java :-
package com.dccodes.chugli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import com.dccodes.chugli.Adapter.OnItemClick;
import com.dccodes.chugli.Fragments.ChatsFragment;
import com.dccodes.chugli.Fragments.ProfileFragment;
import com.dccodes.chugli.Fragments.UsersFragment;
import com.dccodes.chugli.Model.Chat;
import com.dccodes.chugli.Model.User;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity implements OnItemClick {
boolean doubleBackToExitPressedOnce = false;
CircleImageView profile_image;
TextView t_username;
ProgressDialog dialog;
Typeface MR,MRR;
FirebaseUser firebaseUser;
DatabaseReference reference;
OnItemClick onItemClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.onItemClick = this;
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
profile_image = findViewById(R.id.profile_image);
final TabLayout tabLayout = findViewById(R.id.tab_layout);
final ViewPager viewPager = findViewById(R.id.view_pager);
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
}
});
t_username = findViewById(R.id.t_username);
t_username.setTypeface(MR);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
t_username.setText(user.getUsername());
if (user.getImageURL().equals("No image")){
profile_image.setImageResource(R.drawable.profile_img);
} else {
//change this
Glide.with(getApplicationContext()).load(user.getImageURL()).into(profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
reference = FirebaseDatabase.getInstance().getReference("Chats");
dialog = com.dccodes.chugli.Utils.showLoader(MainActivity.this);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
int unread = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (chat.getReceiver().equals(firebaseUser.getUid()) && !chat.isIsseen()){
unread++;
}
}
if (unread == 0){
viewPagerAdapter.addFragment(ChatsFragment.newInstance(onItemClick), "Chats");
} else {
viewPagerAdapter.addFragment(ChatsFragment.newInstance(onItemClick), "("+unread+") Chats");
}
viewPagerAdapter.addFragment(UsersFragment.newInstance(onItemClick), "Users");
viewPagerAdapter.addFragment(new ProfileFragment(), "Profile");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if(dialog!=null){
dialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.logout:
FirebaseAuth.getInstance().signOut();
// change this code beacuse your app will crash
startActivity(new Intent(MainActivity.this, StartActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
return true;
}
return false;
}
#Override
public void onItemCLick(String uid, View view) {
ViewProfileActivity viewProfileActivity =
ViewProfileActivity.newInstance(uid,this);
viewProfileActivity.show(getSupportFragmentManager(),
"view_profile");
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragments;
private ArrayList<String> titles;
ViewPagerAdapter(FragmentManager fm){
super(fm);
this.fragments = new ArrayList<>();
this.titles = new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
public void addFragment(Fragment fragment, String title){
fragments.add(fragment);
titles.add(title);
}
// Ctrl + O
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
private void status(String status){
reference = FirebaseDatabase.getInstance().getReference("User").child(firebaseUser.getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
reference.updateChildren(hashMap);
}
#Override
protected void onResume() {
super.onResume();
status("online");
}
#Override
protected void onPause() {
super.onPause();
status("offline");
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tap again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000); }
}
MainActivity.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical"
tools:context="com.dccodes.chugli.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dgreen"
android:padding="#dimen/padding_10_dp"
android:theme="#style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/MenuStyle">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/profile_img"
android:id="#+id/profile_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/t_username"
android:textSize="22sp"
android:layout_marginLeft="25dp"
android:textColor="#fff"
android:textStyle="bold"
android:layout_marginStart="25dp" />
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dgreen"
app:tabIndicatorColor="#fff"
app:tabSelectedTextColor="#fff"
app:tabTextColor="#fff"
tools:ignore="SpeakableTextPresentCheck,SpeakableTextPresentCheck" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:ignore="SpeakableTextPresentCheck,SpeakableTextPresentCheck" />
</LinearLayout>
I don't understand why I get this error, I have searched it everywhere, but I couldn't find the answer. I hope anyone will help me!
Related
This is the error I am facing
Caused by: 'java.lang.NullPointerException' Attempt to invoke virtual method 'java.lang.String() on a null object reference
at com.example.stdio9.MainActivity.getProfileImage(MainActivity.java:230)
at com.example.stdio9.MainActivity.onCreate(MainActivity.java:84)
This is my java code
package com.example.stdio9;
import static com.google.android.gms.auth.api.signin.GoogleSignIn.getClient;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.stdio9.fragment.ExploreFragment;
import com.example.stdio9.fragment.HomeFragment;
import com.example.stdio9.fragment.LibraryFragment;
import com.example.stdio9.fragment.SubscriptionsFragment;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
BottomNavigationView bottomNavigationView;
FrameLayout frameLayout;
private Fragment selectorFragment;
ImageView user_profile_image;
GoogleSignInClient mGoogleSignInClient;
private static final int RC_SIGN_IN = 100;
FirebaseAuth auth;
FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
bottomNavigationView = findViewById(R.id.bottom_navigation);
frameLayout = findViewById(R.id.frame_layout);
auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
user_profile_image = findViewById(R.id.user_profile_image);
getProfileImage();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
mGoogleSignInClient = GoogleSignIn.getClient(MainActivity.this,gso);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
selectorFragment = new HomeFragment();
break;
case R.id.explore:
selectorFragment = new ExploreFragment();
break;
case R.id.publish:
Toast.makeText(MainActivity.this, "Upload a video", Toast.LENGTH_SHORT).show();
break;
case R.id.subscriptions:
selectorFragment = new SubscriptionsFragment();
break;
case R.id.library:
selectorFragment = new LibraryFragment();
break;
}
if (selectorFragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, selectorFragment).commit();
}
return true;
}
});
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, new HomeFragment()).commit();
user_profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user !=null){
Toast.makeText(MainActivity.this, "User Already Signed In", Toast.LENGTH_SHORT).show();
}else{
showDialog();
}
}
});
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
ViewGroup viewGroup = findViewById(android.R.id.content);
View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_signin_dialogue,viewGroup,false);
builder.setView(view);
TextView txt_google_signIn = view.findViewById(R.id.txt_google_signIn);
txt_google_signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
builder.create().show();
}
private void signIn() {
Intent intent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(intent,RC_SIGN_IN);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_SIGN_IN){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try{
GoogleSignInAccount account = task.getResult(ApiException.class);
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
auth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
HashMap<String,Object> map = new HashMap<>();
map.put("username",account.getDisplayName());
map.put("email",account.getEmail());
map.put("profile",String.valueOf(account.getPhotoUrl()));
map.put("uid", firebaseUser.getUid());
map.put("search",account.getDisplayName().toLowerCase());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users");
reference.child(firebaseUser.getUid()).setValue(map);
}
else{
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
catch(Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.notification:
Toast.makeText(this, "Notification", Toast.LENGTH_SHORT).show();
break;
case R.id.search:
Toast.makeText(this, "Search", Toast.LENGTH_SHORT).show();
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
private void getProfileImage(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users");
reference.child(user.getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String p =snapshot.child("profile").getValue().toString();
Picasso.get().load(p).placeholder(R.drawable.ic_baseline_account_circle).into(user_profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
My XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appBar">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar"
android:background="#color/white"
app:menu="#menu/toolbar_menu">
<ImageView
android:layout_width="70dp"
android:layout_height="50dp"
android:src="#drawable/icon1"
android:adjustViewBounds="true"
android:id="#+id/icon"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:src="#drawable/ic_baseline_account_circle"
android:layout_marginStart="190dp"
android:id="#+id/user_profile_image"/>
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/appBar"
android:layout_above="#+id/bottom_navigation"
android:id="#+id/frame_layout"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
app:menu="#menu/bottom_menu"
android:layout_alignParentBottom="true"
app:itemTextColor="#color/black"
app:itemIconTint="#color/black"
app:itemRippleColor="#color/cardview_dark_background"
android:id="#+id/bottom_navigation"
app:labelVisibilityMode="labeled"/>
</RelativeLayout>
Error in this particular lines
reference.child(user.getUid()).addValueEventListener(new ValueEventListener() {
and `getProfileImage();
I am new to android can someone please help...will really appretiate
If it's referring to the line:
reference.child(user.getUid()).addValueEventListener(new ValueEventListener()
then it's telling you that either "reference" or "user" is null, and you're note checking for it. So, you need to do something like:
if(reference == null || user == null) return;
right before that line, or alternatively, put in some logic to handle the case of either of those being NULL
I am new to android development and am trying to bind recycler View with setAdapter but am getting this error "Cannot resolve method 'setAdapter' in 'ConstraintLayout' "
my mainActivity.java code is:
my main objective is to use ActivityMainBinding to bind recyclerView with setAdapter
package com.example.baatcheet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.baatcheet.usersAdapter.*;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.baatcheet.databinding.ActivityMainBinding;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
FirebaseDatabase database;
ArrayList<User> users;
usersAdapter UserAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
database = FirebaseDatabase.getInstance();
users = new ArrayList<>();
UserAdapter = new usersAdapter(this, users);
binding.recyclerView.setAdapter(UserAdapter);
database.getReference().child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users.clear();
for(DataSnapshot snapshot1 : snapshot.getChildren()){
User user = snapshot1.getValue(User.class);
users.add(user);
}
UserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
Toast.makeText(this,"Search Clicked" , Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(this , " setting Clicked" , Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.top_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
this is the part where i am getting an error -> binding.recyclerView.setAdapter(UserAdapter);
and it tells me to rename reference
what does this actually mean?
the activity_main.xml file is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:elevation="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/menu">
</com.google.android.material.bottomnavigation.BottomNavigationView>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/row_conversation"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
the users.java code is:
package com.example.baatcheet;
public class User {
private String uid,name,phoneNumber,profileImage;
public User(){
}
public User(String uid, String name, String phoneNumber, String profileImage) {
this.uid = uid;
this.name = name;
this.phoneNumber = phoneNumber;
this.profileImage = profileImage;
}
public void setUid(String uid) {
this.uid = uid;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setProfileImage(String profileImage) {
this.profileImage = profileImage;
}
public String getUid() {
return uid;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getProfileImage() {
return profileImage;
}
}
the usersAdapter.java code is:
package com.example.baatcheet;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baatcheet.databinding.RowConversationBinding;
import java.util.ArrayList;
public class usersAdapter extends RecyclerView.Adapter<usersAdapter.UsersViewHolder>{
Context context;
ArrayList<User> users;
public usersAdapter(Context context , ArrayList<User> users){
this.context = context;
this.users = users;
}
{
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_conversation,parent,false);
return new UsersViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UsersViewHolder holder, int position) {
User user = users.get(position);
holder.binding.userName.setText(user.getName());
}
#Override
public int getItemCount() {
return users.size();
}
public class UsersViewHolder extends RecyclerView.ViewHolder{
RowConversationBinding binding;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
binding = RowConversationBinding.bind(itemView);
}
}
}
In your layout file, it is the root ConstraintLayout that has the #+id/recyclerView id:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerView"
... />
You should move this id to the RecyclerView itself:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
... />
Once you do this, binding.recyclerView will refer to the RecyclerView instead of the ConstraintLayout.
If you need to access the ConstraintLayout via the view binding for some other reason, you can use binding.root.
I have tool bar and I want to show two menu icons i.e myicon_clearnotifications and /myicon_goback but when I click only notifications are showing not these two menu items on toolbar.other content is showing but toolbar is not even appearing.
XML toolbar code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorWhite"
tools:context="Activities.AllNotifications">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/allNotifications_tollbar"
android:layout_alignParentTop="true"
android:background="#5A6E64"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:id="#+id/allNotifications_RecyclerView"/>
</RelativeLayout>
My menu items code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/allNotifications_item_clear"
android:title="CLEAR"
android:icon="#drawable/myicon_clearnotifications"
android:checkable="true"
app:showAsAction="always"
/>
<item
android:id="#+id/allNotifications_item_goBack"
android:title="GO BACK"
android:icon="#drawable/myicon_goback"
android:checkable="true"
app:showAsAction="always"
/>
</menu>
and this is my java code
package Activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import com.example.connectsocialmediaapp.R;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.firestore.WriteBatch;
import java.util.ArrayList;
import AdapterClasses.AllNotificationsAdapter;
import ModelClasses.Model_AllNotifications;
public class AllNotifications extends AppCompatActivity {
private FirebaseFirestore objectFirebaseFirestore;
private RecyclerView objectRecyclerView;
private AllNotificationsAdapter objectAllNotificationsAdapter;
private Toolbar objectToolbar;
private FirebaseAuth objectFirebaseAuth;
private Dialog objectDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_notifications);
objectFirebaseFirestore=FirebaseFirestore.getInstance();
objectFirebaseAuth=FirebaseAuth.getInstance();
attachJavaToXML();
getAllNotificationIntoRV();
}
#Override
protected void onStart() {
super.onStart();
objectAllNotificationsAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
objectAllNotificationsAdapter.stopListening();
}
private void getAllNotificationIntoRV()
{
try
{
if(objectFirebaseAuth!=null) {
String currentLoggedInUser = objectFirebaseAuth.getCurrentUser().getEmail();
Query objectQuery = objectFirebaseFirestore.collection("userProfileData")
.document(currentLoggedInUser).collection("Notifications");
FirestoreRecyclerOptions<Model_AllNotifications> objectOptions =
new FirestoreRecyclerOptions.Builder<Model_AllNotifications>()
.setQuery(objectQuery, Model_AllNotifications.class).build();
objectAllNotificationsAdapter = new AllNotificationsAdapter(objectOptions);
objectRecyclerView.setAdapter(objectAllNotificationsAdapter);
objectRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
else
{
Toast.makeText(this, R.string.no_user_online, Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
ArrayList<String> objectStringArrayList=new ArrayList<>();
private void clearAllNotifications()
{
try
{
if(objectFirebaseAuth!=null)
{
final String currentLoggedInUser=objectFirebaseAuth.getCurrentUser().getEmail();
objectFirebaseFirestore.collection("userProfileData")
.document(currentLoggedInUser)
.collection("Notifications")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
for(QueryDocumentSnapshot objectQueryDocumentSnapshot:task.getResult())
{
objectStringArrayList.add(objectQueryDocumentSnapshot.getId());
WriteBatch objectWriteBatch=objectFirebaseFirestore.batch();
for(int count=0;count<objectStringArrayList.size();count++)
{
objectWriteBatch.delete(
objectFirebaseFirestore.collection("userProfileData")
.document(currentLoggedInUser)
.collection("Notifications")
.document(objectStringArrayList.get(count))
);
}
objectWriteBatch.commit().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
Toast.makeText(AllNotifications.this, "Notifications Cleared", Toast.LENGTH_SHORT).show();
}
else if(!task.isSuccessful())
{
Toast.makeText(AllNotifications.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
});
}
else
{
Toast.makeText(this, R.string.no_user_online, Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void attachJavaToXML()
{
try
{
objectDialog =new Dialog(this);
objectDialog.setContentView(R.layout.please_wait_dialog);
objectToolbar=findViewById(R.id.allNotifications_tollbar);
setSupportActionBar(objectToolbar);
objectRecyclerView=findViewById(R.id.allNotifications_RecyclerView);
objectToolbar.inflateMenu(R.menu.all_notifications_menu);
objectToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId())
{
case R.id.allNotifications_item_clear:
clearAllNotifications();
return true;
case R.id.allNotifications_item_goBack:
startActivity(new Intent(AllNotifications.this,MainContentPage.class));
return true;
}
return false;
}
});
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
The problem is that is menu is not connected to AllNotifications.
To fix that you need to override onCreateOptionsMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
Replace my_menu with the name of your menu under res/menu
Also to have events on the menu items you need to override onOptionsItemSelected()
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.allNotifications_item_clear) {
// Do something
} else if (id == R.id.allNotifications_item_goBack) {
// Do something else
}
}
Another point
It seems that you have a custom Toolbar in layout, so you can set it with
Toolbar toolbar = mView.findViewById(R.id.allNotifications_tollbar);
setSupportActionBar(toolbar);
But make sure that you use NoActionBar theme.
I am trying to get a list of posts to display on a RecyclerView in a fragment in Android Studio using Java I do have the ".setAdapter()" code displayed but I am still receiving this error message and I have been stuck on this for a week. I am sure it is something Stupid but here is my fragment, my adapter, and the XML file for the fragment
Fragment
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.zapster_picture_sharing.Adapter.PostAdapter;
import com.example.zapster_picture_sharing.Model.Post;
import com.example.zapster_picture_sharing.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private PostAdapter postAdapter;
private List<Post> postLists;
private List<String> followingList;
ProgressBar progressBar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
progressBar = view.findViewById(R.id.progress_circular);
checkFollowing();
recyclerView = view.findViewById(R.id.recycler_view_story);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists, true);
recyclerView.setAdapter(postAdapter);
return view;
}
private void checkFollowing(){
followingList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child("following");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
followingList.clear();
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
followingList.add(snapshot.getKey());
}
readPosts();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void readPosts(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
postLists.clear();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
Post post = snapshot.getValue(Post.class);
for(String id:followingList){
if(post.getPublisher().equals(id)){
postLists.add(post);
}
}
}
postAdapter.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
PostAdapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.zapster_picture_sharing.Model.Post;
import com.example.zapster_picture_sharing.Model.User;
import com.example.zapster_picture_sharing.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.List;
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.ViewHolder> {
public Context mContext;
public List<Post> mPosts;
//private FirebaseUser firebaseUser;
public PostAdapter(Context mContext, List<Post> mPosts, boolean b){
this.mContext = mContext;
this.mPosts = mPosts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.post_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final Post post = mPosts.get(i);
Glide.with(mContext).load(post.getPostimage()).into(viewHolder.post_image);
if (post.getDescription().equals("")){
viewHolder.description.setVisibility(View.GONE);
} else {
viewHolder.description.setVisibility(View.VISIBLE);
viewHolder.description.setText(post.getDescription());
}
publisherInfo(viewHolder.image_profile, viewHolder.username, viewHolder.publisher, post.getPublisher());
}
#Override
public int getItemCount() {
return mPosts.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView image_profile, post_image, like, comment, save;
public TextView username, likes, publisher, description, comments;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image_profile = itemView.findViewById(R.id.image_profile);
post_image = itemView.findViewById(R.id.post_image);
comments = itemView.findViewById(R.id.comments);
like = itemView.findViewById(R.id.like);
comment = itemView.findViewById(R.id.comment);
save = itemView.findViewById(R.id.save);
username = itemView.findViewById(R.id.username);
likes = itemView.findViewById(R.id.likes);
publisher = itemView.findViewById(R.id.publisher);
description = itemView.findViewById(R.id.description);
}
}
private void publisherInfo(final ImageView image_profile, final TextView username, final TextView publisher, final String userid){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
Glide.with(mContext).load(user.getImageurl()).into(image_profile);
username.setText(user.getUsername());
publisher.setText(user.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
XML for the fragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment.HomeFragment">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="180dp"
android:layout_height="35dp"
android:src="#drawable/zapster_logo"
android:id="#+id/logo"
android:layout_marginLeft="-20dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:src="#drawable/ic_inbox"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/bar">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view_story"
android:layout_margin="5dp"
android:layout_below="#id/bar"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view"
android:layout_below="#id/recycler_view_story"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<ProgressBar
android:id="#+id/progress_circular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
Post Model
package com.example.zapster_picture_sharing.Model;
public class Post {
private String postid;
private String postimage;
private String description;
private String publisher;
public Post(String postid, String postimage, String description, String publisher){
this.postid = postid;
this.postimage = postimage;
this.description = description;
this.publisher = publisher;
}
public Post(){
}
public String getPostid() {
return postid;
}
public void setPostid(String postid) {
this.postid = postid;
}
public String getPostimage() {
return postimage;
}
public void setPostimage(String postimage) {
this.postimage = postimage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
In the XML, there are actually two instances of androidx.recyclerview.widget.RecyclerView.
But in your code, you only attach an adapter to one of them, which causes this warning.
require add setLayoutManager
postAdapter = new PostAdapter(getContext(), postLists, true);
recyclerView.setAdapter(postAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView#setLayoutManager(androidx.recyclerview.widget.RecyclerView.LayoutManager)
You are re-initializing postsList after calling your checkFollowing() method.
try
postLists = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postLists, true);
recyclerView.setAdapter(postAdapter);
checkFollowing();
i have created the online wallpaper application and i used to activity for my app and i use volley and glide for my app but when i use bottom navigation drawer , activity is not useful .
after that i use fragment but now when i run application my recyclerview doesn't show anything
MainFragment.java:
package ir.zooding.wallpaper.activity;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.adapter.GalleryAdapter;
import ir.zooding.wallpaper.app.AppController;
import ir.zooding.wallpaper.model.Image;
import ir.zooding.wallpaper.receiver.ConnectivityReceiver;
public class MainFragment extends Fragment implements ConnectivityReceiver.ConnectivityReceiverListener {
RecyclerView recycler_view;
static final String url="";
ArrayList<Image> images;
GalleryAdapter mAdapter;
ProgressDialog pd;
View v;
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_main, container, false);
Toolbar toolbar=(Toolbar)v.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
recycler_view=(RecyclerView) v.findViewById(R.id.recycler_view);
pd=new ProgressDialog(getActivity());
pd.setCancelable(false);
images=new ArrayList<>();
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
RecyclerView.LayoutManager mLayoutManager=new GridLayoutManager(getActivity().getApplicationContext(),2);
recycler_view.setLayoutManager(mLayoutManager);
recycler_view.setAdapter(mAdapter);
Log.i("LOG:","stop 1");
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
recycler_view.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getActivity().getApplicationContext(),recycler_view, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle=new Bundle();
bundle.putSerializable("images",images);
bundle.putInt("position",position);
//Log.i("LOG:",""+position);
// FragmentTransaction ft=getFragmentManager().beginTransaction();
android.app.FragmentTransaction ft=getActivity().getFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment=SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft,"slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
checkConnection();
fetchImages();
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "دسترسی به حافظه داخلی لغو شد!!!", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void fetchImages()
{
pd.setMessage("در حال بارگزاری ...");
pd.show();
StringRequest req = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("", response.toString());
pd.dismiss();
images.clear();
try {
JSONObject object = new JSONObject(response);
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject dataObject = dataArray.getJSONObject(i);
Image image = new Image();
image.setName_client(dataObject.getString("name_client"));
image.setName(dataObject.getString("name"));
// JSONObject url = object.getJSONObject("url");
image.setSmall(dataObject.getString("small"));
image.setOriginal(dataObject.getString("orginal"));
image.setTimestamp(dataObject.getString("timestamp"));
images.add(image);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("LOG:","stop 2");
mAdapter.notifyDataSetChanged();
Log.i("LOG:","stop 3");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("", "Error: " + error.getMessage());
pd.dismiss();
}
});
AppController.getmInstance().addToRequsetQueue(req);
}
// Method to manually check connection status
private void checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
}
// Showing the status in Snackbar
private void showSnack(boolean isConnected) {
String message ="";
//View parentLayout = v.findViewById(android.R.id.content);
RelativeLayout parentLayout = (RelativeLayout)v.findViewById(R.id.mroot);
if (!isConnected) {
message = "اتصال شما به اینترنت برقرار نیست!";
Snackbar snackbar = Snackbar
.make(parentLayout, message, Snackbar.LENGTH_LONG)
.setAction("بررسی مجدد", new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchImages();
checkConnection();
}
});
snackbar.setActionTextColor(Color.RED);
snackbar.setActionTextColor(Color.parseColor("#e62d3f"));
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.parseColor("#FFC107"));
snackbar.setDuration(8000);
snackbar.show();
}
}
#Override
public void onResume() {
super.onResume();
// register connection status listener
AppController.getmInstance().setConnectivityListener(this);
}
/**
* Callback will be triggered when there is change in
* network connection
*/
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
showSnack(isConnected);
}
}
GalleryAdapter.java:
package ir.zooding.wallpaper.adapter;
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 ir.zooding.wallpaper.R;
import ir.zooding.wallpaper.model.Image;
import static android.R.animator.fade_in;
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
List<Image> images;
Context mContext;
public GalleryAdapter (Context context,List<Image> images){
this.images = images;
mContext = context;
}
#Override
public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_thumbnail,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(GalleryAdapter.MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getSmall())
.thumbnail(0.5f)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.drawable.loading)
.fitCenter()
.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{
GalleryAdapter.ClickListener clickListener;
GestureDetector gestureDetector;
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) {
}
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail =(ImageView) view.findViewById(R.id.thumbnail);
}
}
}
MainActivity.java:
package ir.zooding.wallpaper.activity;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import ir.adad.client.Adad;
import ir.zooding.wallpaper.R;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Adad.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = MainFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = CategoryFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = InfoFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, MainFragment.newInstance());
transaction.commit();
//Used to select an item programmatically
//bottomNavigationView.getMenu().getItem(2).setChecked(true);
}
}
fragment_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/mroot"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/include"
layout="#layout/content_main"/>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?attr/actionBarSize">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="vertical"/>
There are Contexts considerations you need to make throught your code. You may be using the wrong Contexts example very big Contexts. For example from what I can see fast one of it is this line in MainFragment.java:
mAdapter=new GalleryAdapter(getActivity().getApplicationContext(),images);
You have passed the application context while you need just Context from Activity. So change that to:
mAdapter=new GalleryAdapter(getActivity(),images); // remove the method getApplicationContext
Try doing that if it will work or else lets try finding more code that may bring a problem.