I want to add an element to the Today child element from another action in an ExpandableListView . The activity I want to add is called LocHistory , here is the code to add to the list:
static void addListData(final Context context) { List<NewsItem> list = listDataChild.get("Today"); NewsItem newsData = new NewsItem(); newsData = new NewsItem(); newsData.setHeadline("11.11111, 1.1111"); newsData.setSpeed("1.11KM/H"); newsData.setDirection("111"); newsData.setDate("11-1-1111 11:11:11"); list.add(0, newsData); listDataChild.put("Today", list); }
This works when I call a function in the same class ( LocHistory ). But when I call it in MainActivity as follows:
public class MainActivity extends Activity { Button button2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button2 = (Button) this.findViewById(R.id.button2); button2.setOnClickListener(new OnClickListener() { public void onClick(View v) { LocHistory.addListData(getBaseContext()); } }); } }
Then nothing is added to the list. Is it possible to add an item from another activity in an ExpandableListView ? I want if something is added that the LocHistory class LocHistory not open, so I think that startActivity with intent is not an option (but I'm not sure).
(Sources of java can be found here: MainActivity.java , LocHistory.java , NewsItem.java and ExpandableListAdapter.java )
Edit:
As some guys noted in another forum, now I am using SharedPreferences . I am using this code:
static void addListData (int TimeStamp, final String lat, final String lng, final String speed, final String direction, final Context context){ int todaystamp = startOf("today"); int yesterdaystamp = startOf("yesterday"); String Datetime = DateFormat.format("dd-MM-yyyy kk:mm:ss", new Date(TimeStamp * 1000L)).toString(); SharedPreferences pref = context.getSharedPreferences("myPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); if (TimeStamp >= todaystamp) { editor.putString("Today", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";"); } else if (TimeStamp >= yesterdaystamp) { editor.putString("Yesterday", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";"); } else if (TimeStamp < yesterdaystamp) { editor.putString("Older", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";"); } editor.commit(); }
But now I'm stuck in one problem, when I add an item to SharedPreferences on the same key, it will overwrite the previous data. How to add data to the same key without overwriting previous data? Is it possible, perhaps, to get the data first, and then join the element to the data, and then add the data to SharedPreferences ?