I'm currently creating my own application with Android Studio. In this app, I want to create a switch, that changes to dark mode and back.
In the MainActivity.java I'm using the following code
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
public class MainActivity extends AppCompatActivity {
private Button button;
private Switch aSwitch;
public static final String MyPREFERENCES = "nightModePrefs";
public static final String KEY_ISNIGHTMODE = "isNightMode";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button feed = findViewById(R.id.feed);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
aSwitch = findViewById(R.id.day_night);
checkNightModeActivated();
aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
saveNightModeState(true);
recreate();
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
saveNightModeState(true);
recreate();
}
});
feed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Newsfeed.class));
}
});
}
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
private void checkNightModeActivated() {
if(sharedpreferences.getBoolean(KEY_ISNIGHTMODE, false)) {
aSwitch.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else{
aSwitch.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
The problem is, that the switch will change the mode to dark when I've started the app. But then, the app beginns to flicker and does not longer responds.
Can soneone please tell me, what I'm doing wrong?
Kind regards
Kai
I've found a solution for my problem.
private Switch day_night;
day_night=findViewById(R.id.day_night);
day_night.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else {
getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
});
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 want to save some data from the dialog to use it in my app, but after enetering the data and going to the next step my app is crushing instantly (after pressing on Create).So i'm practicing with a textView(fragment layout). What should i do, bcs i didn't manage even with an method or class .Actually my purpose is to print in the text ,the input without crashing.
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class Passwords_Fragment extends Fragment {
FloatingActionButton floating_button;
AlertDialog dialog;
TextView text;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_passwords_, container, false);
floating_button=view.findViewById(R.id.floatingActionButton);
buildDialog();
floating_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.show();
}
});
return view;
}
private void buildDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
View view = getLayoutInflater().inflate(R.layout.dialog,null);
EditText name_of_platform=view.findViewById(R.id.platform_name);
EditText name_of_password=view.findViewById(R.id.password_name);
builder.setView(view)
.setTitle("Save a new password")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
addItem(name_of_platform.getText().toString()); // my app crashes here
}
});
dialog=builder.create();
}
private void addItem(String name){
View view = getLayoutInflater().inflate((R.layout.item),null);
TextView text= view.findViewById(R.id.textView2);
text.setText(name);
}
}```
My error at Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.passowrdgenerator.Passwords_Fragment.buildDialog(Passwords_Fragment.java:65)
at com.example.passowrdgenerator.Passwords_Fragment.onCreateView(Passwords_Fragment.java:32)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1808)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7898)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
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
I'm currently working on a mobile app as a final project for my course. I have these two fragments inside a ViewPager2 controlled by a TabLayout. There are buttons inside of these fragments.
The first frag contains 2 buttons. The other frag has only one button. I want them to open an activity but the problem is when I run the app, these buttons won't work. They didn't open the other activity.
Login Fragment
package com.example.biowit;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
public class LoginTabFragment extends Fragment {
EditText email, password;
Button btn_login, btn_forpass;
TextView textView;
float v=0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_fragment, container, false);
email = root.findViewById(R.id.input_LI_email);
password = root.findViewById(R.id.input_LI_pass);
btn_forpass = root.findViewById(R.id.btn_FPass);
btn_login = root.findViewById(R.id.btn_LIn);
email.setTranslationX(800);
password.setTranslationX(800);
btn_forpass.setTranslationX(800);
btn_login.setTranslationX(800);
email.setAlpha(v);
password.setAlpha(v);
btn_forpass.setAlpha(v);
btn_login.setAlpha(v);
email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
password.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_forpass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeScreen.class);
startActivity(intent);
Animatoo.animateFade(getActivity());
getActivity().finish();
}
});
return root;
}
}
LoginScreen (where the fragment locates)
package com.example.biowit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class
LoginScreen extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager;
float v=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
LoginAdapter login_adapter = new LoginAdapter(this);
viewPager.setAdapter(login_adapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0:
tab.setText("LOGIN");
break;
case 1:
tab.setText("SIGNUP");
break;
}
}
}).attach();
tabLayout.setAlpha(v);
}
}
Here's the error log(?)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.biowit, PID: 18551
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.biowit/com.example.biowit.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.biowit.HomeScreen.onCreate(HomeScreen.java:22)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
HomeScreen (Activity that supposedly open when clicking the button)
package com.example.biowit;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class HomeScreen extends AppCompatActivity {
Button Chap1_btn, Achieve_btn, HowToPlay_btn, LogOut_btn, Settings_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide(); // hides the action bar.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Chap1_btn = findViewById(R.id.btn_Chap1);
Achieve_btn = findViewById(R.id.btn_Achievements);
HowToPlay_btn = findViewById(R.id.btn_HowToPlay);
LogOut_btn = findViewById(R.id.btn_Logout);
Settings_btn = findViewById(R.id.btn_Settings);
Chap1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Chap1 = new Intent(getApplicationContext(), LessonScreen.class);
startActivity(open_Chap1);
}
});
Achieve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_Achievements = new Intent(getApplicationContext(), Achievements.class);
}
});
HowToPlay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_HowToPlay = new Intent(getApplicationContext().HowToPlay.class);
}
});
LogOut_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Settings = new Intent(getApplicationContext(), Settings.class);
startActivity(open_Settings);
}
});
}
}
getSupportActionBar().hide(); is what's causing the error. You have added it before
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
So it's trying to execute it before the activity is initialised.
Add it after the above 2 lines and it should work.
I have a problem with comunication between my phone and wear device. I decided to add wear module to my app. Wear app has just one class (MainActivity)
package cz.johrusk.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
public class MainActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener,DataApi.DataListener {
GoogleApiClient mGoogleApiClient;
private TextView mTextView;
static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
Log.d(TAG, "onConnected: " + connectionHint);
sendNumber(1);
Log.d(TAG,"BBBBBBBB");
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
})
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
Log.d(TAG,"mGoogleApiClient connected;");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG,"FAILE" + connectionResult);
}
public void sendNumber(int number) {
PutDataMapRequest putDataMapRequest = PutDataMapRequest.create("/number");
putDataMapRequest.getDataMap().putInt("number",number);
putDataMapRequest.getDataMap().putLong("Time",System.currentTimeMillis());
PutDataRequest putDataReq = putDataMapRequest.asPutDataRequest();
putDataReq.setUrgent();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataReq)
.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(#NonNull DataApi.DataItemResult dataItemResult) {
if (!dataItemResult.getStatus().isSuccess()) {
Log.d(TAG,"Fail");
}
else{
Log.d(TAG,"Succes");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d(TAG,"TEST");
}
}
I quess that "Wearable.DataApi.putDataItem" should call WearableListenerService in my phone app. Here is that service:
package cz.johrusk.showsmscode.service;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import com.google.android.gms.wearable.WearableListenerService;
public class WatchListener_service extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
Log.d("prijato","number is: ");
for (DataEvent dataEvent : dataEventBuffer) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
String path = dataEvent.getDataItem().getUri().getPath();
if (path.equals("/number")){
int number = dataMap.getInt("numa");
long time = dataMap.getInt("timestamp");
Log.d("received","number is: " + number);
}
}
}
}
}
However, onDataChanged method in WatchListener_service isn't called. onResult method inside ResultCallbacks print "Succes" so it seems that DataItem is send correctly.
I already find many similar problems on Stackoverlflow so I checked all these things:
Both modules has same applicationId
Both modules use 'com.google.android.gms:play-services-wearable:9.0.0'
SetUrgent is used to putDataRequest so there shouldnt be any delay.
WearableListenerService has declared correct intent filter in Manifest :
action android:name="com.google.android.gms.wearable.DATA_CHANGED"
data android:scheme="wear" android:host="*"
Both phone and Wear app run on physical device. My question is... What should I do to fix this issue?
Thanks
Check if both apps have the same debug key. I had some problems with that and problem was different keys for both apps (wear and mobile).
PS: The Android Wear API is ridiculous. I quit developing for Wear because of how terrible is that API that doest not work as they say this should.