required android.support.v4.app.fragment - java

i have simple project that have list view
when any one click on any item on list view
open in single window
by fragment
the problem is that i want to replace my fragment with on of this tabs fragment on this project
http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
i put my mainactivty class in switch case but it get to me this error
in first picture
i try to import import android.support.v4.app.Fragment
but also the same promplem
this is the clases of my project
....Main2Activity class
public class Main2Activity extends AppCompatActivity implements fragmentA.comunicatir
{
fragmentA f1;
fragmentB f2;
FragmentManager manegaer;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
manegaer=getSupportFragmentManager();
f1=(fragmentA)manegaer.findFragmentById(R.id.fragment1);
f1.setcomunicatir(this);
}
#Override
public void respned(int index){
f2=(fragmentB)manegaer.findFragmentById(R.id.fragment2);
if(f2!=null&&f2.isVisible()){
f2.cahngedata(index);
}else{
Intent intent=
new Intent(this,
AnotherActivity.class);
intent.putExtra("index",index);
startActivity(intent);
}
}
}
the another classes
class fragmentA
public class fragmentA extends Fragment implements AdapterView.OnItemClickListener
{
ListView list;
comunicatir com;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment1,container,false);
list=(ListView)view.findViewById(R.id.listView1);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.chapters, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
return view;
}
public void setcomunicatir (comunicatir comunicator)
{
this.com=comunicator;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View veiw, int i, long l) {
com.respned(i);
}
public interface comunicatir
{
public void respned(int index);
}
}
public class fragmentB extends Fragment
{
TextView text;
TextView textView2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, container, false);
//text = (TextView) view.findViewById(R.id.textView1);
//imgv=(ImageView) view.findViewById(R.id.imageView1);
textView2 =(TextView)view.findViewById(R.id.textView22);
return view;
}
public void cahngedata(int index)
{
/*String[] descrption =getResources().getStringArray(R.array.hadeith);
text.setText(descrption[index]);*/
String []Hadith=getResources().getStringArray(R.array.hadeith);
//imgv.setImageResource(img[index]);
textView2.setText(Hadith[index]);
//int []descrption =getResources().getIntArray(img[index]);
// imgv.setImageResource(descrption[index]);
/*text.setText(descrption[index]);
int arr[]=getResources().getIntArray(img[index]);
imgv.setImageResource(arr[index]);*/
}
}
public class AnotherActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.another);
Intent intent = getIntent();
int index= intent.getIntExtra("index", 0);
fragmentB f2= (fragmentB)
getFragmentManager().
findFragmentById(R.id.fragment2);
if (f2!=null)
f2.cahngedata(index);
}
}
the Another Activity class also have error in picture 2

1st issue: You just can't put an activity on a Tab, but you probably won't need the getItem() you can delete that method
2nd issue:
Replace:
fragmentB f2 = (fragmentB) ...
With:
fragment f2 = (Fragment) ...

go to the tab.class which u have problem in and change
import android.app.Fragment;
to
import android.support.v4.app.Fragment;
it will run .

Related

Change the fragment to another fragment within a setOnclick

I have a simple block code and i wish pass this fragment to another fragment with a click in a button.
If anyone could help me I would appreciate it
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_inicio,container,false);
linearLayout = view.findViewById(R.id.clientea);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Teste",Toast.LENGTH_SHORT).show();
}
});
return view;
}
I will show a simple way with code.
There are one Activity and two Fragments in the code.
First , the MainActivity contains the FragmentOne.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction().add(R.id.container, new FragmentOne(), "")
.addToBackStack(null)
.commit();
}}
Then FragmentOne, there is a button in it, which will jump FragmentTwo when click.
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
Button btnClick = view.findViewById(R.id.btn);
btnClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.container, new FragmentTwo())
.addToBackStack(null)
.commit();
}
});
return view;
}}
The last is the FragmentTwo:
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_two, container, false);
return view;
}
}
I could give the xml if you want.
From my experience with Android development, the approach that is taken to this problem is to create a functional interface, implement the interface in the Activity that the fragments are managed by and then do the fragment swapping inside the method provided by the interface.
So first create an interface, let's call it IFragmentToSwap.
public interface IFragmentToSwap{
void OnButtonClicked();
}
Then in the Activity that controls fragment transactions you need to implement this interface.
public class MainActivity extends AppCompatActivity implements IFragmentToSwap {
#Override
public void OnButtonClicked()
{
//Swap fragment here
}
}
Now in your fragment in the OnAttach override method you should do the following:
private IFragmentToSwap mListener;
#Override
public void onAttach(Context context)
{
super.onAttach(context);
if (context instanceof IFragmentToSwap)
{
mListener = (MainActivity) context;
}
else
{
throw new RuntimeException(context.toString()
+ " must implement IFragmentToSwap");
}
}
And in the method you provided that is contained inside your fragment you would call the method on the functional interface when a click happens, like this:
#Override
public View onCreateView(final LayoutInflater inflater, final
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_inicio,container,false);
linearLayout = view.findViewById(R.id.clientea);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.OnButtonClicked();
Toast.makeText(getActivity(),"Teste",Toast.LENGTH_SHORT).show();
}
});
return view;
}
And don't forget to detach the listener in the OnDetach override:
public void onDetach()
{
super.onDetach();
mListener = null;
}
This is the most common approach I have seen to swapping fragments on Android.

communication between two fragments . I am not using any already defined view for any of the fragments. I am just adding fragments at runtime

I have two fragments MyFragment and MyFragment2 , an interface defined within MyFragment2.
code for MyFragment2:
public class MyFragment2 extends android.support.v4.app.Fragment implements View.OnClickListener {
public interface MyInterface2
{
public void respond(String s);
}
EditText editText;
Button sendData;
MyInterface2 comm;
View v=getView();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.my_fragment_2,container,false);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.comm = (MyInterface2)getActivity();
editText = (EditText)getActivity().findViewById(R.id.text);
sendData =(Button)getActivity().findViewById(R.id.sendData);
sendData.setOnClickListener(this);
}
#Override
public void onClick(View v) {
try {
String s = editText.getText().toString();
comm.respond(s);
}
catch(Exception e)
{
Toast.makeText(getActivity(),"error:"+e,Toast.LENGTH_LONG).show();
}
}
}
I am trying to send the content of editText from MyFragment2 to the fragment MyFragment by pressing the button (Myfragment2 initially set on the main activity's view using the Java code)
The main activity's code is as follows*(my_layout is the id of layout in which I am putting the fragments)*:
public class MainActivity extends AppCompatActivity implements MyFragment2.MyInterface2 {
//String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyFragment2 fragment2= new MyFragment2();
FragmentManager fManager= getSupportFragmentManager();
FragmentTransaction transaction= fManager.beginTransaction();
transaction.add(R.id.my_layout,fragment2,"MyFragment2");
transaction.commit();
}
public void respond(String s)
{
MyFragment fragment = new MyFragment();
FragmentManager fManager =getSupportFragmentManager();
FragmentTransaction transaction = fManager.beginTransaction();
transaction.replace(R.id.my_layout,fragment);
transaction.commit();
fragment.getData(s);
}
}
when I click the sendData button in fragment MyFragment2 , MyFragment2 gets replaced with fragment Myfragment but no data change occurs in the MyFragmnet's textView and an error is also shown which I have catched in a try catch block from fragment MyFragment2(here is the image for that).
code for MyFragment :
public class MyFragment extends android.support.v4.app.Fragment {
TextView textView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.my_fragment,container,false);
//textView =(TextView)v.findViewById(R.id.getText);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textView =(TextView)getActivity().findViewById(R.id.getText);
}
public void getData(String data)
{
textView.setText(data);
}
}
You can easily pass data between fragments using a callback or passing the arguments via a bundle.
Check out this article:
https://developer.android.com/training/basics/fragments/communicating.html
onActivityCreated is no need. Uncomment ur text view initiation statement in onCreateView block.
Ensure you have text view in your respective layout file with same id you have passed

How can I find the null pointer error in this Android Code involving Fragments

I have been trying for 2 hours now to find the null pointer in my code and am having no luck. I am hoping one of you far smarter individuals than I can figure it out. First off, I am following the tutorial here: http://youtu.be/Y2liEQV3tbQ?list=PLonJJ3BVjZW4lMlpHgL7UNQSGMERcDzHo by slideNerd.
Here is what is baffling me: When in horizontal mode, the code executes perfectly and the displays are updated with correct information. This means that the horizontal portion of the if statement is working. When it is in portrait however and I click a list view icon, it immediately force closes with null pointer. The error comes from the line that reads:
f2b.changeTextView(index);
If I remove that line, the second activity opens without a problem. I am simply at a loss as to what has been causing me so much trouble.
Here are my classes:
MainActivity:
public class MainActivity extends Activity implements FragmentA.Communicator{
private FragmentA f1a;
private FragmentB f2b;
private FragmentManager manager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager=getFragmentManager();
f1a = (FragmentA) manager.findFragmentById(R.id.fragment1a);
f1a.setCommunicator(this); //the respond method that is implemented from Fragment a
f2b = (FragmentB) manager.findFragmentById(R.id.fragment2b);
}
#Override
public void respond(int index) {
//Check if portrait mode
if (f2b != null && f2b.isVisible()){ //Horizontal
f2b.changeTextView(index);
} else { //Vertical
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
Fragment A:
public class FragmentA extends Fragment implements AdapterView.OnItemClickListener {
ListView listView;
Communicator comm;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.fragment_a_list_view);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.chapters, android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
comm.respond(position);
}
public void setCommunicator(Communicator communicator){
this.comm = communicator;
}
//Interface to allow access between fragments
public interface Communicator{
public void respond(int index);
}
}
Fragment B:
public class FragmentB extends Fragment {
TextView textView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
textView = (TextView) getActivity().findViewById(R.id.fragment_b_text_view);
}
public void changeTextView(int position){
String [] descriptions = getResources().getStringArray(R.array.descriptions);
textView.setText(descriptions[position]);
}
}
Activity2:
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
Intent intent = getIntent();
int index = intent.getIntExtra("index", 0);
//reference the fragment
FragmentB f2b = (FragmentB) getFragmentManager().findFragmentById(R.id.fragment2b);
if (f2b != null){
f2b.changeTextView(index);
}
}
}
And Here is the error code in the logcat:
Caused by: java.lang.NullPointerException
at com.pgmacdesign.fragmentexamples3_flexibleui.FragmentB.changeTextView(FragmentB.java:42)
at com.pgmacdesign.fragmentexamples3_flexibleui.Activity2.onCreate(Activity2.java:25)
I have already confirmed that the index/ position variable is passing correctly. If anyone has any suggestions as to how to find the null pointer error, I would love the assistance.
In your Fragment B,
Try to replace textView = (TextView) getActivity().findViewById(R.id.fragment_b_text_view) by textView = (TextView) view.findViewById(R.id.fragment_b_text_view) and move it from onActivityCreated() to onCreateView().
Hope this helps.
I think your problem is when you can try to find the ID.
Try this textView = (TextView) view.findViewById(R.id.fragment_b_texT_view) where this view is your View view = inflater.inflate(R.layout.fragment_b, container, false);.

How to implement listener interface in fragment?

I am trying to communicate between an activity and the fragment that sits on top of it, I want new data (image/text - retrieved from the db) to be passed into the frag every time an onclick occurs (onclick is in the activity). I made a simple interface to test (let me know if this is not suitable for images or if it is too slow or inefficient), and I am trying to have it included in my fragment so when an onclick occurs the fragment changes the image and the text.
Here is the simple interface code:
public interface FragmentCommunicator {
public void passDataToFragment(String someValue);
}
Here is the activity code:
public class RandomActivity extends FragmentActivity implements ActivityCommunicator {
//viewpager adapter
private PageAdapter mAdapter;
private ViewPager viewPager;
//interface through which communication is made to fragment
public FragmentCommunicator fragmentCommunicator;
//Buttons for yes, no, skip
Button btnYesRandom, btnNoRandom, btnSkipRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random);
//set buttons
btnYesRandom = (Button) findViewById(R.id.btnYesRandom);
// Initializing pager
viewPager = (ViewPager) findViewById(R.id.random_pager);
//calling bundle to attach data to fragment
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
RandomFragment randFrag = new RandomFragment();
randFrag.setArguments(bundle);
//Setting up fragment
FragmentManager fm = getFragmentManager();
mAdapter = new PageAdapter(getSupportFragmentManager(), new UserUpVotesFragment(), randFrag, new UserDownVotesFragment());
viewPager.setAdapter(mAdapter);
// Here you would declare which page to visit on creation
viewPager.setCurrentItem(1);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
if(position !=1) {
//swiping to the right
if(position == 0) {
Log.e("Swiping", "SWIPING TO THE Right BUT RESET ERR");
getIntent().removeExtra("edttext");
}
//swiping to the left
if(position == 2) {
Log.e("Swiping", "SWIPING TO THE left BUT RESET ERR");
}
// RandomFragment randomFrag = (RandomFragment) getFragmentManager().findFragmentById(R.id.fra);
viewPager.setCurrentItem(1);
}
}
});
btnYesRandom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(fragmentCommunicator != null)
fragmentCommunicator.passDataToFragment("Hi from FragmentActivity");
}
});
}
Code for Fragment:
public class RandomFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//call data from activity bundle
String strtext = getArguments().getString("edttext");
View rootView = inflater.inflate(R.layout.fragment_random, container, false);
RelativeLayout random_frag_layout = (RelativeLayout) rootView.findViewById(R.id.random_frag_layout);
activityButton = (ImageView) rootView.findViewById(R.id.imagehere);
//setRetainInstance(true);
texthere = (TextView) rootView.findViewById(R.id.texthere);
texthere.setText(strtext);
return rootView;
}
//FragmentCommunicator interface implementation
public void passDataToFragment(String someValue){
activityAssignedValue = someValue;
Log.e("ACTIVITY", activityAssignedValue);
}
}
If you have only one fragment, then you can access it directly and send any data just via method: make your fragment a field and call your passDataToFragment() on it from activity.
To access an activity from fragment, call ((RandomActivity)getActivity()).activityMethod()
What is ActivityCommunicator?
If you wish to go down this route have your RandomActivity class implement the FragmentCommunicator interface, which should either be declared as an inner-public interface in the RandomFragment class say, or publicly (or package local) in its own file.

Passing Assigned Value of a Spinner from Fragment to Fragment within Viewpager NullPointerException

I've make it more simple and updated it based on the answers in my previous post: Adding Assigned Values in Spinner NullPointerException
I have a MainAcitivty that uses a ViewPager. I have 2 Fragments in my MainActivity (FragA and FragB)
In my FragA I have a spinner. While in FragB, I have a TextView and a Button.
Now what am I trying to do is, when I select "Hello" in my spinner, my int a will have a value of 5. And when I click the Button, 5 will display in the TextView.
Here's my code:
FragA
public class FragA extends Fragment {
Spinner spinner1;
String s1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fraga, container, false);
spinner1 = (Spinner) view.findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter_a = ArrayAdapter.createFromResource(getActivity(), R.array.spinner1,android.R.layout.simple_spinner_item );
spinner1.setAdapter(adapter_a);
s1 = spinner1.getSelectedItem().toString();
return view;
}
public int getInt() {
int a = 0;
if(s1.equals("Hello")) {
a = 5;
}
return a;
}
}
MainActivity
public class MainActivity extends FragmentActivity {
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
{
fragment = new FragA();
}
if (i == 1)
{
fragment = new FragB();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
public String get() {
FragA FragA = new FragA();
return Integer.toString(FragA.getInt());
}
}
FragB
public class FragB extends Fragment{
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragb, container, false);
textView = (TextView) view.findViewById(R.id.textview);
Button button = (Button) view.findViewById(R.id.button);
button.setOnClickListener(Click);
return view;
}
OnClickListener Click = new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(((MainActivity)getActivity()).get());
}
};
}
By the way, I have no problem passing the value of a from FragA to FragB when this is my code:
public int getInt() {
int a = 5;
return a;
}
But, it doesn't involve my spinner and that's not I want to do.
Here is a simple way to communicate between fragments.
In MainActivity, keep static instances of the fragments.
public static FragA fragmentA;
public static FragB fragmentB;
Now if you want to access FragB from FragA, write something similar:
((MainActivity) getActivity()).fragmentB.setSomething();
And Here is a better/proper way to communicate between fragments:
http://developer.android.com/training/basics/fragments/communicating.html

Categories