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
Related
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!
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.
Getting Error while sharing a news on whatsapp using my Webview App
**package com.agraleaks.imgauravanimator;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.View;
import android.graphics.Bitmap;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import com.agraleaks.imgauravanimator.Common.Config;
public class MainActivity extends AppCompatActivity implements OnRefreshListener {
private WebView webView;
private ProgressDialog dialog;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private SwipeRefreshLayout swipeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
//WebView
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.imageView1).setVisibility(View.GONE);
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
}
});
webView.loadUrl("http://www.agraleaks.com/");
webView.setHorizontalScrollBarEnabled(false);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(128);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Config.STR_PUSH))
{
String message = intent.getStringExtra(Config.STR_PUSH);
showNotification ("Agra Leaks- Fastest News Channel in the City",message);
}
}
};
onNewIntent(getIntent());
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
if(url != null && url.startsWith("whatsapp://"))
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Agra Leaks - Digital Newspaper.");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
return true;
}else
{
return false;
}
}
private void showNotification(String title, String message) {
Intent intent = new Intent(getBaseContext(),MainActivity.class);
intent.putExtra(Config.STR_KEY,message);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getBaseContext());
builder.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(message)
.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager)getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN){
switch (keyCode){
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()){
webView.goBack();
}
else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,new IntentFilter("registrationComplete"));
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,new IntentFilter(Config.STR_PUSH));
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override public void run() {
// webView.reload();
swipeLayout.setRefreshing(false);
webView.loadUrl( "javascript:window.location.reload( true )" );
}
}, 5000);
}
}**
These are my code
Unable to share on Whatsapp from my WebView. Getting Error - The webpage at whatsapp://send?text= could not be load because net::ERR_UNKNOWN_URL_SCHEME.
here is my activity_main
<?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="com.agraleaks.imgauravanimator.MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v4.widget.SwipeRefreshLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/splash" />
<ProgressBar
android:id="#+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true" />
</RelativeLayout>
i found my Answer myself ,
i just need to put these codes
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url != null && url.startsWith("whatsapp://"))
{
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Moon TV");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);return true;
}else
{
return false;
}
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.
Hi I used firebase login to get Google Sign in to work on my app. My group and I have been having an issue for the past couple weeks. We don't know how to change screens to a new activity after the user signs in.
This is our MainActivity.java code
package com.plannerangelica.tmr;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import static com.plannerangelica.tmr.R.styleable.View;
public class MainActivity extends AppCompatActivity {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
public static final String ANONYMOUS = "anonymous";
private String mUsername;
private String mPhotoUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add these just after setContentView(R.layout.activity_main);
// Initialize Firebase Auth
mUsername = ANONYMOUS;
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if (mFirebaseUser == null) {
// Not signed in, launch the Sign In activity
startActivity(new Intent(this, SignInActivity.class));
finish();
return;
} else {
mUsername = mFirebaseUser.getDisplayName();
if (mFirebaseUser.getPhotoUrl() != null) {
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
Log.i("User Name:", mUsername);
}
}
}
and SignInActivity.java
package com.plannerangelica.tmr;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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;
public class SignInActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
private SignInButton mSignInButton;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mFirebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
// Assign fields
mSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
// Set click listeners
mSignInButton.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Initialize FirebaseAuth
mFirebaseAuth = FirebaseAuth.getInstance();
}
private void handleFirebaseAuthResult(AuthResult authResult) {
if (authResult != null) {
// Welcome the user
FirebaseUser user = authResult.getUser();
Toast.makeText(this, "Welcome " + user.getEmail(), Toast.LENGTH_SHORT).show();
// Go back to the main activity
startActivity(new Intent(this, MainActivity.class));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
default:
return;
}
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// Google Sign In failed
Log.e(TAG, "Google Sign In failed.");
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mFirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(SignInActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
}
}
});
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
}
and activity_sign_in.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sign_in_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:text="sign_in"/>
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
android:layout_gravity="center"/>
</FrameLayout>
Use this
startActivity(new Intent(this, activity_sign_in.class));
after the user is signed in i.e. inside this
else {
mUsername = mFirebaseUser.getDisplayName();
if (mFirebaseUser.getPhotoUrl() != null) {
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
Log.i("User Name:", mUsername);
}