继较早的线程之后,我想知道创建链表并让它们在多个活动中保持不变。有人建议我扩展应用程序类来做到这一点,所以我决定研究一下。
我已经这样做了,假设我没有把它弄得一团糟,应用程序现在应该用一些我希望在主要活动中使用的示例数据填充一个链表。但我似乎无法访问数据,我有点难过。
刚刚开始使用 android 开发,如果这是一个荒谬的问题,我很抱歉。无论如何,这是我到目前为止所拥有的。
扩展类GlobalData
package com.example.employeeList;
import java.util.LinkedList;
import android.app.Application;
import android.widget.Toast;
import com.example.employeeList.Employee;
public class GlobalData extends Application {
public LinkedList<Employee> EmployeeList;
@Override
public void onCreate(){
super.onCreate();
createEmployeeLinkedList();
}
public void createEmployeeLinkedList(){
// create a linked list
Employee emp1 = new Employee("John");
Employee emp2 = new Employee("Bob");
Employee emp3 = new Employee("Fred");
LinkedList<Employee> EmployeeList = new LinkedList<Employee>();
EmployeeList.add(emp1);
EmployeeList.add(emp2);
EmployeeList.add(emp3);
// The following code works, used for testing to see if linklist was actually being created.
// Employee boo = newEmployee();
// Employee boo = EmployeeList.getFirst();
// Toast.makeText(getApplicationContext(), "("+boo.name+")" ,Toast.LENGTH_LONG).show();
}
}
员工类
package com.example.employeeList;
import android.app.Application;
public class Employee extends Application{
public String name;
public Employee(String name) {
this.name = name;
}
}
MainActivity类
package com.example.employeeList;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
import android.widget.Toast;
import com.example.employeeList.Employee;
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();
//Would have thought I could just do this but apparently not.
Employee boo = globalData.EmployeeList.getFirst();
Toast.makeText(getApplicationContext(), "("+boo.name+")" ,Toast.LENGTH_LONG).show();
}
}
违规行似乎是
Employee boo = globalData.EmployeeList.getFirst();
Toast.makeText(getApplicationContext(), "("+boo.name+")" ,Toast.LENGTH_LONG).show();
有任何想法吗?