I followed this tutorial https://morioh.com/p/10dc2d87bb2f but despite doing everything the same i get the following error:
error: cannot find symbol
mAuth.signInWithCredential(authCredential).addOnCompleteListener( MainActivity.his,new onCompleteListener() {
^
symbol: variable his
location: class MainActivity
I tried changing the cersions of play-services and firebase-auth/core but nothing changed.
My MainActivity.java:
package com.imoroney.easylearn;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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.SignInButton;
import com.google.android.gms.common.api.ApiException;
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;
import com.google.android.gms.tasks.OnCompleteListener;
public class MainActivity extends AppCompatActivity {
private SignInButton signInButton;
private GoogleSignInClient mGoodleSignInClient;
private String TAG = "MainActivity";
private FirebaseAuth mAuth;
private Button btnSignOut;
private int RC_SIGN_IN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.sign_in_button);
mAuth = FirebaseAuth.getInstance();
btnSignOut = findViewById(R.id.sign_out_button);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
mGoodleSignInClient = GoogleSignIn.getClient(this,gso);
signInButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
signIn();
}
});
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGoodleSignInClient.signOut();
Toast.makeText(MainActivity.this,"You Are Signed Out", Toast.LENGTH_SHORT).show();
btnSignOut.setVisibility(View.INVISIBLE);
}
});
}
private void signIn(){
Intent signInIntent = mGoodleSignInClient.getSignInIntent();
startActivityForResult(signInIntent,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);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask){
try {
GoogleSignInAccount acc = completedTask.getResult(ApiException.class);
Toast.makeText(MainActivity.this,"Signed In Successfully", Toast.LENGTH_SHORT).show();
FirebaseGoogleAuth(acc);
}
catch (ApiException e){
Toast.makeText(MainActivity.this,"Sign In Failed", Toast.LENGTH_SHORT).show();
FirebaseGoogleAuth(null);
}
}
private void FirebaseGoogleAuth(GoogleSignInAccount acct){
AuthCredential authCredential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
mAuth.signInWithCredential(authCredential).addOnCompleteListener( MainActivity.his,new onCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task){
if(task.isSuccessful()){
Toast.makeText(MainActivity.this,"Successful", Toast.LENGTH_SHORT).show();
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
}
else{
Toast.makeText(MainActivity.this,"Failed", Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
private void updateUI(FirebaseUser fUser){
btnSignOut.setVisibility(View.VISIBLE);
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
if(account != null){
String personName = account.getDisplayName();
String personGivenName = account.getGivenName();
String personFamilyName = account.getFamilyName();
String personEmail = account.getEmail();
String personId = account.getId();
Uri personPhoto = account.getPhotoUrl();
Toast.makeText(MainActivity.this, personName + personEmail, Toast.LENGTH_SHORT).show();
}
}
}
My build gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.imoroney.easylearn"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-auth:19.3.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.firebase:firebase-core:17.5.0'
implementation 'com.google.android.gms:play-services-auth:18.1.0'
implementation 'com.google.firebase:firebase-messaging:20.2.4'
}
Related
package com.example.bookapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bookapp.databinding.ActivityLoginBinding;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
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;
public class LoginActivity extends AppCompatActivity {
private ActivityLoginBinding binding;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private Button BtnLogin;
private EditText TxtEmail;
private EditText TxtPassword;
private TextView singUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = firebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
BtnLogin =(Button) findViewById(R.id.loginBtn);
singUp =(TextView) findViewById(R.id.noAccountTv);
singUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
});
BtnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
validateData();
}
});
}
private String email = "", password = "";
private void validateData() {
TxtEmail =(EditText) findViewById(R.id.emailet);
email =TxtEmail.getText().toString().trim();
TxtPassword = (EditText) findViewById(R.id.passwordet);
password = TxtPassword.getText().toString().trim();
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
Toast.makeText(this, "Invalid Email Pattern..!", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password))
{
Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
}
else
{
loginUser();
}
}
private void loginUser()
{
progressDialog.setMessage("Logging In");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,password)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
checkUser();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure( Exception e) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void checkUser()
{
progressDialog.setMessage("Checking User..");
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot)
{
progressDialog.dismiss();
String userType = ""+snapshot.child("userType").getValue();
if(userType.equals("user"))
{
Intent i = new Intent(LoginActivity.this,DashboardUserActivity.class);
startActivity(i);
finish();
}
else if(userType.equals("admin"))
{
Intent i = new Intent(LoginActivity.this,DashboardAdminActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
}
Application is unable to move to the DashboardAdminActivity/DashboardUserActivity while progressbar is showing & email and password validation is also working, but it's not going to the next activities according to the "usertype".
I also tried intent another way, but it's not working, if you guys can find any error/correction in my code, it would be appreciated.
I have created a movie app the app is almost complete but there is one shortcoming where if users click one particular category they have to see all the details of that particular category. I'm new to android so I don't know how to implement this. one of them told we can use sql fetch but i have used retro fit so i dont want to change my backend from json to sql .
I have tried a similar question but did not work uploading my main activity, adapter model class and JSON file data
Mainacivity.Java
package com.example.movieapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Filter;
import com.example.movieapp.adapter.BannerMoviesPagerAdapter;
import com.example.movieapp.adapter.ItemRecyclerAdapter;
import com.example.movieapp.adapter.MainRecyclerAdapter;
import com.example.movieapp.listener.OnItemClickLIstener;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.BannerMovies;
import com.example.movieapp.model.CategoryItemList;
import com.example.movieapp.retrofit.RetrofitClient;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
BannerMoviesPagerAdapter bannerMoviesPagerAdapter;
TabLayout IndicatorTab,categoryTab;
ViewPager bannerMoviesViewpager;
List<BannerMovies> homeBannerList;
List<BannerMovies> tvBannerList;
List<BannerMovies> songBannerList;
List<BannerMovies> audioBannerList;
NestedScrollView nestedScrollView;
AppBarLayout appBarLayout;
MainRecyclerAdapter mainRecyclerAdapter;
ItemRecyclerAdapter itemRecyclerAdapter;
RecyclerView mainRecycler;
List<AllCategory> allCategoryList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding this line will prevent taking screenshot in your app
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
IndicatorTab =findViewById(R.id.tab_indicator);
categoryTab =findViewById(R.id.tabLayout);
nestedScrollView =findViewById(R.id.nested_scroll);
appBarLayout =findViewById(R.id.appbar);
homeBannerList=new ArrayList<>();
tvBannerList=new ArrayList<>();
songBannerList=new ArrayList<>();
audioBannerList=new ArrayList<>();
getBannerData();
getAllMoviesData(1);
categoryTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()){
case 1:
setBannerMoviesPagerAdapter(tvBannerList);
getAllMoviesData(2);
return;
case 2:
setBannerMoviesPagerAdapter(songBannerList);
getAllMoviesData(3);
return;
case 3:
setBannerMoviesPagerAdapter(audioBannerList);
getAllMoviesData(4);
return;
default:
setBannerMoviesPagerAdapter(homeBannerList);
getAllMoviesData(1);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
//titles
allCategoryList=new ArrayList<>();
}
private void setBannerMoviesPagerAdapter(List<BannerMovies> bannerMoviesList) {
bannerMoviesViewpager = findViewById(R.id.banner_viewPager);
bannerMoviesPagerAdapter = new BannerMoviesPagerAdapter(this, bannerMoviesList);
bannerMoviesViewpager.setAdapter(bannerMoviesPagerAdapter);
IndicatorTab.setupWithViewPager(bannerMoviesViewpager);
}
public void setMainRecycler(List<AllCategory>allCategoryList){
mainRecycler=findViewById(R.id.main_recycler);
RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(this,RecyclerView.VERTICAL,false);
mainRecycler.setLayoutManager(layoutManager);
mainRecyclerAdapter =new MainRecyclerAdapter(this,allCategoryList);
mainRecycler.setAdapter(mainRecyclerAdapter);
}
private void getBannerData()
{
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllBanners()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<List<BannerMovies>>() {
#Override
public void onNext(List<BannerMovies> bannerMovies) {
for ( int i=0; i < bannerMovies.size(); i++ )
{
if(bannerMovies.get(i).getBannerCategoryId().toString().equals("1"))
{
homeBannerList.add(bannerMovies.get(i));
} else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("2"))
{
tvBannerList.add(bannerMovies.get(i));
} else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("3"))
{
songBannerList.add(bannerMovies.get(i));
} else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("4"))
{
audioBannerList.add(bannerMovies.get(i));
}
else
{
homeBannerList.add(bannerMovies.get(i));
}
}
}
#Override
public void onError(Throwable e) {
Log.d("bannerData",""+e);
}
#Override
public void onComplete() {
setBannerMoviesPagerAdapter(homeBannerList);
}
})
);
}
private void getAllMoviesData(Integer categoryId)
{
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllCategoryMovies(categoryId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<List<AllCategory>>() {
#Override
public void onNext(List<AllCategory> allCategoryList) {
for ( int i=0; i < allCategoryList.size(); i++ )
{
}
setMainRecycler(allCategoryList);
}
#Override
public void onError(Throwable e) {
Log.d("bannerData",""+e);
}
#Override
public void onComplete() {
}
})
);
}
}
Itemrecycleradpater
package com.example.movieapp.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.movieapp.MovieDetails;
import com.example.movieapp.R;
import com.example.movieapp.model.CategoryItemList;
import java.util.ArrayList;
import java.util.List;
public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ItemViewHolder> implements Filterable {
Context context;
private List<CategoryItemList> categoryItemList;
private List<CategoryItemList>allCategoryListFull;
public ItemRecyclerAdapter(Context context, List<CategoryItemList> categoryItemList) {
this.context = context;
this.categoryItemList = categoryItemList;
allCategoryListFull = new ArrayList<>(categoryItemList);
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview_movies,parent,false));
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, final int position) {
Glide.with(context).load(categoryItemList.get(position).getSmallThumb()).placeholder(R.drawable.image12).into(holder.image_item);
holder.image_item.setOnClickListener(view -> {
Intent i = new Intent(context, MovieDetails.class);
i.putExtra("movieId",categoryItemList.get(position).getId());
i.putExtra("movieName",categoryItemList.get(position).getMovieName());
i.putExtra("smallThumb",categoryItemList.get(position).getSmallThumb());
i.putExtra("movieImageUrl",categoryItemList.get(position).getImageUrl());
i.putExtra("movieFile",categoryItemList.get(position).getFileUrl());
i.putExtra("MovieDesc",categoryItemList.get(position).getMovieDesc());
i.putExtra("Language",categoryItemList.get(position).getLanguage());
i.putExtra("Singers",categoryItemList.get(position).getSingers());
i.putExtra("TrailerUrl",categoryItemList.get(position).getTrailerUrl());
context.startActivity(i);
});
}
#Override
public int getItemCount() {
return categoryItemList.size();
}
#Override
public Filter getFilter() {
return filterNew;
}
private Filter filterNew = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<CategoryItemList> filteredList = new ArrayList<>();
if(constraint == null || constraint.length() ==0){
filteredList.addAll(allCategoryListFull);
}
else{
String filterPattern = constraint.toString().toLowerCase().trim();
for(CategoryItemList item: allCategoryListFull)
{
if(item.getMovieName().toLowerCase().contains(filterPattern))
{
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
categoryItemList.clear();
categoryItemList.addAll((List)results.values);
notifyDataSetChanged();
}
};
public static final class ItemViewHolder extends RecyclerView.ViewHolder
{
ImageView image_item;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
image_item=itemView.findViewById(R.id.image_item);
}
}
}
package com.example.movieapp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.movieapp.R;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.CategoryItemList;
import java.util.List;
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {
Context context;
private List<AllCategory> allCategoryList;
public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
this.context = context;
this.allCategoryList = allCategoryList;
}
#NonNull
#Override
public MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MainViewHolder holder, int position) {
holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());
setItemRecycler(holder.itemRecycler,allCategoryList.get(position).getCategoryItemList());
}
#Override
public int getItemCount() {
return allCategoryList.size();
}
public static final class MainViewHolder extends RecyclerView.ViewHolder {
TextView categoryName;
RecyclerView itemRecycler;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.item_category);
itemRecycler = itemView.findViewById(R.id.item_recycler);
}
}
private void setItemRecycler(RecyclerView recyclerview, List<CategoryItemList> categoryItemList) {
ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context,categoryItemList);
recyclerview.setLayoutManager(new LinearLayoutManager(context,RecyclerView.HORIZONTAL,false));
//recyclerview.setLayoutManager(new GridLayoutManager(context,3));
recyclerview.setAdapter(itemRecyclerAdapter);
}
}
package com.example.movieapp.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.movieapp.R;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.CategoryItemList;
import java.util.List;
public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {
Context context;
private List<AllCategory> allCategoryList;
public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
this.context = context;
this.allCategoryList = allCategoryList;
}
#NonNull
#Override
public MainViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull MainViewHolder holder, int position) {
// Here is your call to an individual item or object like category name
holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Stuff to open new activity
List<CategoryItemList> categoryItemList = allCategoryList.get(position).getCategoryItemList()
Intent i = new Intent(context, MopvieList.class); //New screen
i.putExtra("itemList", categoryItemList); //passing serializable object
//NOTE: CategoryItemList class must implement Serializable
}
});
setItemRecycler(holder.itemRecycler, allCategoryList.get(position).getCategoryItemList());
}
#Override
public int getItemCount() {
return allCategoryList.size();
}
public static final class MainViewHolder extends RecyclerView.ViewHolder {
TextView categoryName;
RecyclerView itemRecycler;
public MainViewHolder(#NonNull View itemView) {
super(itemView);
categoryName = itemView.findViewById(R.id.item_category);
itemRecycler = itemView.findViewById(R.id.item_recycler);
}
}
private void setItemRecycler(RecyclerView recyclerview, List<CategoryItemList> categoryItemList) {
ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context, categoryItemList);
recyclerview.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
//recyclerview.setLayoutManager(new GridLayoutManager(context,3));
recyclerview.setAdapter(itemRecyclerAdapter);
}
}
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<CategoryItemList> categoryItemList = allCategoryList.get(position).getCategoryItemList();
Intent i = new Intent(context, MovieCat.class); //my activity for showing all category
i.putExtra("itemList", (Serializable) categoryItemList);
context.startActivity(i);
}
public class AllCategory implements Serializable {}// as instructed made it serializable.
public class MovieCat extends AppCompatActivity {
TextView MovieCat;
String movieNameCat;
ArrayList<CategoryItemList> catItems;
RecyclerView recyclerView;
MainRecyclerAdapter mainRecyclerAdapter;
Button button;
String cat; //for item_list intent
String catId;// for intent
int categoryId;// for get all movies data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_cat);
MovieCat = findViewById(R.id.textView2);
movieNameCat = getIntent().getStringExtra("categoryTitle");
cat = getIntent().getStringExtra("itemList");
button=findViewById(R.id.view_all_btn);
MovieCat.setText(movieNameCat);
catId = getIntent().getStringExtra("categoryId"); getAllMoviesData(categoryId);
getAllMoviesData(categoryId);
}
private void getAllMoviesData(int categoryId) {
{
CompositeDisposable compositeDisposable = new CompositeDisposable();
compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllCategoryMovies(categoryId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<List<AllCategory>>() {
#Override
public void onNext(List<AllCategory> itemList) {
for (int i = 0; i < itemList.size(); i++) {
setMainRecycler(itemList);
}
}
#Override
public void onError(Throwable e) {
Log.d("bannerData", "" + e);
}
#Override
public void onComplete() {
}
})
);
}
}
public void setMainRecycler(List<AllCategory> catItems) {
recyclerView = findViewById(R.id.item_cycle);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
mainRecyclerAdapter = new MainRecyclerAdapter(this, catItems);
recyclerView.setAdapter(mainRecyclerAdapter);
}
Updated my code
#KGeeks
adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );This Line Generates Error & my knowlwdge is quite low about this error. the both required java file & the detailed error is given after this two java files.
ImageAdapter.java
package com.example.login;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
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.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context Context;
private List<Upload> Uploads;
private OnItemClickListener Listener;
public ImageAdapter (Context context, List<Upload> uploads1){
Context = context;
Uploads = uploads1;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent,int viewType) {
View v= LayoutInflater.from(Context).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder,int position) {
Upload uploadCurrent= Uploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.with(Context)
.load(uploadCurrent.getImageUrl())
.placeholder(R.drawable.logo)
.fit()
.centerInside()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return Uploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_product_name);
imageView = itemView.findViewById(R.id.product_image);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
Listener.OnItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem details = menu.add(Menu.NONE ,1,1,"Details");
MenuItem delete = menu.add(Menu.NONE ,2,2,"Delete");
details.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if(Listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch(item.getItemId()){
case 1:
Listener.OnDetailsClick(position);
return true;
case 2:
Listener.OnDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener{
void OnItemClick(int Position);
void OnDetailsClick(int Position);
void OnDeleteClick(int Position);
}
public void SetOnClickItemListener(OnItemClickListener listener){
Listener = listener;
}
}
MyAddsFragment.java
package com.example.login.ui.login;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.login.ImageAdapter;
import com.example.login.R;
import com.example.login.Upload;
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 MyAddsFragment extends Fragment implements ImageAdapter.OnItemClickListener{
private RecyclerView recyclerView;
private ImageAdapter adapter;
private ProgressBar progressBar;
private DatabaseReference databaseRef;
private List<Upload> Uploads;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_myadds, container, false);
recyclerView = v.findViewById(R.id.Recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressBar = v.findViewById(R.id.progress_bar_1);
Uploads = new ArrayList<>();
databaseRef = FirebaseDatabase.getInstance().getReference("uploads");
databaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot){
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Upload upload = postSnapshot.getValue(Upload.class);
Uploads.add(upload);
}
adapter = new ImageAdapter(getActivity(), Uploads);
recyclerView.setAdapter(adapter);
adapter.SetOnClickItemListener((ImageAdapter.OnItemClickListener) getActivity());
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
return v;
}
#Override
public void OnItemClick(int Position) {
Toast.makeText(getActivity(),"Normal Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDetailsClick(int Position) {
Toast.makeText(getActivity(),"Details Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
#Override
public void OnDeleteClick(int Position) {
Toast.makeText(getActivity(),"Delete Click Position:"+Position,Toast.LENGTH_SHORT).show();
}
}
Error is Given below
01-24 12:33:27.072 6252-6252/com.example.login E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.login, PID: 6252
java.lang.ClassCastException: com.example.login.HomeActivity cannot be cast to com.example.login.ImageAdapter$OnItemClickListener
at com.example.login.ui.login.MyAddsFragment$1.onDataChange(MyAddsFragment.java:57)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.0:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
....................................................................................................
your class MyAddsFragment is implementing the ImageAdapter.OnItemClickListener so to set adapter.SetOnClickItemListener you can simple use below code -
adapter.SetOnClickItemListener(MyAddsFragment.this)
You can not cast ImageAdapter.OnItemClickListener to HomeActicity.class as it might not implementing it.
I'm writing a utility method to extract an array of wrapped unparcelable objects:
public interface UnparcelableHolder<U> {
#Nullable U getUnparcelable();
}
public final class FragmentUtil {
#Nullable
public static <U> List<U> getUnparcelableHolderListArgument(
#Nonnull Fragment fragment,
#Nonnull Class<UnparcelableHolder<U>> unparcelableHolderClass,
#Nonnull String key
) {
#Nullable final Bundle arguments = fragment.getArguments();
if (arguments == null) {
return null;
} else {
#Nullable final Parcelable[] parcelableArray = arguments.getParcelableArray(key);
if (parcelableArray == null) {
return null;
} else {
return Arrays
.stream(parcelableArray)
.filter(unparcelableHolderClass::isInstance)
.map(unparcelableHolderClass::cast)
.filter(Objects::nonNull)
.map(UnparcelableHolder::getUnparcelable)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
if (unparcelableHolderClass.isInstance(parcelable)) {
#Nonnull final UnparcelableHolder<U> unparcelableHolder =
Objects.requireNonNull(unparcelableHolderClass.cast(parcelable));
return unparcelableHolder.getUnparcelable();
} else {
return null;
}
}
}
}
Android Studio is warning me that my .map(UnparcelableHolder::getUnparcelable) call might cause a NullPointerException. This shouldn't be possible because of my preceding filter(Objects::nonNull) call. How do I tell Android Studio's inspector that my code is clean?
This is an MCVE is available on github built with Android Studio 3.4 beta 2:
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.github.hborders.streamsnonnulljsr305"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.code.findbugs:jsr305:3.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
MainActivity.java:
package com.github.hborders.streamsnonnulljsr305;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class MainActivity extends AppCompatActivity {
class Foo {
#Nonnull
private final String string;
Foo(#Nonnull String string) {
this.string = string;
}
#Nonnull
String getString() {
return string;
}
}
class Bar {
#Nullable
private final Foo foo;
Bar(#Nullable Foo foo) {
this.foo = foo;
}
#Nullable
Foo getFoo() {
return foo;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Bar bar1 = new Bar(new Foo("foo"));
final Bar bar2 = new Bar(null);
final Bar[] bars = new Bar[]{
null,
bar1,
bar2,
};
final List<String> strings = Arrays
.stream(bars)
.map(Bar::getFoo)
.filter(Objects::nonNull)
.map(Foo::getString)
.collect(Collectors.toList());
System.out.println("strings: " + strings);
}
}
The same problem occurs on the .map(Foo::getString) call. Ironically, Android studio doesn't complain about my .map(Bar::getFoo) call despite that definitely throwing a NullPointerException.
It's an Android Studios bug as none of Android Studios suggestions work here.
No warning:
Apply suggestion and get the warning:
It also suggests to insert .filter(Objects::nonNull) step when it is already there.
So it's a definite AS bug.
This is a true MCVE for this issue:
import android.support.annotation.Nullable; // or any nullable you care to use
import java.util.Arrays;
import java.util.Objects;
public class MCVE {
class Foo {
}
class Bar {
#Nullable
private final Foo foo;
Bar(#Nullable Foo foo) {
this.foo = foo;
}
#Nullable
Foo getFoo() {
return foo;
}
}
public void mcve() {
final Bar[] bars = new Bar[]{
new Bar(new Foo()),
};
Arrays.stream(bars)
.map(Bar::getFoo)
.filter(Objects::nonNull)
.map(Foo::toString);
}
}
I'm a beginner to android studio. I'm trying to build an my project app that can send my location to another client with just one click. i.e through online server.
At first I'm trying to test if my button gets the latitude and longitude value from the LocationListener.
below is my mainActivity
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
private String myLoc = " ";
GoogleMap mMap;
Button bShare;
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final double Shillong_Lat = 25.5667,
Shillong_Lng = 91.8833;
private GoogleApiClient mLocationClient;
private com.google.android.gms.location.LocationListener mListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 1000, this);
if (servicesOK() ){
setContentView(R.layout.activity_map);
bShare = (Button) findViewById(R.id.bShare);
bShare.setOnClickListener(this);
if(initMap()) {
Toast.makeText(MainActivity.this, "Ready to map", Toast.LENGTH_SHORT).show();
gotoLocation(Shillong_Lat, Shillong_Lng, 15 );
mMap.setMyLocationEnabled(true);
}else{
Toast.makeText(this, "Map not Connected!", Toast.LENGTH_SHORT).show();
}
}else {
setContentView(R.layout.activity_main);
}
}
private void gotoLocation(double latitude, double longitude, float zoom) {
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(
latLng, zoom);
mMap.moveCamera(update);
}
public boolean servicesOK(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(isAvailable == ConnectionResult.SUCCESS){
return true;
}else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, ERROR_DIALOG_REQUEST);
dialog.show();
}else {
Toast.makeText(this, "Can't connect to map", Toast.LENGTH_SHORT).show();
}return false;
}
private boolean initMap() {
if (mMap == null){
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFragment.getMap();
}
return(mMap != null);
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MainActivity.this, "Location changed: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
myLoc = GetAddressDetailed(latitude, longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.bShare){
Toast.makeText(MainActivity.this, "Sent: " + myLat + ", " + myLon ,Toast.LENGTH_SHORT).show();
}
}
}