How to run only one fragment on screen? - java

I want to run a single fragment from another fragment. I try:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.lecturers_fragment,
container, false);
ListView list = (ListView) rootView.findViewById(R.id.lecturersList);
final List<Lecturer> allLecturersList = LecturerDatabaseHelper
.getAllLecturers(getActivity());
if (allLecturersList != null) {
LecturerItemAdapter lecturerAdapter = new LecturerItemAdapter(
mCurrentActivity, allLecturersList);
list.setAdapter(lecturerAdapter);
}
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int index, long id) {
Lecturer lecturer = allLecturersList.get(index);
L.i("Boulder name is playing link it contains"
+ lecturer.getName());
Intent intent_lecturer = new Intent(mCurrentActivity,
LecturerFragment.class);
intent_lecturer.putExtra(LecturerFragment.SELECTED_LECTURER,
lecturer);
mCurrentActivity.startActivity(intent_lecturer);
}
});
return rootView;
}
In my logcat i have this:
03-25 22:04:36.092: E/AndroidRuntime(12453): Caused by: java.lang.ClassCastException: com.asi.sesjaapp.view.LecturerFragment cannot be cast to android.app.Activity
How can I do it?

Intent intent_lecturer = new Intent(getActivity(), YourActivity.class);
intent_lecturer.putExtra(LecturerFragment.SELECTED_LECTURER, lecturer);
mCurrentActivity.startActivity(intent_lecturer);
You are in a fragment, instead of mCurrentActivity just give your parent activity, something like this:
new Intent(getActivity() , LecturerFragment.class);
and again it looks like LecturerFragment.class is a fragment it should be an activity.
Note: Make sure your parent activity extends FragmentActivity
If this answer didn't help you please post your Parent Activity code and fragments code.

Related

How take image uri from my array declared in one fragment and pass it to other fragment?

I want to pass image uri from my array images[] at 0 position to other fragment.
This is my fragment from which i want to pass in onclick method at postion==0.
public class OrganicAcidFragment extends Fragment {
String[] product_name={"Formic Acid","Acetic Acid","Propionic Acid",};
String[] product_cn={"CH2O2","CH3COOH","C3H602"};
int[] images={R.drawable.formicacid,R.drawable.aceticacidjpg,R.drawable.propionicacid};
ListView list;
String quantity;
String price;
FragmentManager fm;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.i_fragment_organic_acid, container, false);
fm=getFragmentManager();
MyAdapter adapter=new MyAdapter(getActivity(),product_name,images,product_cn,quantity,price);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position==0){
PurchaseFragment ldf = new PurchaseFragment ();
Bundle args = new Bundle();
args.putString("product_name", product_name[0]);
args.putString("product_cn", product_cn[0]);
ldf.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.content_frame, ldf).commit();
}
if(position==1){
fm.beginTransaction().replace(R.id.content_frame,new OrganicBaseFragment()).addToBackStack("chemicalorganicfragment").commit();
}
if(position==2){
fm.beginTransaction().replace(R.id.content_frame,new OrganicBaseFragment()).addToBackStack("chemicalorganicfragment").commit();
}
}
});
return rootview;
}
}
In this fragment i want to get that data:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.i_fragment_purchase, container, false);
String product_names = getArguments().getString("product_name");
String product_cns = getArguments().getString("product_cn");
imagee=(ImageView)rootview.findViewById(R.id.productimage);
cancel= (Button) rootview.findViewById(R.id.cancel);
address= (EditText) rootview.findViewById(R.id.address);
name.setText(product_names);
cn.setText("("+product_cns+")");
return rootview;
}
Both fragments are in same activity.
How can i do it?
I think best and easiest way to send data between running activities and fragments is LocalBroadcast.
Intent intent = new Intent("some_name");
intent.putExtra("some_data_key", "some_data_value");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
This is how to send local broadcast.
For listen local broadcast you must register that broadcast in onCreate() (If listener is Activity) or onCreateView() (If listener is fragment) or whenever you want to receive that broadcast:
LocalBroadcastManager.getInstance(this/*here is context*/).registerReceiver(someReceiver,
new IntentFilter("some_name"));
This is broadcast receiver to receive data:
BroadcastReceiver someReceiver= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String data= intent.getStringExtra("some_data_key");
//Here do whatever you want with data
//It isn't must be a string. If you want to send a object you must make object class implement Parcelable properly.
}
};
In the end, don't forget to unregister this broadcast receiver. Do it in onDestroy() or whereever you want.
LocalBroadcastManager.getInstance(this).unregisterReceiver(someReceiver);
You can use bundle to send data from one fragment to another.
//Put the value
YourNewFragment ldf = new YourNewFragment ();
Bundle args = new Bundle();
args.putString("YourKey", "YourValue");
ldf.setArguments(args);
//Inflate the fragment
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
In onCreateView() of another fragment:
//Retrieve the value
String value = getArguments().getString("YourKey");

transfer data between 2 fragments of a TabLayout Android Studio

So I have an app with a TabLayout. In there, I created 2 tabs (fragments).My first fragment is OngletCours and the 2nd one OngletNotes.
I have a ListView in the first tab/fragment. I would like to transfer the Item I clicked in that ListView to the 2nd Fragment to a TextView.
I have already tried something but I get a NullPointerException at line 23:
03-06 09:38:32.874 23677-23677/com.example.dasilvadd.students E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.dasilvadd.students.OngletNotes.onCreateView(OngletNotes.java:23)
here's the code from my 1st tab OngletCours (Only the setOnItemClickListener):
final ListView l1 = (ListView) rootView.findViewById(R.id.ListCours);
l1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
OngletNotes fragment = ((Onglets)getActivity()).getOngletNotes ();
if(fragment != null) {
l1.getItemAtPosition(i);
//Put the value
OngletNotes onotes = new OngletNotes();
Bundle args = new Bundle();
args.putString("Item","l1.getItemAtPosition(i)");
onotes.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.container, onotes).commit();
}
((Onglets)getActivity()).goToFragment(1);
}
});
return rootView;
}
Here's the code from my 2nd tab OngletNotes:
public class OngletNotes extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.ongletnotes, container, false);
//where i want to insert the selectedItem
TextView Cours = (TextView)rootView.findViewById(R.id.TVCours);
//Retrieve the value
//THE ERROR IS HERE !
String cours = getArguments().getString("Item");
Cours.setText(cours);
return rootView;
}
public static OngletNotes newInstance() {
OngletNotes fragment = new OngletNotes();
return fragment;
}
So, I don't know how to transfer the selected Item into the 2nd tab.
Do I have to create methodes in my TabbedActivity called Onglets? Please tell me if you need the code for that class as well.
Thank you in advance.
I think you got a bit confused in your logic. You are checking for null and then not doing anything if the fragment is null.
You can simplify it like this:
First check if fragment is null , if so create a new instance, then
put the arguments outside the if/else so you make sure you get them every time.
Also put your string item in a variable.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
OngletNotes fragment = ((Onglets)getActivity()).getOngletNotes ();
if(fragment == null) {
fragment = OngletNotes.getInstance();
}
String item = adapterView.getItemAtPosition(i).toString();
//Put the value
Bundle args = new Bundle();
args.putString("Item",item);
fragment.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();
}

Overriding an adapter

I use an adapter to manipulate my listView , to have a nicer result i overrided the adapter. the problem is that when i use "setOnItemClickListener" to open another fragment with getting the content of the clicked item nothing happened!
ClientAdapter adapter = new ClientAdapter(
getActivity(),R.layout.item_client, R.id.textV, clients);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3 {
FragmentManager fragmentManager = getFragmentManager();
Client t = (Client) lv.getItemAtPosition(arg2);
Modifier_Client fargmentACharger = new Modifier_Client();
fargmentACharger.setClient(t);
fragmentManager.beginTransaction().replace(R.id.container, fargmentACharger).addToBackStack(null).commit();
}
});
It's not a clear what the problem do you have
onItemClickListener don't work ?
You can't send data to another fragment ?
I don't see how you send data to another fragment, but you should use something like this:
Bundle args = new Bundle();
args.putString("client", t);
fargmentACharger.setArguments(args);
or parselable the class Client
An get it at fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
.....
client = getArguments().getString("client");
}

Android Studio - Fragment button action

I tried to make an application that shows a fragment at start then you can change that fragment to an other one with a button in the first fragment. But when I put the button action in the fragments java, it won't start and I get the nullpointerexception error. Could you tell me why?
public class Fragment_main extends Fragment {
FragmentManager fm = getFragmentManager();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Button button_inditas = (Button) getView().findViewById(R.id.button_inditas);
button_inditas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fm.beginTransaction().replace(R.id.content_frame, new Fragment_1()).commit();
}
});
return inflater.inflate(R.layout.fragment_main,container,false);
}
}
But when I put the button action in the fragments java, it won't start and I get the nullpointerexception error. Could you tell me why?
Well I see some errors on your code...
First of all you can't call getView() if you haven't inflated one, it means that you MUST inflate a view as i'll put on my answer and then you can avoid the getView() and use that view itself.
And instead of returning the inflater you have to return your View
This is how your Fragment should look like:
public class Fragment_main extends Fragment {
public Fragment_main() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,container,false);
Button button_inditas = (Button)rootView.findViewById(R.id.button_inditas);
button_inditas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction ();
fragmentTransaction.add (R.id.content_frame, new Fragment_1());
fragmentTransaction.commit ();
});
return rootView;
}
}
You have to inflate the view first and use the view returned by that instead of getView ().
View view = inflater.inflate (...);
and then
... = (Button) view.findView(...);
This happens because the view that is returned by getView () hasn't been created yet, so getView() returns null.

Nullpointerexception thrown when trying to findViewById

I have the following Activity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new StartFragment())
.commit();
}
Button login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
startActivity(intent);
}
});
}
I get a NPE when I try to invoke findViewByID for R.id.loginButton, and I'm guessing this is because loginButton is within a separate Fragment, which I have as:
public static class StartFragment extends Fragment {
public StartFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
However, I am unsure of how to fix this so that I can find the loginButton ID. I haven't worked with fragments before, so I realize I may be using them/implementing them incorrectly. fragment_main contains a few buttons in a LinearLayout, and activity_main has nothing but a single FrameLayout.
Try to implement your onCreateView(...) in Fragment like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
View something = rootView.findViewById(R.id.something);
something.setOnClickListener(new View.OnClickListener() { ... });
return rootView;
}
The Button is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.
Write code to initialize button from fragment becuase your button is into fragment layout not into activity's layout.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
Button login = (Button) rootView.findViewById(R.id.loginButton);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
LoginActivity.class);
startActivity(intent);
}
});
return rootView;
}
And remove the login button related code from onCreate of Activity.
findViewById() works with reference to a root view.
Without having a view in the first place will throw a null pointer exception
In any activity you set a view by calling setContentView(someView);.
Thus when you call findViewById() , its with reference to the someView.
Also findViewById() finds the id only if its in that someView. So in you case null pointer exception
For fragments, adapters, activity, .... any view's findViewById() will only find if the id exixts in the view
Alternately if you are inflating a view, then you can also use inflatedView.findViewById() to get a view from that inflatedView
In short make sure you have the id in your layout you are referring to or make findViewById() call in appropriate place(Ex. adapters getView(), activity's onCreate() or onResume() or onPause() , fragments onCreateView(), ....)
Also have an idea about UI & background thread's as you cannot efficiently update UI in bg-threads

Categories