如何将数据从片段发送到活动?

时间:2016-03-20 07:34:29

标签: android android-fragments

我希望将片段中的数据发送到活动,但我现在的代码不起作用。

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    Intent intent = new Intent();
    Context ctx = getActivity();
    DBoperations db = new DBoperations(ctx);
    Cursor cr = db.getInfo(db);
    cr.moveToFirst();
    long count = id;
    while( count > 0){
        cr.moveToNext();
        count --;
    }
    String ID = Integer.toString(cr.getInt(0));
    String Name = cr.getString(1);
    intent.putExtra("extra",ID + " " + Name);
    startActivity(getActivity(),LocationInfo.class);
}

此函数位于扩展Fragment的类中。 这里整个最后一行startActivity(...)用红色下划线标出:

  片段中的

startActivity(android.content.intent,android.os.Bundle)   无法应用   (android.support.v4.app.FragmentActivity,java.lang.Class中)

那么如何将数据从片段传递给活动?

2 个答案:

答案 0 :(得分:1)

我没有写

startActivity(new Intent(getActivity(),LocationInfo.class));

这是唯一的问题......

答案 1 :(得分:0)

试试这个:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    Intent intent = new Intent(getActivity(), LocationInfo.class);
    Context ctx = getActivity();
    DBoperations db = new DBoperations(ctx);
    Cursor cr = db.getInfo(db);
    cr.moveToFirst();
    long count = id;
    while( count > 0){
        cr.moveToNext();
        count --;
    }
    String ID = Integer.toString(cr.getInt(0));
    String Name = cr.getString(1);
    intent.putExtra("extra",ID + " " + Name);
    startActivity(intent);
}