How to pass data between two activities - java

I have a NetworkList class which has a arraylist of type string. I am using parcelable interface in it.but i am getting only the first element of arraylist in my new activity.
how can i get all the elements?
here is NetworkList class
public class NetworkList implements Parcelable{
private ArrayList<String> name=new ArrayList<String>();
private ArrayList<String> id=new ArrayList<String>();
#SuppressWarnings("unchecked")
public NetworkList(Parcel in) {
// TODO Auto-generated constructor stub
name=in.readArrayList(null);
id=in.readArrayList(null);
}
public NetworkList() {
// TODO Auto-generated constructor stub
}
public void setName(String tempValue) {
// TODO Auto-generated method stub
this.name.add(tempValue);
}
public void setid(String tempValue) {
// TODO Auto-generated method stub
this.id.add(tempValue);
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeList(name);
dest.writeList(id);
}
public ArrayList<String> getname() {
return name;
}
public static final Creator<NetworkList> CREATOR = new Parcelable.Creator<NetworkList>() {
public NetworkList createFromParcel(Parcel in) {
return new NetworkList(in);
}
public NetworkList[] newArray(int size) {
return new NetworkList[size];
}
};
}
here is how where i pass it
Intent(AllNetworkActivity.this,WorkActivity.class);
intent.putExtra("name",network);
startActivity(intent);
}});
}
here is how i retrieve it
Bundle extras=getIntent().getExtras();
NetworkList network=(NetworkList)extras.getParcelable("name");
String name[]=new String[network.getname().size()];
for(int i=0;i<network.getname().size();i++){
name[i]=network.getname().get(i);
}
setListAdapter(new ArrayAdapter<String>(this,R.layout.work,name));
hope u are able to help me know

You should also look into Application class in Android. You can define global variables in there which can be accessed by all activities. However Bundle is the most popular and right method for sending data between activities.

Try using appropriate methods to serialize List<String>:
public NetworkList(Parcel in) {
in.readStringList(name);
in.readStringList(id);
}
public void writeToParcel(Parcel dest, int flags) {
// log the number of elements - check that this is actually what you expect it to be
// use only during development
Log.i("NetworkList"," number of elements = "+name.size())
dest.writeStringList(name);
dest.writeStringList(id);
}

first
Intent Jan = new Intent(Months.this,Holiday.class);
Jan.putExtra("ListCount", "Jan");
startActivity(Jan);
then
Bundle extras = getIntent().getExtras();
String data = extras.getString("ListCount");
if(data.equals("Jan")){
TextView txtMonth = (TextView)findViewById(R.id.txtMonth);
txtMonth.setText("January");
TextView txtDetail = (TextView)findViewById(R.id.txtDetail);
txtDetail.setText(R.string.JanHol);
}
check this post I wrote. Hope this will help you.

Related

Javafx right click edit listView item and similar methods

I am building a JavaFX todo list and am not sure how to continue. The right click popup menu works fine but I am not sure how to edit/change the contents of the ListView other than just removing them.
LocalEvent e = a string somehow?
I am trying to do 4 total things in a right click popup menu in Javafx:
Done is to place a check mark next to and strikeout the item.
Nest is to create a nested list from a list item (no idea at all how).
Edit is to make the list item editable and save the chages.
Remove works :)
I have done this by adding the following to the fxml file:
<JFXListView fx:id="eventList" editable="true" layoutX="24.0" layoutY="106.0" prefHeight="354.0" prefWidth="939.0">
<contextMenu>
<ContextMenu>
<items>
<MenuItem fx:id="popUp" mnemonicParsing="false" onAction="#Done" text="Done" />
<MenuItem fx:id="popUp3" mnemonicParsing="false" onAction="#Remove" text="Remove" />
<MenuItem fx:id="popUp1" mnemonicParsing="false" onAction="#Nest" text="Nest" />
<MenuItem fx:id="popUp2" mnemonicParsing="false" onAction="#Edit" text="Edit" />
</items>
</ContextMenu>
</contextMenu></JFXListView>`
Here is my Controller.java file:
package application;
import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextField;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.DatePicker;
import javafx.scene.control.MenuItem;
import javafx.scene.input.MouseEvent;
public class Controller implements Initializable{
#Override
public void initialize(URL url, ResourceBundle rb) {
datePicker.setValue(LocalDate.now());
eventList.setExpanded(true);
eventList.depthProperty().set(1);
}
#FXML
private MenuItem popUp;
#FXML
private JFXTextField textBox;
#FXML
private JFXListView<LocalEvent> eventList;
ObservableList<LocalEvent> list = FXCollections.observableArrayList();
#FXML
private JFXButton AddButton;
#FXML
private DatePicker datePicker;
#FXML
void Submit(ActionEvent event) {
list.add(new LocalEvent(datePicker.getValue(), textBox.getText()));
eventList.setItems(list);
datePicker.setValue(LocalDate.now());
textBox.setText("");
}
#FXML
public void onEnter(ActionEvent event){
list.add(new LocalEvent(datePicker.getValue(), textBox.getText()));
eventList.setItems(list);
datePicker.setValue(LocalDate.now());
textBox.setText("");
}
#FXML
void Done(ActionEvent event) {
int index = eventList.getSelectionModel().getSelectedIndex();
String str = list.get(index).toString();
str = "[✓] " + str;
LocalEvent e = null; // <- how to put a string in here?
list.set(index, e);
eventList.setItems(list);
//eventList.setItems(list.set(index, element));
}
#FXML
void Remove(ActionEvent event) {
// remove selected task
list.remove(eventList.getSelectionModel().getSelectedIndex());
}
#FXML
void Nest(ActionEvent event) {
System.out.println("How the hell do I do that? lol");
// check for nested level
// create a nested list item
}
#FXML
void Edit(ActionEvent e) {
System.out.println("Edit selection");
eventList.setEditable(true);
int index = eventList.getSelectionModel().getSelectedIndex();
eventList.scrollTo(index);
eventList.layout();
eventList.edit(index);
eventList.layout();
}
}
LocalEvent is a java class file as follows:
package application;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javafx.beans.InvalidationListener;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
public class LocalEvent implements ObservableList<LocalEvent> {
private String description;
private LocalDate date;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public LocalEvent(LocalDate date, String description) {
this.setDate(date);
this.setDescription(description);
}
#Override
public String toString() {
return "At " + this.getDate() + ": " + this.getDescription();
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean contains(Object o) {
// TODO Auto-generated method stub
return false;
}
#Override
public Iterator<LocalEvent> iterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public Object[] toArray() {
// TODO Auto-generated method stub
return null;
}
#Override
public <T> T[] toArray(T[] a) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean add(LocalEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean remove(Object o) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean containsAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean addAll(Collection<? extends LocalEvent> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean addAll(int index, Collection<? extends LocalEvent> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean removeAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean retainAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
#Override
public LocalEvent get(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public LocalEvent set(int index, LocalEvent element) {
// TODO Auto-generated method stub
return null;
}
#Override
public void add(int index, LocalEvent element) {
// TODO Auto-generated method stub
}
#Override
public LocalEvent remove(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public int indexOf(Object o) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int lastIndexOf(Object o) {
// TODO Auto-generated method stub
return 0;
}
#Override
public ListIterator<LocalEvent> listIterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public ListIterator<LocalEvent> listIterator(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<LocalEvent> subList(int fromIndex, int toIndex) {
// TODO Auto-generated method stub
return null;
}
#Override
public void addListener(InvalidationListener listener) {
// TODO Auto-generated method stub
}
#Override
public void removeListener(InvalidationListener listener) {
// TODO Auto-generated method stub
}
#Override
public void addListener(ListChangeListener<? super LocalEvent> listener) {
// TODO Auto-generated method stub
}
#Override
public void removeListener(ListChangeListener<? super LocalEvent> listener) {
// TODO Auto-generated method stub
}
#Override
public boolean addAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean setAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean setAll(Collection<? extends LocalEvent> col) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean removeAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean retainAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public void remove(int from, int to) {
// TODO Auto-generated method stub
}
}
Any help at all appreciated.
The first thing that stands out was mentioned in the comments: your LocalEvent shouldn't implements ObservableList, it's just a data holder. You probably will want it to also hold a boolean to see if it's completed:
public class LocalEvent {
private String description;
private LocalDate date;
private boolean completed = false;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public void setCompleted(boolean completed) {
this.completed= completed;
}
public LocalEvent(LocalDate date, String description) {
this.setDate(date);
this.setDescription(description);
}
#Override
public String toString() {
String base = "At " + this.getDate() + ": " + this.getDescription();
return completed ? "[✓] " + base : base;
}
}
I don't know what the jfoenix controls are, but I'll assume they are close enough to JavaFX standard controls. The ListView should be bound to the list of events:
ObservableList<LocalEvent> list = FXCollections.observableArrayList();
ListView<LocalEvent> eventList = new ListView<>(list);
(I would also rename the lists to something that makes more sense.)
Now any change to list will be reflected in eventList so you don't need to touch eventList. This allows your done method to look like:
#FXML
void done(ActionEvent event) {
int index = eventList.getSelectionModel().getSelectedIndex();
LocalEvent localEvent = list.get(index);
localEvent.setCompleted(true);
list.set(index, localEvent);
}
Note that we needed to reset the item in the list because it doesn't know that a field of the LocalEvent instance has changed. You can make it that the fields also report changes by using an extractor, see here and many other answers here about it.
Editing depends on the cell used by the ListView, I would suggest reading about it in the docs and other questions here. Note that you probably want to be able to edit the description and date separately and not the whole toString value, so you'll have to provide a mechanism for that like bringing back the DatePicker.
Nesting depends on what you want it to look like. You might need to define your own cell factory, but consider just adding an indentation, via "\t"s, which will make it looks nested. If you really need a nesting in the data model, then each LocalEvent will have to hold its own ObservableList<LocalEvent> nestedEvents.
Also, method names should start with a lowercase.

JCombobox using hasmap/ no point model

Hey i am looking for solving a problem i need to make a model for jcombobox.
I have a :
Map<Integer, Pathes_format> profiles =new HashMap<Integer, Pathes_format>();
I wana to show on jcombobox pathes_format.getname will be displayed at index pathes_format.GetiD i never wrote or touch a abstract class or models.
Here what i made
package subDialogs;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;
import json.Pathes_format;
public class PatheseModel implements ComboBoxModel {
Map<Integer, Pathes_format> profiles =new HashMap<Integer, Pathes_format>();
int index=-1;
#Override
public int getSize() {
// TODO Auto-generated method stub
return profiles.size();
}
#Override
public Object getElementAt(int index) {
// TODO Auto-generated method stub
return profiles.get(index);
}
#Override
public void addListDataListener(ListDataListener l) {
// TODO Auto-generated method stub
}
#Override
public void removeListDataListener(ListDataListener l) {
// TODO Auto-generated method stub
}
#Override
public void setSelectedItem(Object anItem) {
// TODO Auto-generated method stub
}
#Override
public Object getSelectedItem() {
// TODO Auto-generated method stub
return null;
}
//void addElement(Object obj){
//
//}
void insertElementAt(Object obj, int index) {
profiles.put(index, (Pathes_format) obj);
}
void removeElement(Object obj) {
Pathes_format tmp = profiles.get(obj);
tmp=null;
}
void removeElementAt(int index){
profiles.remove(index);
}
}
I don't know is this correct :/. Mby i should make for a format patches single not for map; and add ability to add map??

I can't transfer an object from one activity to another

I want to send an object from one Details Activity to Persons Activity. I followed the tutorials but I get the following error:
12-19 08:19:00.434: E/AndroidRuntime(1011): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workingonlist/com.example.workingonlist.Persons}: android.os.BadParcelableException: Parcelable protocol requires a Parcelable.Creator object called CREATOR on class com.example.workingonlist.Person
Here is the Person model:
public class Person implements Parcelable {
private String name;
private String surname;
private String gender;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(Parcel in){
name= in.readString();
surname= in.readString();
gender= in.readString();
}
public Person(String name,String surname,String gender){
this.name=name;
this.surname=surname;
this.gender=gender;
}
// getters and setters
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(surname);
dest.writeString(gender);
}
private Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
#Override
public Person createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Person(source);
}
#Override
public Person[] newArray(int size) {
// TODO Auto-generated method stub
return new Person[size];
}
};
}
This is Details Activity which I want to send Person object.
private View.OnClickListener onClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==btn_save.getId()){
Person p = new Person();
p.setName(et_name.getText().toString());
p.setSurname(et_surname.getText().toString());
switch(rg.getCheckedRadioButtonId()){
case R.id.button1:{
p.setGender("Male");
break;
}
case R.id.button2:{
p.setGender("Female");
break;
}
}
Intent i = new Intent(Details.this,Persons.class);
i.putExtra("person",p);
startActivity(i);
}
}
};
And here is the Persons Activity which I want to get Person object.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
PersonAdapter adapter = new PersonAdapter();
setContentView(R.layout.persons);
Bundle b = getIntent().getExtras();
if (b != null) {
Person p = b.getParcelable("person");
adapter.add(p);
}
setListAdapter(adapter);
}
What can I do in order to solve this problem ? Any help is appreciated.Thanks in advance.
You need to set your CREATOR public static final:
public static final Parcelable.Creator CREATOR = new Parcelable.Creator()
Look at this tutorials which deals with your issue
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
public Person createFromParcel(Parcel in) {
return new Person(in);
}
public Person[] newArray(int size) {
return new Person[size];
}
};
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
For some reason I can't add a comment to Festus Tamakloe's answer, but I just wanted to add that this helped me. I was following some tutorials which was using the static creator. I didn't have "public" on it!
So make sure you have public on it.

android dictionary int, Imageview

I am failing to put objects in dictionary and get them, I want to put imageViews against int but failing without any error
dictionary declared as:
Dictionary<Integer, ImageView> dictPlayerAll = new Dictionary<Integer, ImageView>(){
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public ImageView remove(Object key) {
// TODO Auto-generated method stub
return null;
}
#Override
public ImageView put(Integer key, ImageView value) {
// TODO Auto-generated method stub
return null;
}
#Override
public Enumeration<Integer> keys() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public ImageView get(Object key) {
// TODO Auto-generated method stub
return null;
}
#Override
public Enumeration<ImageView> elements() {
// TODO Auto-generated method stub
return null;
}
};;
here putting values in dictionary
int mTag = iv.getTag();//its my imageview
dictPlayerAll.put(mTag, iv);
but it shows zero size
Your update makes more sense, but the Dictionary class is still obselete. From the documentation:
java.util
Class Dictionary
...
Note: Do not use this class since it is obsolete.
Since you want to create a table indexed by Integers (new Dictionary<Integer, ImageView>()) we should use a SparseArray.
Also when you use setTag() you convert your Integer to an Object and every time you use getTag() you are converting your Integer back from an Object. This works, but if you can use getId() it will be faster.
I recommend this:
SparseArray<ImageView> allPlayers = new SparseArray<ImageView>();
...
allPlayers.put(iv.getId(), iv);

Implement methods of an implemented List to an ArrayList

I know what to do with my programming code, but I just don't know why we have to do it.
My ArrayList class implements a List<E> interface. This means I have to copy all methods in my List interface to my ArrayList class. This is to stop the error of my ArrayList class saying: "ArrayList is not abstract and does not override abstract method iterator(int)" error. Can someone explain that to me in more detail?
Also: When I used the auto correct in NetBeans it says statements after each method "throw new UnsupportedOperationException("Not supported yet.");". Why?
Here's my code:
public class ArrayList<E> implements List<E> {
private E[] elementData;
private int elementCount;
private int capacityIncrement;
private static final int INVALID_INDEX=-1;
private static final int DEFAULT_CAPACITY = 100;
public ArrayList() {
capacityIncrement = 0;
elementData = (E[]) new Object[DEFAULT_CAPACITY];
}
public ArrayList(int capacity) {
this.capacityIncrement = 0;
this.elementData = (E[]) new Object[capacity];
}
public ArrayList(int capacity, int increment) {
this.capacityIncrement = increment;
this.elementData = (E[]) new Object[capacity];
}
private static class ArrayListIterator<E> implements Iterator<E> {
private ArrayListIterator(ArrayList c) {
elementData = c;
}
public interface List<E> {
public int size();
public boolean isEmpty();
public void clear();
public boolean contains(E element);
public void add(E element);
public boolean remove(E element);
public E elementAt(int index);
public int indexOf(E element);
public void insertElementAt(E element, int index);
public void removeElementAt(int index);
public void setElementAt(E element, int index);
public void removeDuplicates();
public void trimToSize();
public Iterator<E> iterator();
public Iterator<E> iterator(int index);
public String toString();
}
Since you implement an interface, you must implement all of the methods it declares (unless your class is abstract). Have a look at the Java tutorial trail on inheritance.
An interface is a contract that states that certain functionality will be provided by any class that implements it. That's done by specifying each of the method signatures (but, generally, no method bodies - so there's no actual implementation logic). So, if you have a class that implements that interface, you have to provide implementations for each of the methods so that your class fulfills that contract.
You implement the interface List so you need to implement all method which are defined in this interface. The exception says you should add the method iterator() to ArrayList.
An interface is like a contract which you (your class) sign(s). You have to fulfill everything which is defined in the contract or in other words you need to implement every (abstract) method from the interface.
Edit: I cleaned up the code and now the only thing you have to do is to implement every method with a // TODO comment in it.
public class ArrayList<E> implements List<E> {
private Object[] elementData;
private int elementCount;
private int capacityIncrement;
private static final int INVALID_INDEX = -1;
private static final int DEFAULT_CAPACITY = 100;
public ArrayList() {
capacityIncrement = 0;
elementData = new Object[DEFAULT_CAPACITY];
}
public ArrayList(int capacity) {
this.capacityIncrement = 0;
this.elementData = new Object[capacity];
}
public ArrayList(int capacity, int increment) {
this.capacityIncrement = increment;
this.elementData = new Object[capacity];
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
#Override
public boolean contains(E element) {
// TODO Auto-generated method stub
return false;
}
#Override
public void add(E element) {
// TODO Auto-generated method stub
}
#Override
public boolean remove(E element) {
// TODO Auto-generated method stub
return false;
}
#Override
public E elementAt(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public int indexOf(E element) {
// TODO Auto-generated method stub
return 0;
}
#Override
public void insertElementAt(E element, int index) {
// TODO Auto-generated method stub
}
#Override
public void removeElementAt(int index) {
// TODO Auto-generated method stub
}
#Override
public void setElementAt(E element, int index) {
// TODO Auto-generated method stub
}
#Override
public void removeDuplicates() {
// TODO Auto-generated method stub
}
#Override
public void trimToSize() {
// TODO Auto-generated method stub
}
#Override
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public Iterator<E> iterator(int index) {
// TODO Auto-generated method stub
return null;
}
protected class ArrayListIterator<T> implements Iterator<T> {
private ArrayList<T> list;
private ArrayListIterator(ArrayList<T> list) {
this.list = list;
}
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
#Override
public T next() {
// TODO Auto-generated method stub
return null;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
}
}
interface List<T> {
public int size();
public boolean isEmpty();
public void clear();
public boolean contains(T element);
public void add(T element);
public boolean remove(T element);
public T elementAt(int index);
public int indexOf(T element);
public void insertElementAt(T element, int index);
public void removeElementAt(int index);
public void setElementAt(T element, int index);
public void removeDuplicates();
public void trimToSize();
public Iterator<T> iterator();
public Iterator<T> iterator(int index);
public String toString();
}
Since you are saying that your class "implements List", it must implement all methods defined in the List interface. An interface is like an abstract specification for your class, specifying what your class can do (its methods) without giving an details about what your class contains/how it does its work

Categories

Resources