如何在Activity类中实现Singleton类

时间:2013-12-17 07:34:10

标签: java android singleton

我希望在整个应用程序中提供单一培训。让我们从主要活动列表视图中说出每个单一的培训。但我没有从Singleton类中获取值。我的代码中有什么问题。我从昨天开始一直在努力,想不通为什么?感谢您的帮助。

这是Singleton类:

public class CurrentTraining {

private Training training; //Training is my model class.

private static CurrentTraining instance;

private CurrentTraining() {

}

public static CurrentTraining getInstance() {
    if (instance == null)
        instance = new CurrentTraining();
    return instance;

}

public Training getTraining() {
    return training;
}

public Training setTraining(Training training) {
    return this.training = training;
}

}

我的主要活动课程:

public class MainActivity extends ListActivity implements OnItemClickListener {

private Portfolio portfolio;

private ListAdapter trainingListAdapter;

private Dialog dialog;

Training currentTraining;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    currentTraining = CurrentTraining.getInstance().getTraining();

    portfolio = new Portfolio(this);

    trainingListAdapter = new ArrayAdapter<Training>(this,
            android.R.layout.simple_list_item_1,
            portfolio.getTrainingArrayList());

    setListAdapter(trainingListAdapter);

    ((ListView) findViewById(android.R.id.list))
            .setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

    Log.i ("DEBUG" , currentTraining.getTitle());
    CurrentTraining.getInstance().setTraining(currentTraining);

    Toast.makeText(getApplicationContext(), "You clicked on position : " + arg2 + " and ID : " + currentTraining.getId(), Toast.LENGTH_LONG).show();
    }

OnClick到listView,因为NullPointer异常而崩溃。

3 个答案:

答案 0 :(得分:0)

在你的onCreate中你这样做:

currentTraining = CurrentTraining.getInstance().getTraining();

我认为,由于您尚未设置它,因此返回null。当您输入onItemClick()时,使用

进行登录
currentTraining.getTitle()

可能会给出NullPointerException。尝试使用

进行日志记录
Log.i ("DEBUG" , currentTraining);

首先要确保它不是空的。

答案 1 :(得分:0)

你在这条线上获得NPE

Log.i(“DEBUG”,currentTraining.getTitle());

因为currentTraining为空。单例静态方法getInstace()初始化instance字段,但不填充getTraining()

返回的字段

答案 2 :(得分:0)

Log.i ("DEBUG" , currentTraining.getTitle());
    CurrentTraining.getInstance().setTraining(currentTraining);

没有设定价值,如何获得价值?

 @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        currentTraining = (Training)arg0.getAdapter().getItem(arg2);
        Log.i ("DEBUG" , currentTraining.getTitle());

        CurrentTraining.getInstance().setTraining(currentTraining);

        Toast.makeText(getApplicationContext(), "You clicked on position : " + arg2 + " and ID : " + currentTraining.getId(), Toast.LENGTH_LONG).show();
        }