Overriding an adapter - java

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");
}

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();
}

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.

How to run only one fragment on screen?

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.

Press back button current fragment persist not restore previous fragment

I have Fragment Activity which contains a Framelayout for fragment transition. A fragment named LeadActiviy extends SherlockListFragment contains Asynctask, in AsyncTask's method onPostExcute contents else block statement. In else block current fragment replaced by ItemNotFound extends Fragment. After set the contents of ItemNotFound in framelayout when press back button it's current state persist & not appear its previous fragment. Please help me to solve issue-
Code of AsyncTask's method onPostExecute from LeadActivity ...
protected void onPostExecute(String file_url){
pDialog.dismiss();
//FragmentManager fm=getFragmentManager();
//final FragmentTransaction ft=fm.beginTransaction();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(success==1){
// TODO Auto-generated method stub
ListAdapter adapter = new SimpleAdapter(
getActivity(), leadlist,R.layout.leadlistview, new String[] { Tag_Lead},
new int[] { R.id.textView6});
// updating listview
setListAdapter(adapter);
//get leads of order
ListView lv=getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String pid=((TextView) arg1.findViewById(R.id.textView6)).getText().toString();
LeadDetail frag=new LeadDetail();
Bundle bnd=new Bundle();
bnd.putString("lead",pid);
frag.setArguments(bnd);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.replace(R.id.content_frame, frag);
ft.addToBackStack(null);
ft.commit();
}
});
}
else {
String e="Lead Not Found";
ItemNotFound frag=new ItemNotFound();
//Frag1 frag=new Frag1();
Bundle bnd=new Bundle();
bnd.putString("data",e);
frag.setArguments(bnd);
FragmentManager fm1=getFragmentManager();
FragmentTransaction ft1=fm1.beginTransaction();
ft1.replace(R.id.content_frame, frag,st);
ft1.addToBackStack(st);
ft1.commit();
}
}
Code for ItemNotFound.............
public class ItemNotFound extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
View V = inflater.inflate(R.layout.itemnotfound, container, false);
TextView tv=(TextView)V.findViewById(R.id.textView7);
Bundle bnd=this.getArguments();
String s=bnd.getString("data");
tv.setText(s);
return V;
}
}
You can see my solution here.
I have a ViewPager with three pages which contains Fragments. In first page, I have a ListFragment and onListItemClick I replace that Fragment with another one. When Back Button is pressed, I go back to ListFragment.

Categories