Animation for activity(intent) - java

my promblem is : i cant use animition for intent becuse this calss extend recyclerView adapter i know overridePendingTransition();but its dont work for tis class
It does not know => overridePendingTransition(R.layout.one,R.layout.two);
public class ListAdapterw extends RecyclerView.Adapter {
List<cardViewhomeinfo> sliders;
ImageLoader imageLoader=ImageLoader.getInstance();
public ListAdapterw(List<cardViewhomeinfo> sliders) {
this.sliders = sliders;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view=inflater.inflate(R.layout.recycleview_home,parent,false);
return new Holder(view);
}
#Override
public void onBindViewHolder(Holder holder, int position) {
holder.title.setText(sliders.get(position).getTitle());
holder.id=sliders.get(position).getId();
imageLoader.displayImage("http://wwwww"+sliders.get(position).getPicture(),holder.pic);
}
#Override
public int getItemCount() {
return sliders.size();
}
public class Holder extends RecyclerView.ViewHolder{
public TextView title;
public ImageView pic;
public String id="";
CardView cardView;
public Holder(final View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.TitleCardView_home);
pic=(ImageView)itemView.findViewById(R.id.imageCardView_home);
cardView= (CardView) itemView.findViewById(R.id.cardView);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(itemView.getContext(),subCat.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("id",id);
overridePendingTransition(R.layout.one,R.layout.two);
itemView.getContext().startActivity(intent);
}
});
}
}
}
and my activtity
public class Home extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view= inflater.inflate(R.layout.fragment_home, container, false);
JSON();
return view;
}
private void JSON() {
final RecyclerView recyclerView1 = (RecyclerView) view.findViewById(R.id.recycle_home);
StringRequest request=new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
List<cardViewhomeinfo> sliders = new ArrayList<>();
JSONArray jsonArray=new JSONArray(s);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
cardViewhomeinfo slider = new cardViewhomeinfo();
slider.setTitle(jsonObject.getString("title"));
slider.setPicture(jsonObject.getString("pic"));
slider.setId(jsonObject.getString("id"));
sliders.add(slider);
}
ListAdapterw adapter = new ListAdapterw(sliders);
recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
recyclerView1.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
dialog();
}
});
Volley.newRequestQueue(getActivity().getApplicationContext()).add(request);
}
private void dialog() {
Toast.makeText(getActivity().getApplicationContext(),"No INTENT",Toast.LENGTH_LONG).show();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Home");
}
}
and subActivty
public class subCat extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_cat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
final String idCat = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(),idCat,Toast.LENGTH_LONG).show();}

Put your overridePendingTransition(R.layout.one,R.layout.two); code into the onCreate of the activity that you're going to when you click on cardView.
It should be something like this in your onCreate method of the activity:
public class subCat extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_cat);
overridePendingTransition(R.layout.one,R.layout.two); //Put it here.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
final String idCat = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(),idCat,Toast.LENGTH_LONG).show();
}
Remove overridePendingTransition(R.layout.one,R.layout.two); this from the adapter class of your recycler view.

On the other hand,
overridePendingTransition(R.layout.one,R.layout.two);
it should be called
after finish();
or
after startActivity();

Related

Firebase firestore Recycle View in fragment. How to do delete on slide

I'm working on my school project with Firebase firestore and firebase Auth. It's something like a Kanban app.
My intend is to add delete documents from database while slide, and move documents to another catalog while sliding left-right. My main activity (TestActivity) is tabbed, so I want the deletion or moving to depend on direction and actual tab. Each tab have own Recycle View. You know: To do, In progress, Done.
I tried to follow Code Flow: https://www.youtube.com/watch?v=ub6mNHWGVHw&list=PLrnPJCHvNZuAXdWxOzsN5rgG2M4uJ8bH1
but my project need fragments, and with them, his "NoteAdapter" doesn't work. I found this tutorial: https://www.youtube.com/watch?v=FFHuYcB3YnU
and used it to place the adapter in right fragment.
Everything works until I want to do something with the firebase documents. This doesn't work at all or I just don't have idea where to place it:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
Im using firebase and fragments first time.
Here comes some of my code: TestActivity (my main, I have also a drawer with user info and signout button, but this button which doesn't work,too):
public class TestActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private TabLayout tabLayout;
private ViewPager viewPager;
private SectionsPagerAdapter adapter;
private DrawerLayout drawer;
FirebaseAuth mAuth;
FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Toolbar toolbar = findViewById(R.id.toolbar); // toolbar staje sie action bar
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
updateNavHeader();
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new TodoFragment(), "To Do");
adapter.AddFragment(new InprogressFragment(), "In Progress");
adapter.AddFragment(new DoneFragment(), "Done");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.add_todo);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Add new item", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
updateUI();
}
});
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// po zalogowaniu dane w drawer sie zmienia
public void updateNavHeader() {
NavigationView navigationView =(NavigationView) findViewById(R.id.nav_view);
View headerView = navigationView.getHeaderView(0);
TextView navUserName = headerView.findViewById(R.id.nav_username);
TextView navUserEmail = headerView.findViewById(R.id.nav_useremail);
ImageView userAvatar = headerView.findViewById(R.id.nav_useravatar);
navUserName.setText(currentUser.getDisplayName());
navUserEmail.setText(currentUser.getEmail());
if (currentUser.getPhotoUrl() != null) {
Glide.with(this).load(currentUser.getPhotoUrl()).into(userAvatar);
} else {
Glide.with(this).load(R.drawable.userphoto).into(userAvatar);
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
if (item.getItemId() == R.id.nav_signout) {
FirebaseAuth.getInstance().signOut();
Intent loginActivity = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(loginActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void updateUI() {
Intent NewActivity = new Intent(getApplicationContext(), NewActivity.class);
startActivity(NewActivity);
finish();
}
}
TodoFragment:
public class TodoFragment extends Fragment {
private View v;
private RecyclerView recyclerView;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference TodoRef= db.collection("ToDo");
FirebaseAuth mAuth;
String Uemail;
public TodoFragment() {
// Required empty public constructor
}
public static TodoFragment newInstance() {
TodoFragment fragment = new TodoFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
Query q =TodoRef.whereEqualTo("email", Uemail);
FirestoreRecyclerOptions options=new FirestoreRecyclerOptions.Builder<Item>().setQuery(q, Item.class).build();
FirestoreRecyclerAdapter<Item, ItemViewHolder>adapter= new FirestoreRecyclerAdapter<Item, ItemViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ItemViewHolder itemViewHolder, int i, #NonNull Item item) {
itemViewHolder.textViewItem.setText(item.getTextitem());
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
ItemViewHolder viewHolder = new ItemViewHolder(v);
return viewHolder;
}
};
recyclerView.setAdapter(adapter);
adapter.startListening();
}
public static class ItemViewHolder extends RecyclerView.ViewHolder{
TextView textViewItem;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
textViewItem = itemView.findViewById(R.id.item_text);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_todo, container, false);
recyclerView = v.findViewById(R.id.recycler_view_todo);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth=FirebaseAuth.getInstance();
Uemail= mAuth.getCurrentUser().getEmail();
return v;
}
}
My Item class:
public class Item {
private String textitem;
private String email;
public Item(){
//needed
}
public Item(String textitem, String email) {
this.email=email;
this.textitem=textitem;
}
public String getTextitem() {
return textitem;
}
public void setTextitem(String textitem) {
this.textitem = textitem;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
}
And my Section Pager Adapter:
public SectionsPagerAdapter( FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
#Override
public int getCount() {
return titles.size();
}
public void AddFragment(Fragment fragment, String title ){
fragments.add(fragment);
titles.add(title);
}
}
I did my best to find the solution on my own, but I apparently failed.
EDIT:
I finally found out how to handle it.
I moved adapter to independent class again, but with little changes in both fragments and adapter.
My adapter now: (with moving and deleting docs in Firestore)
public class ItemAdapter extends FirestoreRecyclerAdapter<Item, ItemAdapter.NoteHolder> {
public ItemAdapter(#NonNull FirestoreRecyclerOptions<Item> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull NoteHolder holder, int position, #NonNull Item model) {
holder.textViewTitle.setText(model.getTextitem());
}
#NonNull
#Override
public NoteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
parent, false);
return new NoteHolder(v);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
Log.d("Firestore", "DocumentSnapshot successfully deleted!");
}
public void moveItem(int position, CollectionReference ColRef) {
DocumentReference from= getSnapshots().getSnapshot(position).getReference();
DocumentReference to =ColRef.document();
moveFirestoreDocument( from, to);
}
public void moveFirestoreDocument(final DocumentReference fromPath, final DocumentReference toPath) {
fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
toPath.set(document.getData())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("Firestore", "DocumentSnapshot successfully written!");
fromPath.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("Firestore", "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("Firestore", "Error deleting document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("Firestore", "Error writing document", e);
}
});
} else {
Log.d("Firestore", "No such document");
}
} else {
Log.d("Firestore", "get failed with ", task.getException());
}
}
});
}
class NoteHolder extends RecyclerView.ViewHolder {
TextView textViewTitle;
public NoteHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.item_text);
}
}
}
And my Fragment now looks like this:
public class TodoFragment extends Fragment {
private View v;
private RecyclerView recyclerView;
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference TodoRef = db.collection("ToDo");
CollectionReference InProgRef = db.collection("InProgress");
ItemAdapter adapter;
FirebaseAuth mAuth;
String Uemail;
public TodoFragment() {
}
public static TodoFragment newInstance() {
TodoFragment fragment = new TodoFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
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_todo, container, false);
recyclerView = v.findViewById(R.id.recycler_view_todo);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth=FirebaseAuth.getInstance();
Uemail= mAuth.getCurrentUser().getEmail();
setUpRecyclerView(recyclerView);
return v;
}
private void setUpRecyclerView(RecyclerView recyclerView) {
Query q =TodoRef.whereEqualTo("email", Uemail);
FirestoreRecyclerOptions<Item> options = new FirestoreRecyclerOptions.Builder<Item>()
.setQuery(q, Item.class)
.build();
adapter = new ItemAdapter(options);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT|ItemTouchHelper.UP) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int right = 8;
if(direction==right){
adapter.moveItem(viewHolder.getAdapterPosition(),InProgRef);
}else{
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}
}).attachToRecyclerView(recyclerView);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
To sum up:
setUpRecyclerView function neded to get the right Recycler View as an argument, without it there was NullPointer Excepction all the time.
I made a mistake with wrong layout in inflaters, too
Hope it will be usefull for somebody.

How do I send data from fragment to another activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
In my app, i have an activity that have recyclerview inside a fragment and the recycleview retrieve data from cloud store Firebase. I want to open new activity that will retrieve the data according to the link(that display on the recycler view) user has clicked.
How do i get the data and display it in new activity?
From ForumTitle.java > Show ReviewFragment.java > User click a value > Show ForumInterface.java
ForumTitle.java
public class ForumTitle extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
ImageButton IVReview,IVTechnical,IVHardware;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_title);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment selectedFragment = null;
if (v == findViewById(R.id.iBReview)){
selectedFragment = new ReviewFragment();
}
else if (v == findViewById(R.id.iBTech)){
selectedFragment = new TechnicalSupportFragment();
}
else if (v == findViewById(R.id.iBHardware)){
selectedFragment = new HardwareFragment();
}
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,selectedFragment);
transaction.commit();
}
};
IVReview = (ImageButton)findViewById(R.id.iBReview);
IVTechnical = (ImageButton)findViewById(R.id.iBTech);
IVHardware = (ImageButton)findViewById(R.id.iBHardware);
IVReview.setOnClickListener(listener);
IVTechnical.setOnClickListener(listener);
IVHardware.setOnClickListener(listener);
}
}
ReviewFragment.java
public class ReviewFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference userRef = db.collection("Review");
private ForumAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_review,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Query query = userRef.orderBy("DatePosted",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Forum> options = new
FirestoreRecyclerOptions.Builder<Forum>()
.setQuery(query,Forum.class)
.build();
adapter = new ForumAdapter(options);
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.rvReview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ForumAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
Forum forum = documentSnapshot.toObject(Forum.class);
String title = forum.getTitle();
String id = documentSnapshot.getId();
Intent intent = new Intent(getActivity(), ForumInterface.class);
Bundle extras = intent.getExtras();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
startActivity(intent);
}
});
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
ForumInterface.java
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
private CollectionReference userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}
ForumAdapter.java
public class ForumAdapter extends FirestoreRecyclerAdapter<Forum,ForumAdapter.ForumHolder> {
private OnItemClickListener listener;
public ForumAdapter(FirestoreRecyclerOptions<Forum> options) {
super(options);
}
#Override
public void onBindViewHolder(ForumHolder forumHolder, int i, Forum forum) {
forumHolder.textViewTitle.setText(forum.getTitle());
forumHolder.textViewDescription.setText(forum.getDescription());
forumHolder.timeStamp.setText(forum.getDatePosted().toString());
}
#NonNull
#Override
public ForumHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
android.view.View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardviewforumtitle,parent,false);
return new ForumHolder(v);
}
class ForumHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
TextView textViewDescription;
TextView timeStamp;
public ForumHolder(View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.title);
textViewDescription = itemView.findViewById(R.id.description);
timeStamp = itemView.findViewById(R.id.timestamp);
textViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
// NO_POSITION to prevent app crash when click -1 index
if(position != RecyclerView.NO_POSITION && listener !=null ){
listener.onItemClick(getSnapshots().getSnapshot(position),position);
}
}
});
}
}
public interface OnItemClickListener{
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return super.getItemCount();
}
}
With the code above i run it, i got an error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.putString(java.lang.String, java.lang.String)' on a null object reference
at my.edu.fsktm.um.finalproject.Fragment.ReviewFragment$1.onItemClick(ReviewFragment.java:61)
at my.edu.fsktm.um.finalproject.ForumTitle.ForumAdapter$ForumHolder$1.onClick(ForumAdapter.java:56)
The picture of my app
When I clicked the title "GTX 1660 Ti Gaming X"
You try to set content on a Bundle which is null in your ReviewFragment's onClick. Use new Bundle() instead of intent.getExtras(); to instantiate Bundle
Bundle extras = new Bundle();
extras.putString("FORUM_TYPE","Review");
extras.putString("FORUM_ID",id);
extras.putString("TITLE",title);
//You have to set the bundle to intent
intent.putExtras(extras);
startActivity(intent);
Beside this move below code inside onCreate of ForumInterface Activity
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
And here is the complete Activity.
public class ForumInterface extends AppCompatActivity {
private FirebaseFirestore db;
private CollectionReference userRef;
private ForumAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum_interface);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String forum_title = extras.getString("TITLE");
String forum_type = extras.getString("FORUM_TYPE");
String forum_id = extras.getString("FORUM_ID");
db = FirebaseFirestore.getInstance();
userRef = db.collection(forum_type).document(forum_id).collection(forum_title);
TextView test = (TextView)findViewById(R.id.tvForumTitle);
test.setText(forum_title);
}
}

passing data from activity to tabs fragment

Not able to pass the retrived list of data from retrofit to a recyclerview in fragment!
Tried some solutions but not working!
I have tried creating methods in fragment and passing but not working!
Getting null!
Activity
TabLayout tabLayout;
ViewPager viewPager;
RecyclerView recyclerView;
//vars
private Dto dto;
List<Post_DTO> post_dto_list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
dto=new Dto();
UpdateList();
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
tabLayout=(TabLayout)findViewById(R.id.tabLayout);
viewPager=(ViewPager)findViewById(R.id.viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Dashboard"));
tabLayout.addTab(tabLayout.newTab().setText("Converations"));
tabLayout.addTab(tabLayout.newTab().setText("Profile"));
PostFragment pf=new PostFragment();
pf.passData(getApplicationContext(),post_dto_list);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
//ft.add(R.id.posts_recyclerview, ft);
ft.addToBackStack(null);
ft.commit();
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final MyAdapter adapter = new MyAdapter(this,getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println(tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void UpdateList() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(getString(R.string.postUrl))
.addConverterFactory(GsonConverterFactory.create())
.build();
PostsInterface postsInterface =retrofit.create(PostsInterface.class);
Call<Post_DTO_Resp> call= postsInterface.getPosts();
call.enqueue(new Callback<Post_DTO_Resp>() {
#Override
public void onResponse(Call<Post_DTO_Resp> call, Response<Post_DTO_Resp> response) {
//pDialog.dismiss();
if(!response.isSuccessful())
{
Toast.makeText(getApplicationContext(),"Loading the posts!",Toast.LENGTH_SHORT).show();
}
Post_DTO_Resp posts = response.body();
post_dto_list=posts.getPost_dto_list();
//dto.setList(post_dto_list);
}
#Override
public void onFailure(Call<Post_DTO_Resp> call, Throwable t) {
//pDialog.dismiss();
if(t.getMessage().equals("End of input at line 1 column 1 path $"))
{
Toast.makeText(getApplicationContext(), "There are no posts!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Api Error!", Toast.LENGTH_LONG).show();
}
}
});
}
}
Fragment!
public class PostFragment extends Fragment {
RecyclerView recyclerView;
View v;
Dto dtobject;
private static final String DESCRIBABLE_KEY = "list";
private Describable mDescribable;
List<Post_DTO> post_dto_list;
public PostFragment() {
// Required empty public constructor
}
public void passData(Context context, List<Post_DTO> list) {
//mContext = context;
post_dto_list = list;
// mIndex = pos;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_posts, container, false);
recyclerView=(RecyclerView) v.findViewById(R.id.posts_recyclerview);
RecyclerViewAdapter recyclerViewAdapter=new RecyclerViewAdapter(getContext(),post_dto_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(recyclerViewAdapter);
//listupdater();
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Just want to get the post_dto_list from Activity to fragment class!
Suggestions please!
You can use a bundle to pass a list from activity to fragment.
In activity:
Bundle bundle = new Bundle();
bundle.putSerializable("list", mList);
mFragment.setArguments(bundle);
And then in your fragment:
mList = getIntent().getExtras().getSerializable("list"));
But the POJO that your list contains should be parcelable ( Parcelable better than Serializable).
Your POJO should be something like:
public class MyPOJO implements Parcelable {
For more info refer this.

Why is my code always receiving a null pointer exception when I have binded the element in to it? I am using Java in Android Studio

I am receiving java.lang.NullPointerException, although I have binded the element correctly.
Tried to check the ID of the element, it matches, but still I receive the same exception.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Text to Speech
tts = new TextToSpeech(this, this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
speakButton = view.findViewById(R.id.speakButton);
}
}
It should be running fine, But I am receiving the java.lang.NullPointerException
You button code should be declared in you fragment not in you activity as the button is in your fragment.xml. As you are accessing the button in onCreate method of the activity it will give nullpointer exception because you fragment's view is not yet rendered.The best practice is to access the view in onViewCreated function of your fragment.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
TranslatorFragment.java
public class TranslatorFragment extends Fragment {
public Button speakButton;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Text to Speech
tts = new TextToSpeech(getActivity(), this);
speakButton = findViewById(R.id.speakButton);
speechText = findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
// End
}
void speakOut(){
}
The solution is to implement TextToSpeech.OnInitListener in the project and make the public variables to be private.
public class TranslatorFragment extends Fragment implements TextToSpeech.OnInitListener{
private Button speakButton; // public Button speakButton;
private TextToSpeech tts;
private EditText speechText; // public EditText speechText;
public TranslatorFragment(){
//Empty Constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.translator_fragment, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tts = new TextToSpeech(getActivity(), this);
speakButton = view.findViewById(R.id.speakButton);
speechText = view.findViewById(R.id.speechText);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speakOut();
}
});
}
private void speakOut(){
String text = speechText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status){
if(status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(getActivity(), "Language not supported!", Toast.LENGTH_SHORT).show();
} else {
speakButton.setEnabled(true);
speakOut();
}
}
else
{
Toast.makeText(getActivity(), "Initilization failed!", Toast.LENGTH_SHORT).show();
}
}
public void onDestroy() {
if(tts != null){
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}

Passing a string to another activity in android

I am working on an app and I need to pass the contents of some textviews to a new activity, but I want to save the content I pass while the app is open so that the user can select more items from other activities and send them to the final checkout activity.
right now I have spinners which save the selection to a Textview
public class Americano extends AppCompatActivity {
// MyDBHandler dbHandler;
String result;
TextView tvSize;
Spinner spinner;
int mPos;
String mSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_americano);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Spinner spinnerSize = (Spinner) findViewById(R.id.spinner_size);
AdapterView.OnItemSelectedListener listener = new myOnItemSelectedListener();
spinnerSize.setOnItemSelectedListener(listener);
Spinner spinnerSyrups = (Spinner) findViewById(R.id.spinner_syrups);
AdapterView.OnItemSelectedListener listenerSyrups = new myOnItemSelectedListener2();
spinnerSyrups.setOnItemSelectedListener(listenerSyrups);
Spinner spinnerTopping = (Spinner) findViewById(R.id.spinner_toppings);
AdapterView.OnItemSelectedListener listenerTopping = new myOnItemSelectedListener3();
spinnerTopping.setOnItemSelectedListener(listenerTopping);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBAdapter dbAdapter = new DBAdapter(view.getContext());
}
});
}
public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSize);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener2 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSyrup);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener3 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvTopping);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I have more menu item classes exactly like this one
I want to pass the textview data to the checkout page. But save that data in that page until the user closes the app.
thanks
You can do it sending the information through an Intent.
In your listener you would go to another actvity like this:
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("RESULT_TEXT", resultText);
startActivity(intent);
And on the NewActivity you can get the information like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String resultText = bundle.getString("RESULT_TEXT", "");
}
Hope it helps.

Categories

Resources