How to start another fragment using button inside the fragment - java

i have android app which have main activity and three fragment 1-home 2-visa 3-trans,i want to click button in home fragment to start visa fragment ,I've tried more things in home fragment which have the button and
here is my code for Home after i tried to add onclicklistner in onCreatView :
package com.example.ghoniem.myfrag.Fragments;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.ghoniem.myfrag.R;
public class Home extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Home() {
// Required empty public constructor
}
public static Home newInstance(String param1, String param2) {
Home fragment = new Home();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Button button=rootView.findViewById(R.id.text_View88);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visa visa = new Visa();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.visaaa, visa);
fragmentTransaction.commit();
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
code for visa fragment :
package com.example.ghoniem.mfrag.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.ghoniem.myfrag.R;
public class Visa extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Visa() {
}
public static Visa newInstance(String param1, String param2) {
Visa fragment = new Visa();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_visa, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
and this xml for fragment_visa
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/visaaa"
android:layout_height="match_parent"
tools:context="com.example.ghoniem.myfuckenfrag.Fragments.Visa">
<TextView
android:textColor="#color/colorPrimary"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text 2"/>
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:alpha="0.3"
android:src="#drawable/ic_photo_library_black_24dp" />
</FrameLayout>

replace ur onCreateView() in Home Fragment from it
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Button button=rootView.findViewById(R.id.text_View88);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visa visa = new Visa();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.visaaa, visa);
fragmentTransaction.commit();
}
});
// Inflate the layout for this fragment
return rootView;
}

the best practice is to define a call back in the activity that is called from fragment 1 when the button is clicked, this call back should replace the fragment

Try This:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Visa fragment = new Visa();
replaceFragment(fragment);
}
});
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getActivity().getFragmentManager().beginTransaction();
transaction.replace(R.id.visaaa, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}

i tried this and worked for me
Button button=rootView.findViewById(R.id.text_View88);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
Visa visa=new Visa();
fragmentTransaction.replace(R.id.frame,visa);
fragmentTransaction.commit();}
});

Related

No Activity found to handle Intent { act=android.intent.action.CALL dat=tel;xxxxxxxxxx }

** android.content.ActivityNotFoundException: No Activity found to handle Intent {enter image description here**** its is firebase databse seytem**
i have a button ther when i click the button app was crass and send me the error
android.content.ActivityNotFoundException: No Activity found to handle Intent
.kazimasum.firebasefragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
public class descfragment extends Fragment {
private Button callBtn;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
String name, course, email, purl, call;
public descfragment() {
}
public descfragment(String name, String course, String email, String purl, String call) {
this.name=name;
this.course=course;
this.email=email;
this.purl=purl;
this.call=call;
}
public static descfragment newInstance(String param1, String param2) {
descfragment fragment = new descfragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_descfragment, container, false);
Button callBtn=view.findViewById(R.id.callBtn);
ImageView imageholder=view.findViewById(R.id.imagegholder);
TextView nameholder=view.findViewById(R.id.nameholder);
TextView courseholder=view.findViewById(R.id.courseholder);
TextView emailholder=view.findViewById(R.id.emailholder);
final TextView callholder=view.findViewById(R.id.callholder);
callBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = "tel" + call;
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(s));
startActivity(intent);
}
});
nameholder.setText(name);
courseholder.setText(course);
emailholder.setText(email);
Glide.with(getContext()).load(purl).into(imageholder);
callholder.setText(call);
return view;
}
public void onBackPressed()
{
AppCompatActivity activity=(AppCompatActivity)getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.wrapper,new recfragment()).addToBackStack(null).commit();
}

fragment won't hide

I have a navbar which is supposed to be hidden when a button is pressed, but nothing happens.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mavisTxt;
private Button testBtn;
private Fragment navigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVariables();
}
private void initVariables() {
navigationBar = new HeaderNav();
mavisTxt = (TextView)findViewById(R.id.mavisTxt);
testBtn = (Button)findViewById(R.id.testBtn);
testBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.hide(navigationBar)
.commit();
mavisTxt.setText("navbar is hidden");
}
});
}
}
Here is the java file for the fragment
public class HeaderNav extends Fragment {
private static Button homeBtn, optionsBtn, connectionBtn, micBtn, aboutBtn;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.navbar, container, false);
homeBtn = (Button)view.findViewById(R.id.homeBtn);
optionsBtn = (Button)view.findViewById(R.id.optionsBtn);
connectionBtn = (Button)view.findViewById(R.id.micBtn);
micBtn = (Button)view.findViewById(R.id.homeBtn);
aboutBtn = (Button)view.findViewById(R.id.aboutBtn);
return view;
}
}
and the fragment tag in the main_activity xml :
<fragment
android:id="#+id/navigationBar"
android:name="com.example.egi.mavisme.HeaderNav"
android:layout_width="fill_parent"
android:layout_height="60dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout="#layout/navbar" />
what am I doing wrong? none of the solutions here in SO works for me. Someone help me.
EDIT:
I have edited my code and now it hides. I have another issue when adding a custom animation, I am getting a
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.ViewGroup.startViewTransition(android.view.View)' on a null object reference
Here is my code now :
public class MainActivity extends AppCompatActivity {
private TextView mavisTxt;
private Button testBtn;
private HeaderNav navigationBar;
private FragmentManager fm;
private FragmentTransaction ft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVariables();
}
private void initVariables() {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
navigationBar = (HeaderNav)fm.findFragmentById(R.id.navigationBar);
mavisTxt = (TextView)findViewById(R.id.mavisTxt);
testBtn = (Button)findViewById(R.id.testBtn);
testBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.hide(navigationBar)
.commit();
if(navigationBar.isHidden()) {mavisTxt.setText("navbar is hidden");}
}
});
}
}
Here are some things to note-
Use the ActionBar/ToolBar, this isn't iOS
You have to add a fragment first
You are using the show call instead of hiding it
testBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.**show**(navigationBar)
.commit();
mavisTxt.setText("navbar is hidden");
}
});

I have a code break in this fragment but I can't solve it.. It showing that I have null reference ob set text but when I debug I see data

## fragment 1
I am geting null reference on setText on TextView control but I can't find a reason why...
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.helper.Util;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.OpstinaVM;
import ba.fit.app.hci_odbrana.podaci.PosiljkaVM;
public class PosiljaocFragment extends Fragment {
public static final String NEKI_KLJUC = "nekiKljuc";
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TextView viewImePosiljaoca;
private TextView adresaPosiljaoca;
private PosiljkaVM posiljkaVM = new PosiljkaVM();
private OpstinaVM opstina;
public PosiljaocFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PosiljaocFragment newInstance(PosiljkaVM posiljka) {
PosiljaocFragment fragment = new PosiljaocFragment();
Bundle args = new Bundle();
args.putSerializable(NEKI_KLJUC, posiljka);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
posiljkaVM = (PosiljkaVM) getArguments().getSerializable(NEKI_KLJUC);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_posiljaoc, container, false);
viewImePosiljaoca = (TextView) view.findViewById(R.id.viewImePosiljaoca);
adresaPosiljaoca = (TextView) view.findViewById(R.id.viewAdresaPosiljaoca);
final Button btnPromjeniPosiljaoca = (Button) view.findViewById(R.id.btnPromjeniPosiljaoca);
Button btnDalje = (Button) view.findViewById(R.id.btnDalje);
if (posiljkaVM.posljiaoc != null){
viewImePosiljaoca.setText(posiljkaVM.posljiaoc.getIme() + " " + posiljkaVM.posljiaoc.getPrezime());
adresaPosiljaoca.setText(posiljkaVM.posljiaoc.getAdresa() + " - " + posiljkaVM.posljiaoc.getOpstinaVM().getNaziv());
}
btnDalje.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnDaljeClick();
}
});
btnPromjeniPosiljaoca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPromjeniPosiljaocaClick();
}
});
return view;
}
private void btnDaljeClick() {
if (posiljkaVM.primaoc == null){
posiljkaVM.primaoc = new KorisnikVM("", "", new OpstinaVM(0,"",""), "");
}
if (posiljkaVM.posljiaoc == null){
posiljkaVM.posljiaoc = new KorisnikVM(posiljkaVM.posljiaoc.getIme(), posiljkaVM.posljiaoc.getPrezime(), opstina, "");
}
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PrimaocFragment.newInstance(posiljkaVM));
}
private void btnPromjeniPosiljaocaClick() {
MyRunnable<KorisnikVM> callback = new MyRunnable<KorisnikVM>() {
#Override
public void run(KorisnikVM result) {
posiljkaVM.posljiaoc = result;
viewImePosiljaoca.setText(result.getIme() + " " + result.getPrezime());
adresaPosiljaoca.setText(result.getAdresa() + " - " + result.getOpstinaVM().getNaziv());
posiljkaVM.posljiaoc.setIme(result.getIme());
posiljkaVM.posljiaoc.setPrezime(result.getPrezime());
posiljkaVM.posljiaoc.setOpstinaVM(result.getOpstinaVM());
posiljkaVM.posljiaoc.setAdresa(result.getAdresa());
}
};
Util.otvoriFragmentKaoDijalog(getActivity(), KorisniciFragment.newInstance(callback));
}
}
### dialog fragment
package ba.fit.app.hci_odbrana.fragmenti;
import android.support.v4.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.Storage;
public class KorisniciFragment extends DialogFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private MyRunnable<KorisnikVM> callback;
private String mParam2;
private EditText txtImePrezime;
private ListView listKorisnici;
private TextView linija1;
private TextView linija2;
private List<KorisnikVM> podaci;
public KorisniciFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static KorisniciFragment newInstance(MyRunnable<KorisnikVM> myCallback) {
KorisniciFragment fragment = new KorisniciFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, myCallback);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
callback = (MyRunnable<KorisnikVM>) getArguments().getSerializable(ARG_PARAM1);
}
setStyle(STYLE_NORMAL, R.style.MojDijalog);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_korisnici, container, false);
txtImePrezime = (EditText) view.findViewById(R.id.txtImePrezime);
listKorisnici = (ListView) view.findViewById(R.id.listKorisnici);
Button btnTrazi = (Button) view.findViewById(R.id.btnTrazi);
popuniPodatke("");
btnTrazi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnTraziClick();
}
});
listKorisnici.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
KorisnikVM x = podaci.get(position);
getDialog().dismiss();
callback.run(x);
}
});
return view;
}
private void btnTraziClick() {
popuniPodatke(txtImePrezime.getText().toString());
}
private void popuniPodatke(String name) {
podaci = Storage.getKorisniciByName(name);
listKorisnici.setAdapter(new BaseAdapter() {
#Override
public int getCount() {
return podaci.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
KorisnikVM x = podaci.get(position);
if( view == null)
{
final LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.stavka_korisnici, viewGroup, false);
}
linija1 = (TextView) view.findViewById(R.id.linija1);
linija2 = (TextView) view.findViewById(R.id.linija2);
linija1.setText(x.getIme() + " " + x.getPrezime());
linija2.setText(x.getOpstinaVM().getNaziv() + " - " + x.getAdresa());
return view;
}
});
}
}
## Fragment 2
Here everything works fine and it's very similar to first one.
package ba.fit.app.hci_odbrana.fragmenti;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import ba.fit.app.hci_odbrana.R;
import ba.fit.app.hci_odbrana.helper.MyRunnable;
import ba.fit.app.hci_odbrana.helper.Util;
import ba.fit.app.hci_odbrana.podaci.KorisnikVM;
import ba.fit.app.hci_odbrana.podaci.PosiljkaVM;
/**
* A simple {#link Fragment} subclass.
* Use the {#link PrimaocFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class PrimaocFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private PosiljkaVM mParam1;
private TextView viewImePrimaoca;
private TextView adresaPrimaoca;
public PrimaocFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PrimaocFragment newInstance(PosiljkaVM param1) {
PrimaocFragment fragment = new PrimaocFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (PosiljkaVM) getArguments().getSerializable(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_primaoc, container, false);
viewImePrimaoca = (TextView) view.findViewById(R.id.viewImePrimaoca);
adresaPrimaoca = (TextView) view.findViewById(R.id.viewAdresaPrimaoca);
final Button btnPromjeniPrimaoca = (Button) view.findViewById(R.id.btnPromjeniPrimaoca);
final Button btnNazad = (Button) view.findViewById(R.id.btnNazad);
final Button btnDalje2 = (Button) view.findViewById(R.id.btnDalje2);
if (getArguments() != null){
viewImePrimaoca.setText(mParam1.primaoc.getIme() + " " + mParam1.primaoc.getPrezime());
adresaPrimaoca.setText(mParam1.primaoc.getAdresa() + " - " + mParam1.primaoc.getOpstinaVM().getNaziv());
}
btnDalje2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnDalje2Click();
}
});
btnNazad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNazadClick();
}
});
btnPromjeniPrimaoca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnPromjeniPrimaocaClick();
}
});
return view;
}
private void btnNazadClick() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PosiljaocFragment.newInstance(mParam1));
}
private void btnDalje2Click() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PaketFragment.newInstance(mParam1));
}
private void btnPromjeniPrimaocaClick() {
MyRunnable<KorisnikVM> callback = new MyRunnable<KorisnikVM>() {
#Override
public void run(KorisnikVM result) {
mParam1.primaoc = result;
viewImePrimaoca.setText(result.getIme() + " " + result.getPrezime());
adresaPrimaoca.setText(result.getAdresa() + " - " + result.getOpstinaVM().getNaziv()); //here is where I get that null reference
}
};
Util.otvoriFragmentKaoDijalog(getActivity(), KorisniciFragment.newInstance(callback));
}
}
## package fragment
This is for showing some details on package that is been sent when you chose sender and receiver
public class PaketFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
// TODO: Rename and change types of parameters
private PosiljkaVM mParam1;
private EditText txtMasa;
private EditText txtNapomena;
public PaketFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static PaketFragment newInstance(PosiljkaVM param1) {
PaketFragment fragment = new PaketFragment();
Bundle args = new Bundle();
args.putSerializable(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = (PosiljkaVM) getArguments().getSerializable(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_paket, container, false);
txtMasa = (EditText) view.findViewById(R.id.txtMasa);
txtNapomena = (EditText) view.findViewById(R.id.txtNapomena);
final Button btnZavrsi = (Button) view.findViewById(R.id.btnZavrsi);
final Button btnNazad2 = (Button) view.findViewById(R.id.btnNazad2);
btnNazad2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNazad2Click();
}
});
btnZavrsi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnZavrsiClick();
}
});
return view;
}
private void btnZavrsiClick() {
try {
mParam1.masa = Float.parseFloat(txtMasa.getText().toString());
mParam1.napomena = txtNapomena.getText().toString();
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PosiljaocFragment.newInstance(mParam1));
Toast.makeText(getActivity(), "Uspješno spremljena pošiljka!", Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(getActivity(), "Greška: " + e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
private void btnNazad2Click() {
Util.otvoriFragmentKaoReplace(getActivity(), R.id.fragmentPlace, PrimaocFragment.newInstance(mParam1));
}
}
That's it.. hope someone can help me. Have a pleasant day.

Cant go to fragment from adapter

I have activity, and this activity is drawable menu.
inside drawable, i include some fragment, where in my fragment i show some data with adapter. i try to make action when data is clicked, then it will go to other fragment. oh yeah, i try to send some value from my adapter to fragment to.
please help me
this is my adapter..
package com.skripsi.anna.adapter;
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.TextView;
import com.skripsi.anna.MenuEdit;
import com.skripsi.anna.R;
import com.skripsi.anna.model.ModelMenu;
import java.util.List;
/**
* Created by gandhi on 6/11/17.
*/
public class BarangEditor extends RecyclerView.Adapter<BarangEditor.ViewHolder> {
private List<ModelMenu> modelMenus;
private Context context;
public BarangEditor(List<ModelMenu> modelMenus){
this.modelMenus = modelMenus;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView namaBarang,hargaBarang;
public ViewHolder(View v) {
super(v);
namaBarang = (TextView) v.findViewById(R.id.nama_barang);
hargaBarang = (TextView) v.findViewById(R.id.harga);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
ModelMenu modelMenu = modelMenus.get(position);
MenuEdit menuEdit = new MenuEdit();
menuEdit.newInstance(modelMenu.getIdMenu(),modelMenu.getNamaMenu(),modelMenu.getHargaMenu());
// i want to send this value to fragment
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_barang_editor, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ModelMenu modelMenu = modelMenus.get(position);
holder.hargaBarang.setText(modelMenu.getHargaMenu());
holder.namaBarang.setText(modelMenu.getNamaMenu());
}
#Override
public int getItemCount() {
return modelMenus.size();
}
}
And it is my fragment
package com.skripsi.anna;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MenuEdit extends Fragment {
private String idMenu,namaMenu,hargaMenu;
private OnFragmentInteractionListener mListener;
public MenuEdit() {
}
public static MenuEdit newInstance(String idMenu, String namaMenu, String hargaMenu) {
MenuEdit fragment = new MenuEdit();
Bundle args = new Bundle();
args.putString("idMenu", idMenu);
args.putString("namaMenu", namaMenu);
args.putString("hargaMenu",hargaMenu);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
idMenu = getArguments().getString("idMenu");
namaMenu = getArguments().getString("namaMenu");
hargaMenu = getArguments().getString("hargaMenu");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_edit, container, false);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
i have try this
FragmentTransaction ft = ((AppCompatActivity) context).getSupportFragmentManager().beginTransaction();
but it make my app FC
and it is not work
i using this code and i hope work for you
public void addFragment(Fragment fragment, boolean addToBackStack, String tag)
{
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (addToBackStack)
{
ft.addToBackStack(tag);
}
ft.replace(R.id.content_frame, fragment, tag);
try{
ft.commitAllowingStateLoss();
}catch (Exception e){
}
}
[SOLVED]
i try put this code on my adapter
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, menuEdit).commit();
but it say cant resolve getSupportFragment
so its the real problem, and for solution, i write some code like this
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContent, menuEdit).addToBackStack(null).commit();
and its work
its my full adapter now
package com.skripsi.anna.adapter;
import android.os.Bundle;
import android.support.v4.app.FragmentController;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.skripsi.anna.MenuEdit;
import com.skripsi.anna.R;
import com.skripsi.anna.model.ModelMenu;
import java.util.List;
/**
* Created by gandhi on 6/11/17.
*/
public class BarangEditor extends RecyclerView.Adapter<BarangEditor.ViewHolder> {
private List<ModelMenu> modelMenus;
public BarangEditor(List<ModelMenu> modelMenus){
this.modelMenus = modelMenus;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView namaBarang,hargaBarang;
public ViewHolder(View v) {
super(v);
namaBarang = (TextView) v.findViewById(R.id.nama_barang);
hargaBarang = (TextView) v.findViewById(R.id.harga);
v.setOnClickListener(new View.OnClickListener() {
public FragmentController appCompatActivity;
#Override
public void onClick(View v) {
int position = getAdapterPosition();
ModelMenu modelMenu = modelMenus.get(position);
MenuEdit menuEdit = new MenuEdit();
Bundle bundle = new Bundle();
bundle.putString("idMenu",modelMenu.getIdMenu());
menuEdit.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) v.getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContent, menuEdit).addToBackStack(null).commit();
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_barang_editor, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ModelMenu modelMenu = modelMenus.get(position);
holder.hargaBarang.setText(modelMenu.getHargaMenu());
holder.namaBarang.setText(modelMenu.getNamaMenu());
}
#Override
public int getItemCount() {
return modelMenus.size();
}
}

Android - NullPointerException with Fragment and Spinner

My fragment needs to create a spinner to control what gets displayed in the webview. There is also a progress bar that shows the loading from the spinner selection. Everything works well in a standard activity but moving it to a fragment is proving problematic. I will post the fragment and error.
Thanks!
the error occurs at this line:
spLoadFrom.setAdapter(spinnerArrayAdapter);
Here is the code:
package com.example.fragmenttest.app;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
ProgressBar pd = null;
public static final String PREFS_NAME2 = "SearchFile";
Spinner spLoadFrom;
WebView wv;
private LinearLayout container;
private Button nextButton, closeButton;
private EditText findBox;
private ArrayAdapter<CharSequence> spinnerArrayAdapter;
String name[] = { "mystuff" };
String displayName[] = {
"mystuff" };
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BlankFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
wv = (WebView) container.findViewById(R.id.webview);
pd = (ProgressBar) container.findViewById(R.id.pBar);
spLoadFrom = (Spinner) container.findViewById(R.id.Spinner02);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, displayName);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spLoadFrom.setAdapter(spinnerArrayAdapter);
SpinnerListener spListener = new SpinnerListener();
spLoadFrom.setOnItemSelectedListener(spListener);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.atcsectionweb2, container, false);
}
public class SpinnerListener implements AdapterView.OnItemSelectedListener {
public SpinnerListener() {
}
public void onItemSelected(AdapterView<?> arg0, View arg1,
final int position, long arg2) {
WebView wv = (WebView) getView().findViewById(R.id.webview);
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100
&& pd.getVisibility() == ProgressBar.GONE) {
pd.setVisibility(ProgressBar.VISIBLE);
}
pd.setProgress(progress);
if (progress == 100) {
pd.setVisibility(ProgressBar.GONE);
}
}
});
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setSupportZoom(true);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
wv.loadUrl("file:///android_asset/" + name[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
And the error:
04-23 19:17:10.621 9679-9679/com.example.fragmenttest.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.fragmenttest.app, PID: 9679
java.lang.NullPointerException
at com.example.fragmenttest.app.BlankFragment.onCreateView(BlankFragment.java:243)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:614)
at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
at dalvik.system.NativeStart.main(Native Method)
Here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ProgressBar
android:id="#+id/pBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/Spinner02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/pBar" />
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/Spinner02" />
<LinearLayout
android:id="#+id/layoutId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/webview"
android:orientation="horizontal" >
</LinearLayout>
</RelativeLayout>
You have to use your inflated fragment layout:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.atcsectionweb2, container, false);
wv = (WebView) v.findViewById(R.id.webview);
pd = (ProgressBar) v.findViewById(R.id.pBar);
spLoadFrom = (Spinner) v.findViewById(R.id.Spinner02);
(...)
return v;
}
I got the same issue while setting adapter to spinner in fragment.... and solved it by....
if (getActivity() != null) {
spLoadFrom.setAdapter(spinnerArrayAdapter);
}

Categories