Scenario:
First user login and goes to mainactivity which contains a homefragment which opens by default. Now from here the user goes to new activity where I add some text to edit text and clicks add button which gets back the user back to home fragment which is in mainactivity.
Now my problem is how do I add this text to my listview.
As by default the home fragment loads for the first time it dosen't contain any bundle.
First when my Main Activity Loads this what triggers:
public class HomeFragment extends Fragment {
ListView lv;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
After loading the home fragment It has a list view where I need to add some data to it.
Now I go to new activity by clicking a menu option.
Here I add some text to the edittext and pass that data through intent back to mainactivity as shown below:
addtask = (Button) findViewById(R.id.btnaddlist);
findViewById(R.id.btnaddlist).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText edit = (EditText) findViewById(R.id.tskname);
Intent i = new Intent(AddTask.this,
MainActivity.class);
String TaskName = edit.getText().toString();
i.putExtra("NewTask", TaskName);
startActivity(i);
}
});
Lastly I'm getting the value using intent as shown below:
String AddedTask ;
if (intent.hasExtra("NewTask")) {
AddedTask = this.getIntent().getExtras().getString("NewTask");
Log.d("Task Added:",AddedTask);
Bundle bundle = new Bundle();
bundle.putString("Task Added", AddedTask);
HomeFragment fragobj = new HomeFragment();
fragobj.setArguments(bundle);
}
Now my question is I have a listview in homefragment so how do I add this value to the listview
I'm trying to use this way but logcat is showing me the null exception as when my mainactivity loads the home fragment loads first and I dont get any value from intent:
public class HomeFragment extends Fragment {
ListView lv;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
lv = (ListView)rootView.findViewById(R.id.tasklist);
Bundle b = getActivity().getIntent().getExtras();
if (b != null) {
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> Listadapter;
String ItemName = getArguments().getString("Task Added");
list.add(ItemName);
Listadapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
lv.setAdapter(Listadapter);
Listadapter.notifyDataSetChanged();
}
return rootView;
}
}
Can anyone help me out with this ?
1- From HomeFragment/MainActivity start you 2nd Activity AddTaskActivity using
startActivityForResult(addTaskIntent, CODE_ADD_TASK);
2- Now in your AddTaskActivity change btnaddlist callback to
#Override
public void onClick(View v) {
EditText edit = (EditText) findViewById(R.id.tskname);
Intent i = new Intent();
String TaskName = edit.getText().toString();
i.putExtra("NewTask", TaskName);
setResult(RESULT_OK, i);
finish();
}
3- In your MainActivity override the method onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == CODE_ADD_TASK) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
String taskName = data.getStringExtra("NewTask");
// send this data to your Fragment and add it to the list
}
}
}
You can add check for first time loading, like following.
String ItemName = getArguments().getString("Task Added", "");
if(ItemName != "") {
list.add(ItemName);
}
So it won't crash.
Related
I want to pass data from Activity to Fragment using Bundle (I used Bundle to passing data between 2 Fragment, and that's worked).
In my Activity I have a ListView, in the OnItemClickListener I want to open a new Fragment, and the Item, which clicked pass through the Activity to this Fragment. But the Item is null, so basically nothing is send to the Fragment.
Here is my Activity:
public class Jegyek extends AppCompatActivity {
View v;
DB mydb;
ListView listView;
private String teszt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jegyek);
listView = (ListView)findViewById(R.id.jegyekLista);
mydb = new DB(this);
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(this, "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
bundle.putString("Tantárgy neve", teszt);
Toast.makeText(Jegyek.this, teszt, Toast.LENGTH_SHORT).show();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, jegyekAllando);
ListView listaNezet = (ListView) findViewById(R.id.jegyekLista);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
);
}
}
public String getTanNev () {
System.out.println("WARNING: "+ teszt);
return teszt;
}
}
And my Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = new Bundle();
String tanNev = bundle.getStrin
g("Tantárgy neve");
Jegyek jegyAct = new Jegyek();
String tanNevv = jegyAct.getTanNev();
mydb = new DB(getActivity());
String jegyAtlag =String.valueOf(mydb.JegyekAtlaga(tanNev));
String jegyDarab =String.valueOf(mydb.JegyekDarabszama(tanNev));
return rootView;
}
}
When I realized, that the bundle is null, I try to pass that List Item through getter, so I changed my Fragment code for that:
Jegyek jegyek = new Jegyek();
String jegy = jegyek.getTanNev();
But that's not solved my problem, so I back to the Bundle, which also have some problem, but I can't find it. Intresting, that in the OnItemClickListener when I Toast the Item it's correct and works, but when I want to display in the console or pass to the Fragment, the value's is null.
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Hope this helps
Please follow this example:
In your activity, Pass data like
Bundle bundle = new Bundle();
bundle.putString("test", "Test Data");
// set in your testFragment Arguments
TestFragment testFragment = new TestFragment();
testFragment.setArguments(bundle);
And Receive Data from your TestFragment Like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String text = getArguments().getString("test");
return inflater.inflate(R.layout.fragment, container, false);
}
In fragment "jegyekAllando" you must get your string from onCreate() with Bundle data = getArguments(), but you create new bundle.
I'm passing value from adapter to fragment class,
Here adapter class,
rbFolder.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(selected != null)
{
selected.setChecked(false);
String meee = data.get(position).getTypeId();
System.out.println("*******so*inside********"+meee);
}
rbFolder.setChecked(true);
String so = data.get(position).getTypeId();
System.out.println("*******so*********"+so);
selected = rbFolder;
System.out.println("********selected*******"+selected);
Fragment homepage = new Fragment();
FragmentTransaction fragmentManager =((FragmentActivity)context).getSupportFragmentManager()
.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("name", so); //key and value
System.out.println("*****venki***meee*******"+so);
homepage.setArguments(bundle);
// fragmentManager.replace(R.id.content_frame, homepage);
fragmentManager.addToBackStack(null);
fragmentManager.commit();
}
});
In this, putstring working well but in my fragemt class i didnt receive values. I'm trouble in this place.
Here Fragmnet class,
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootview != null) {
ViewGroup parent = (ViewGroup) rootview.getParent();
if (parent != null)
parent.removeView(rootview);
}
try {
rootview = inflater.inflate(R.layout.homepage, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
Here I get values from adapter but this is not working,
Bundle bundle = ((Activity)context).getIntent().getExtras();
if (bundle != null)
{
String strtext=getArguments().getString("name");
System.out.println("*******strtext*********"+strtext);
}
return rootview;
}
First of All you have to call your HomeFragment() instead of fragment like that
Fragment homepage = new HomeFragment();
FragmentTransaction fragmentManager =((FragmentActivity)context).getSupportFragmentManager()
.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("name", so); //key and value
homepage.setArguments(bundle);
fragmentManager.replace(R.id.content_frame, homepage);
fragmentManager.addToBackStack(null);
fragmentManager.commit();
When you want to get value inside home fragment then
if( getArguments() != null)
String strtext = getArguments().getString("name");
follow steps one by one, copy Context context;
List rowItems;
onItemClickListner onItemClickListner; and pest into your adapter
then copy two constructor methods and then pest on item click method to pass data to fragment.
in your fragment class set adapter item on click listener code in this way...
madapter.setOnClickListener(new MyListAdapterTemp.onItemClickListner() {
#Override
public void onClick(String str) {
}
});
Context context;
List<String> rowItems;
onItemClickListner onItemClickListner;
public MyListAdapterTemp(Context context, List<String> items) {
this.context = context;
this.rowItems = items;
}
public void setOnClickListener(onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
holder.txtDesc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListner.onClick(rowItems.get(position).toString().trim().toUpperCase());
}
});
this method works fine on my app and for activity to fragment , fragment to activity we can pass data using interface but not this
way this is best and proper way to perform this type of operations.
Fragment homepage = new Fragment();
this is supposed to be your Fragment class name -
Fragment homepage = new MyFragment();
And Your Fragment be like -
public class MyFragment extends Fragment {
#Override
public void onCreate(...) {
Bundle b = getArguments(); //To get extras from Fragment
}
}
Other than that,
Bundle bundle = ((Activity)context).getIntent().getExtras();
This is used for an Activity. For Fragment you have to use getArguments()
My problems and needs are kept in comments. Any help and suggestions are appreciated. Need Output Like below:
This is what I perfectly Want. With Same recyclerView but different Value with Different Buttons
public class Recycler extends Fragment {
private List<Name> names;
RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.recyclerview,container,false);
rv= (RecyclerView) view.findViewById(R.id.rv);
LinearLayoutManager llm=new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
initializeData();
initializeAdapter();
return view;
}
private void initializeAdapter() {
rvadapter adapter=new rvadapter(names);
rv.setAdapter(adapter);
}
private void initializeData() {
names=new ArrayList<>();
//names.add(new Name("Nikesh"));
//There are three buttons on First Fragment, If Button 1 is pressed only textview should change and similarly rest for another two buttons
//Pass Data Here According To Button Pressed In the First Fragment
//Example
//If I pressed button 1 then print names.add(new Name("From First"));
//If I pressed button 1 then print names.add(new Name("From Second"));
//If I pressed button 1 then print names.add(new Name("From Third"));
//Better If I can pass here value From Click Listener from MainActivity Button1
}
}
//This is Main_Activity and its a Activity
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.img_boy:
// cardView cardview=new cardView();
Recycler rc=new Recycler();
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container,rc);
fragmentTransaction.addToBackStack(null);
//Wish I can Pass value from here
fragmentTransaction.commit();
break;
}
}
}
You can pass a value to a fragment using a Bundle.
Inside your OnClick
Recycler recycler = new Recycler();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
recycler.setArguments(bundle);
// ...
Inside your RecyclerFragment
private String mValue;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(getArguments() != null){
mValue = getArguments().getString("key");
}
}
You need to add an onClickListener interface to your RecyclerView.Adapter. With this you can return the Name for which button was clicked, then start a new Activity or inflate a new Fragment based on that.
I am using nav drawer. So i need from Fragment start Activity in which i start another Activity where i have ListView,clicking on which i must save data.
After save i need to return to Fragment where saved Data must be showing.
So here is my Fragment
public class ArmoryFragment extends Fragment {
public ArmoryFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_armory, container, false);
Button button = (Button) rootView.findViewById(R.id.button_rifles);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Rifles.class);
startActivity(intent);
}
});
return rootView;
}
}
and here is my activivty from where i need to return
public class Rifles extends Activity implements View.OnClickListener, OnItemSelectedListener {
DatabaseHelper db;
String BrandModel;
private RifleDAO rifleDAO;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rifles);
initList();
this.rifleDAO = new RifleDAO(this);
ListView listView = (ListView) findViewById(R.id.listView1);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, riflesList, android.R.layout.simple_list_item_1, new String[] {"rifle"}, new int[] {android.R.id.text1});
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
BrandModel= ((TextView)view).getText().toString();
String[] parts=BrandModel.split(" ");
String Brand=parts[0];
String Model = parts[1];
// need to return from somewhere here
}
});
} next is parser code... supose it is not needed
So how can I return from Activity to Fragment?
Well if you want to save data, I prefer adding the data to a table in your database (obviously you have a databaseHelper class so make you own table) and when you are back from your activity put extra a position you want and call :
selectItem(mCurrentSelectedPosition);
so mCurrentSelectedPosition is the position of the fragment that you want to be selected.
I have an Actiity where I have a simple Edittext and a button as shwown:
No I have a MainActivity which contains many fragments as shown:
This is my Code For passing edittext text to the main activity:
addlist = (ImageButton) findViewById(R.id.btnaddlist);
findViewById(R.id.btnaddlist).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText edit = (EditText) findViewById(R.id.txtlist);
Intent i = new Intent(CreateList.this,
MainActivity.class);
Bundle bundle = new Bundle();
String ItemName = edit.getText().toString();
// Add your data from getFactualResults method to bundle
bundle.putString("ListItemName", ItemName);
// Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
}
});
}
This is my Home fragment:
ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lv = (ListView) getView().findViewById(R.id.itemslistView);
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Bundle itemintent = getActivity().getIntent().getExtras();
String ItemName = itemintent.getString("ListItemName");
if (itemintent.getString("ListItemName").equals("ItemName")) {
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
list.add(ItemName);
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> Listadapter;
Listadapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
Listadapter.notifyDataSetChanged();
}
return rootView;
}
I'm not getting any error in logcat..But its not able to add any text to listView on MainActivity.
You made the adapter but didn't call ListView#setAdapter()
Change your Home fragment like that:
ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
lv = (ListView) getView().findViewById(R.id.itemslistView);
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Bundle itemintent = getActivity().getIntent().getExtras();
String ItemName = itemintent.getString("ListItemName");
if (ItemName.equals("ItemName")) {
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
list.add(ItemName);
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> Listadapter;
Listadapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
lv.setAdapter(Listadapter);
Listadapter.notifyDataSetChanged();// i don't think this line is necessary
}
return rootView;
}
The better way to do this is as below:
Start main activity
give a button to add item
on click of this button, call the activity(use startActivityForResult ) having edittext and a button
and on this button click, setResult with intent extras and finish this activity.
it will to MainActivity. Here write your onActivityResult method and handle it based on the result code. get your data from intent here.
Hope this answer helps you.