I am making a tabbed activity with multiple fragments which populate themselves with RecyclerView and the data for this is being retrieved from Firebase Realtime database and Storage as backend.
The error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.visan.peds, PID: 1522
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
at com.example.visan.peds.Landing_mother.getData(Landing_mother.java:76)
at com.example.visan.peds.Landing_mother.onCreateView(Landing_mother.java:43)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1643)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1272)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1646)
at android.view.View.measure(View.java:18991)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18991)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2645)
at android.view.View.measure(View.java:18991)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2403)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1342)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1591)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1233)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6552)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:919)
at android.view.Choreographer.doCallbacks(Choreographer.java:710)
at android.view.Choreographer.doFrame(Choreographer.java:645)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:905)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5582)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My Main Activity, Landing.java
package com.example.visan.peds;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class Landing extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout=(TabLayout)findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("CHILD"));
tabLayout.addTab(tabLayout.newTab().setText("MOTHER"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager=(ViewPager) findViewById(R.id.pager);
final Landing_frag_manager frag_manager=new Landing_frag_manager(getSupportFragmentManager(),tabLayout.getTabCount(),Landing.this);
viewPager.setAdapter(frag_manager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
});
}
}
Its layout file, activity_landing.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/main_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
The fragment adapter, Landing_frag_manager.java
package com.example.visan.peds;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class Landing_frag_manager extends FragmentPagerAdapter {
private int num_of_tabs;
Context context;
public Landing_frag_manager(FragmentManager fm, int numOfTabs, Context context){
super(fm);
this.num_of_tabs=numOfTabs;
this.context=context;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Landing_child child=new Landing_child();
return child;
case 1:
Landing_mother mother=new Landing_mother();
return mother;
default:
return null;
}
}
#Override
public int getCount() {
return num_of_tabs;
}
}
Code for Fragment, Landing_mother.java
package com.example.visan.peds;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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 Landing_mother extends Fragment {
private List<Ailment> ailments;
private RecyclerView recyclerView;
LinearLayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public Landing_mother(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragment_landing_mother,container,false);
ailments=new ArrayList<>();
getData();
recyclerView =(RecyclerView)view.findViewById(R.id.recyclerView1);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
return view;
}
private void getData(){
FirebaseDatabase db=FirebaseDatabase.getInstance();
DatabaseReference ref=db.getReference().child("Mother").child("0");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Log.v("SNAPSHOT::",dataSnapshot.toString());
for (DataSnapshot snapshot:dataSnapshot.getChildren()){
Ailment ailment=snapshot.getValue(Ailment.class);
ailments.add(ailment);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adapter=new LandingAdapter(ailments,getActivity());
recyclerView.setAdapter(adapter);
}
}
Its layout file, fragment_landing_mother.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
The Ailment object class, Ailment.java
package com.example.visan.peds;
public class Ailment {
private String name, image_url;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setImage_url(String image_url){
this.image_url=image_url;
}
public String getImage_url(){
return image_url;
}
}
Adapterfor RecyclerView, LandingAdapter.java
package com.example.visan.peds;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.List;
public class LandingAdapter extends RecyclerView.Adapter<LandingAdapter.ViewHolder>{
private List<Ailment> list;
private Context context;
FirebaseStorage storage;
LayoutInflater inflater;
public LandingAdapter(List<Ailment> list, Context context){
super();
this.list=list;
this.context=context;
inflater=LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.landing_list_row,parent,false);
ViewHolder viewHolder=new ViewHolder(itemView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Ailment ailment=list.get(position);
StorageReference storageReference=storage.getReferenceFromUrl(ailment.getImage_url());
Glide.with(context).using(new FirebaseImageLoader()).load(storageReference).into(holder.imageView);
holder.textView.setText(ailment.getName());
}
#Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public ImageView imageView;
public TextView textView;
public ViewHolder(View view){
super(view);
imageView=(ImageView)view.findViewById(R.id.row_image);
textView=(TextView)view.findViewById(R.id.row_name);
}
}
}
Layout file for Single Row of recyclerView, landing_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/row_image"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/row_name"
android:layout_below="#+id/row_image"/>
</RelativeLayout>
Your are calling getData(); which is trying to access RecyclerView before it has been initialised. Call it after you finish recycler view initialisation. For example after recyclerView.setLayoutManager(layoutManager);
Related
I have a view (activity_SingIn) and its Presenter now in the onCreate method gives me the following error related to "singInPresenter.singInUser(v);"
2022-09-18 17:30:51.785 3811-3811/com.example.Natour21 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.Natour21, PID: 3811
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.NaTour21.Presenter.Activity.SingInPresenter.singInUser(android.view.View)' on a null object reference
at com.example.NaTour21.View.Activity.activity_singIn$2.onClick(activity_singIn.java:61)
package com.example.NaTour21.Presenter.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.NaTour21.View.Activity.activity_Home;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import android.widget.ProgressBar;
public class SingInPresenter extends AppCompatActivity {
private EditText EmailLgn,PasswordLgn;
String[] messaggio = {"Campi vuoti inserili"};
private ProgressBar progressBar;
public void singInUser(View view) {
String email = EmailLgn.getText().toString();
String password = PasswordLgn.getText().toString();
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
home();
}
}, 3000);
} else {
String error;
try{
throw task.getException();
}catch(Exception e){
error ="Errore di accesso utente";
}
Snackbar snackbar = Snackbar.make(view,error,Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}
}
});
}
public void home() {
Intent intent = new Intent(this, activity_Home.class);
startActivity(intent);
finish();
}
#Override
public void onStart() {
super.onStart();
FirebaseUser UtenteCorrente = FirebaseAuth.getInstance().getCurrentUser();
if(UtenteCorrente != null){
home();
}
}
}
package com.example.NaTour21.View.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.example.NaTour21.Presenter.Activity.SingInPresenter;
import com.example.NaTour21.R;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.widget.ProgressBar;
public class activity_singIn extends AppCompatActivity{
private EditText EmailLgn,PasswordLgn;
private Button loginLgn;
private Button registratiLgn;
private SingInPresenter singInPresenter;
private ProgressBar progressbar;
String[] messaggio = {"Campi vuoti inserirli",
"Accesso effettuato con successo",
"Formato email non valido",
"La password deve avere minimo 6 caratteri"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singin);
getSupportActionBar().hide();
initializeComponent();
registratiLgn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity_singIn.this, activity_singUp.class);
startActivity(intent);
}
});
loginLgn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = EmailLgn.getText().toString();
String password = PasswordLgn.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Snackbar snackbar = Snackbar.make(v, messaggio[0], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
} else if (!isValidEmail(email)) {
Snackbar snackbar = Snackbar.make(v, messaggio[2], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}else if (!(password.length() < 6)) {
Snackbar snackbar = Snackbar.make(v, messaggio[3], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}else{
Snackbar snackbar = Snackbar.make(v, messaggio[1], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
singInPresenter.singInUser(v); //??????
}
}
});
}
private boolean isValidEmail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void initializeComponent() {
registratiLgn = findViewById(R.id.btRegistratiLgn);
EmailLgn = findViewById(R.id.tilEmailLgn);
PasswordLgn = findViewById(R.id.tilPasswordLgn);
loginLgn = findViewById(R.id.btLoginLgn);
progressbar = findViewById(R.id.progressbarLgn);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/sfondo"
android:id="#+id/activity_singin"
android:clickable="true"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="336dp"
android:layout_height="196dp"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/txtNomeApp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:clickable="true"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:text="NaTour21"
android:textColor="#color/white"
android:textSize="60sp" />
</LinearLayout>
<LinearLayout
android:layout_width="361dp"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<EditText
android:id="#+id/tilEmailLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="25dp"
android:drawableLeft="#drawable/ic_email"
android:ems="10"
android:hint="Email"
android:textColor="#color/white"
android:inputType="textEmailAddress"
app:backgroundTint="#color/white"/>
<EditText
android:id="#+id/tilPasswordLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_password"
android:drawableRight="#drawable/ic_occhio"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#color/white"
app:backgroundTint="#color/white"/>
<ProgressBar
android:id="#+id/progressbarLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
app:layout_constraintTop_toBottomOf="#id/containerComponents" />
<Button
android:id="#+id/btLoginLgn"
android:layout_width="232dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:background="#drawable/button_login"
android:text="Login"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold"/>
<Button
android:id="#+id/btRegistratiLgn"
android:layout_width="232dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:background="#drawable/button_registrati"
android:text="Registrati"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Dear #Fabiola Salomone if you are trying to use MVP because you said you have a presenter then i am afraid you are not doing it correctly at least according to what i know about MVP please study about it that will be better instead of me or anyone else telling you the code directly because you will not know how it works that way , for a head start you need to make an interface and presenter and inside that presenter you will make three more interfaces View Model and Presenter again and then you will initialize that presenter inside you main activity , here you are extending you presenter with appcompactActivty that itself is wrong a lot about your code is wrong its not MVP by any means so i don't how can i help you exactly with this apart from what i just said, Once you know how MVP work then me or other users can surely help you with this, Still if you need any clearance you can ask :)
I am stucked at one problem regarding my fragments. I just want to switch between different fragments and show a menu on the top - quite standard I think - smth. like here:
For this purpose I set up a PageAdapter (where SMartFragmentStatePageAdapter is just derived from FragmentStatePagerAdapter):
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
class ViewPagerAdapter extends SmartFragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
#Override
public int getCount() {
return categories.length;
}
#Override
public CharSequence getPageTitle(int position) {
return categories[position];
}
}
I initializing the page adapter in my main class:
viewPager = (ViewPager) findViewById(R.id.pager);
SmartFragmentStatePagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
And my ArrayFragment Class looks like this:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Collections;
public class ArrayListFragment extends ListFragment {
int mNum;
/**
* Create a new instance of CountingFragment, providing "num"
* as an argument.
*/
public static ArrayListFragment newInstance(int num) {
ArrayListFragment f = new ArrayListFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
View tv = v.findViewById(R.id.text);
int page = getArguments().getInt("num", -1);
((TextView)tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, Collections.singletonList("test1")));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
}
}
Now the weired thing is, that for showing up the heading titles in of the PageAdapter I need to add the "PagerTabStrip" in my layout file - so my layout file for my main class looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center" android:measureWithLargestChild="true"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0">
<Button android:id="#+id/goto_first"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="first">
</Button>
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="last">
</Button>
</LinearLayout>
</LinearLayout>
The Problem now is, when I am using the PagerTabStrip, then the content of the ArrayFragment is not shown up:
With the PagerTabStrip:
Without the PagerTabStrip:
So without the PagerTabStrip the content is shown and I do not know why.
I read here that the solution might be to use getChildFragmentManager() instead of getSupportFragmentManager(). But this function can only be used if my main class derives from Fragment, but it derives from FragmentActivity so this can not be the solution for me.
Any ideas?
I found out in the meanwhile what went wrong.
I was pretty sure, that there has to be a problem in the layout file and indeed it was. Probably I should not have set the android:layout_height="0px" :) Result of hours of hacking without break.
So with small adaptions of the ViewPager it worked like a charme:
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp">
</android.support.v4.view.PagerTabStrip>
</android.support.v4.view.ViewPager>
Thanks everybody who has started analyzing already!
i have added a button in a xml file ..now i want to open it in fragment ..
i am trying to show share option on button click but not findViewbyid working nor anything happen when click on button after RUN..
May be this is the code for sharing.. I am Confused..Please Help
I have Tried My Best..Any Help Will be Appreciated..Thanks to All Experts
(XML Files)
activity_main :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation"
/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemIconTint="#color/selector_item_gray_color"
app:itemTextColor="#color/selector_item_gray_color"
android:background="#302E2D"
app:menu="#menu/bottom_navigation_android" />
</RelativeLayout>
fragment_more :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="#fff"
android:gravity="center_horizontal">
<LinearLayout
android:id="#+id/linear1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<androidx.appcompat.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Night Mode"
android:textColor="#color/textcolour"></androidx.appcompat.widget.SwitchCompat>
<Button
android:id="#+id/btn_share"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_marginTop="85dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Share"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option2"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_share"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Recommend to friends"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option3"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_option2"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Get Free Islamic Apps"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option4"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_option3"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Rate and Feedback"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<Button
android:id="#+id/btn_option5"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_below="#+id/btn_option4"
android:layout_marginTop="10dp"
android:background="#color/design_default_color_secondary_variant"
android:text="Help"
android:textColor="#color/textcolour"
android:textSize="18sp" />
<TextView
android:id="#+id/textview6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Example Text"
android:textSize="12sp"
android:textColor="#000000"/>
</LinearLayout>
</RelativeLayout>
(Java Files)
Main_Activity :
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomnav = findViewById(R.id.bottom_navigation);
bottomnav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home_Fragment()).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem MenuItem) {
Fragment selectedFragment = null;
switch (MenuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new Home_Fragment();
break;
case R.id.nav_settings:
selectedFragment = new More_Fragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
Fragment_More :
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.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class More_Fragment extends Fragment {
Button btn;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, container,false);}
}
Even Tried This Code in Fragment_More But Failed
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.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class More_Fragment extends Fragment {
private String a = "";
private String b = "";
private LinearLayout linear1;
private Button btn_share;
private TextView textview6;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, container,false);}
private void initialize(Bundle _savedInstanceState) {
linear1 = (LinearLayout) getActivity().findViewById(R.id.linear1);
btn_share = (Button) getActivity().findViewById(R.id.btn_share);
textview6 = (TextView) getActivity().findViewById(R.id.textview6);
btn_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
a = textview6.getText().toString();
b = textview6.getText().toString();
Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
}
});
}
private void initializeLogic() { textview6.setVisibility(View.GONE);
}
}
To reference your Button within your fragment you want to do it in onCreateView:
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_more, container,false);
btn_share = (Button) rootView.findViewById(R.id.btn_share);
btn_share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
a = textview6.getText().toString();
b = textview6.getText().toString();
Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
}
});
return rootView;
}
This Is How Its Done..Thanks A Million All Experts..
Fragment_More.java
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.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class More_Fragment extends Fragment{
private String a = "";
private String b = "";
private LinearLayout linear1;
private Button btn_sharethis;
private TextView text;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_more, container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btn_sharethis = (Button)view.findViewById(R.id.btn_shareme);
text = (TextView)view.findViewById(R.id.textview61);
btn_sharethis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = text.getText().toString();
b = text.getText().toString();
Intent i = new Intent(android.content.Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(android.content.Intent.EXTRA_SUBJECT, a); i.putExtra(android.content.Intent.EXTRA_TEXT, b); startActivity(Intent.createChooser(i,"Share using"));
}
});
}
}
I have a strange issue with my Fragment, I get no errors at runtime (I'm using Android Studio v8.7 and the Gradle compiles just fine) but when my app runs on my phone it's now showing up, it looks like an empty Activity.
Activity.class
package android.bignerdranch.com.criminalintent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.MenuItem;
public class CrimeActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
// These are Fragments from the app.v4 package, it's needed to make the app compatible with API < 11
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if(fragment == null) {
fragment = new Fragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Fragment.class
package android.bignerdranch.com.criminalintent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckbox;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mCrime.setTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getDate().toString());
mDateButton.setEnabled(false);
mSolvedCheckbox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
}
Activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_label"
style="?android:listSeparatorTextViewStyle" />
<EditText
android:id="#+id/crime_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_title_hint" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/crime_details_label"
style="?android:listSeparatorTextViewStyle" />
<Button
android:id="#+id/crime_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp" />
<CheckBox
android:id="#+id/crime_solved"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:text="#string/crime_solved_label" />
</LinearLayout>
Can somebody point me in the right direction and tell me what could solve my issue?
Ok i found the errors, I was instantiating the wrong Fragment.
Instead of
if(fragment == null) {
fragment = new Fragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
It should be
if(fragment == null) {
fragment = new CrimeFragment();
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
I'm attempting to create a dynamic UI using the support.v4 library to insert fragments into a framelayout I have defined for my main activity.
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android:id="#+id/button_report"
android:text="#string/button_report"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/button_pay"
android:text="#string/button_pay"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/button_contact"
android:text="#string/button_contact"
android:textSize="22sp"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<FrameLayout
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2" />
</LinearLayout>
And here is the MainActivity.java:
package com.example.Test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity
{
// Declare button variables
protected Button btnReport;
protected Button btnPay;
protected Button btnContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Assign buttons
btnReport = (Button)findViewById(R.id.button_report);
btnPay = (Button)findViewById(R.id.button_pay);
btnContact = (Button)findViewById(R.id.button_contact);
// Import fragments
final Fragment fragmentPhone = new FragmentPhone();
final Fragment fragmentReport = new FragmentReport();
final Fragment fragmentPay = new FragmentPay();
final android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
// Check for existing fragment, if none then add FragmentPhone.class
if (savedInstanceState != null) return;
else {
ft.add(R.id.container, fragmentPhone);
ft.commit();
}
// "Report" button
btnReport.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentReport); //Replace the details_container
ft.addToBackStack(null); // Add transaction to back stack
ft.commit(); // Commit the transaction
}
});
// "Pay" button
btnPay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentPay);
ft.addToBackStack(null);
ft.commit();
}
});
// "Contact" button
btnContact.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ft.replace(R.id.container, fragmentPhone);
ft.addToBackStack(null);
ft.commit();
}
});
}
}
And here is my FragmentPhone class:
package com.example.Test;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentPhone extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone, container, false);
}
}
When I launch the app, the xml loads correctly and the framelayout gets filled with fragmentPhone, but pressing any of the buttons creates an "app has stopped unexpectedly" dialogue and prompts me to force close.
Any ideas or suggestions will be greatly appreciated. Thanks!
I ended up re-getting and re-declaring FragmentManager and FragmentTransaction within each onClickListener. I also removed "addToBackStack" as I decided it was unneeded. Here is my current, working code:
// "Report" button
btnReport.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
android.support.v4.app.FragmentManager fragmentManager1 = getSupportFragmentManager();
FragmentTransaction fragmentTransaction1 = fragmentManager1.beginTransaction();
fragmentTransaction1.replace(R.id.container, fragmentReport);
fragmentTransaction1.commit();
}
});
(untested)
make ft a global field so it's available in the click handler.