Adding Items to ListView from Edittext - android

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.

Related

Pass data between Activity and Fragment

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.

Error Image listview fragment

enter image description hereBelow is the coding i have and it seems i have problem on the
AgentAdapter adapter = new AgentAdapter(getActivity(), R.layout.list_agent, member_names, profile_pics);
How do i use image and text together for the list adapter i have in my fragment? Please help.
public class AgentFragment extends Fragment{
String[] member_names;
TypedArray profile_pics;
ListView mylistview;
String[] agentname={"Robert","Shanni","Rachel","Mady","Nikhil"};
Integer [] imgid = {R.drawable.robert,R.drawable.shanni,R.drawable.rachael,R.drawable.maddy_pic,R.drawable.nikhil_pic};
public AgentFragment(){
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_layout1, null);
setupList(view);
return view;
}
private void setupList(View view){
AgentAdapter adapter = new AgentAdapter(getActivity(), R.layout.list_agent, member_names, profile_pics);
mylistview = (ListView) view.findViewById(R.id.listView);
mylistview.setAdapter(adapter);
}
}
Since its possible that the fragment has not been placed in any activity at runtime you can afford for this by changing the getActivity() to be the context from the view parameter:
private void setupList(View view){
AgentAdapter adapter = new AgentAdapter(view.getContext(), R.layout.list_agent, member_names, profile_pics);
mylistview = (ListView) view.findViewById(R.id.listView);
mylistview.setAdapter(adapter);
}

Adding items to listview from bundle in fragment

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.

spinner won't populate from my array [duplicate]

This question already exists:
Spinner will not populate and won't set arrayadapter
Closed 8 years ago.
My app redirects me to a different screen from my home with the tap of a button. Once, i reach my city screen my spinner is visible. But it doesn't contain any elements from my array. Nothing force closes or anything, but it doesn't work.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_city, container, false);
String[] test = {"test1", "test2"};
Spinner spin = (Spinner) v.findViewById(R.id.countries);
ArrayAdapter<String> adapt = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, test);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapt);
return v;
}
You need to have the below.
public static PlaceHolderFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_city, container, false);
String[] test = {"test1", "test2"};
Spinner spin = (Spinner) v.findViewById(R.id.countries);
ArrayAdapter<String> adapt = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, test);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapt);
return v;
}
}
Also use getActivity() to get the context of hosting activity.

Spinner values get doubled every time I click on the activity

I am using a fragment activites. One of my activity has a spinner. I set its adapter. The problem is whenever I switch to that activity, spinner values increase. It actually adds the the same values into the spinner without removing the previous ones. How to solve it? my code is following:
public class AddPackageFragment extends Fragment {
View rootView;
EditText packageName;
EditText packageNumber;
Spinner network;
CheckBox sim1;
CheckBox sim2;
RadioGroup type;
RadioGroup through;
Button addPackage;
Button actDetails;
ArrayList<String> networks = new ArrayList<String>();
ArrayAdapter<String> adapter;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.add_package, container, false);
initializeViews();
setNetworks();
setSpinner();
return rootView;
}
void initializeViews() {
packageName = (EditText)rootView.findViewById(R.id.pName);
packageNumber = (EditText)rootView.findViewById(R.id.pNumber);
network = (Spinner)rootView.findViewById(R.id.networkS);
sim1 = (CheckBox)rootView.findViewById(R.id.sim1);
sim2 = (CheckBox)rootView.findViewById(R.id.sim2);
type = (RadioGroup)rootView.findViewById(R.id.typeGroup);
through = (RadioGroup)rootView.findViewById(R.id.throughGroup);
addPackage = (Button)rootView.findViewById(R.id.addPackage);
actDetails = (Button)rootView.findViewById(R.id.activationDetails);
context = getActivity().getApplicationContext();
addPackage.setActivated(false);
actDetails.setActivated(false);
}
void setNetworks() {
networks.add("Mobilink");
networks.add("Telenor");
networks.add("Ufone");
networks.add("Warid");
networks.add("Zong");
networks.add("Add New");
}
void setSpinner() {
adapter = new ArrayAdapter<String>(context, R.layout.spinner_item, networks);
network.setAdapter(null);
network.setAdapter(adapter);
}
}
Try this:
void setNetworks() {
networks.clear()
networks.add("Mobilink");
networks.add("Telenor");
networks.add("Ufone");
networks.add("Warid");
networks.add("Zong");
networks.add("Add New");
}
I think it's because your array not cleared, not the spinner adapter.
To elaborate on #Dimmerg
Based on the Fragment lifecycle, your onCreateView will get called more than one time. So you have to take that into consideration and clear values (or Lists) accordingly.

Categories

Resources