Been struggling with this for a while now. Basically i have extended the application class so that it creates a simple linkedlist in the hope that this list would be accessible across various activities. But for can’t seem to get the information out of the linkedlist when i need it.
I’m not sure if this is even possible (although i don’t see why it wouldn’t) or if I am just making some stupid mistakes when dealing with the linkedlist.
Extending the appllication class (GlobalData)
package com.example.testing;
import java.util.LinkedList;
import android.app.Application;
import android.widget.Toast;
public class GlobalData extends Application {
public static LinkedList<String> EmployeeList;
@Override
public void onCreate(){
super.onCreate();
createLinkedList();
}
public void createLinkedList(){
// create a linked list
LinkedList<String> EmployeeList = new LinkedList<String>();
String emp1 ="john", emp2="adam";
EmployeeList.add(emp1);
EmployeeList.add(emp2);
String boo;
boo = EmployeeList.getFirst();
//This works, displays the name ok.
Toast.makeText(getApplicationContext(), "("+boo+")" ,Toast.LENGTH_LONG).show();
}
}
The main where i would like to be able to access the linkedlist.
package com.example.testing;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected GlobalData globalData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application instance
globalData = (GlobalData)getApplication();
String boo;
boo = GlobalData.EmployeeList.getFirst();
//This doesn't work & im not sure why.
Toast.makeText(getApplicationContext(), "("+boo+")" ,Toast.LENGTH_LONG).show();
}
}
Probably should mention that i’m just getting started with this stuff, so apologies if this is a completely idiotic question.
I can’t understand why I am not able to access the contents of that list, if i modify the script so that the GlobalData class contains a string variable the above code(with a few alterations) works fine. So why would the variable be accessible but the linked list not?
Thanks
In this line you are creating a new instance of the list instead of using the one you’ve created as a member of the class:
Simply change this line to :