如何从Fragment访问在Activity中创建的SQLite数据库?

时间:2015-05-15 10:16:30

标签: android sqlite android-fragments

我在FormActivity.java中创建了一个本地SQLite数据库,如下所示:

db = new SQLiteHandler(getApplicationContext());

String name = user.getString("name");
String surname = user.getString("surname");
String title= user.getString("title");

db.addUser(name, surname, title);

然后我有一个包含几个textFields的片段。我希望用我在活动中创建的数据库填充这些字段。如下:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_first, container, false);

        //set inputs for fields
        inputTitle = (EditText) v.findViewById(R.id.titleText);
        inputName = (EditText) v.findViewById(R.id.foreText);
        inputSurname = (EditText) v.findViewById(R.id.surnameText);

        TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
        tv.setText(getArguments().getString("msg"));

        return v;

        // Fetching user details from sqlite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        String surname = user.get("surname");

        // Displaying the user details on the screen
        inputName.setText(name);
        inputSurname.setText(surname);
        inputTitle.setText(title);
    }

我目前的问题是db.getUserDetails(),我不知道也无法找到如何从片段中访问db。 我确定这是一个简单的修复,但有人可以把我放在这里吗? 感谢。

2 个答案:

答案 0 :(得分:3)

只需在Object

中创建SQLiteHandler Fragment
db = new SQLiteHandler(getActivity());

答案 1 :(得分:2)

调用此方法

 HashMap<String, String> user = db.getUserDetails();

返回您的视图并在SQLiteHandler

中创建Fragment
 db = new SQLiteHandler(getActivity());

最终代码将是。

    // Fetching user details from sqlite
 HashMap<String, String> user = db.getUserDetails();

 String name = user.get("name");
 String surname = user.get("surname");

    // Displaying the user details on the screen
 inputName.setText(name);
 inputSurname.setText(surname);
 inputTitle.setText(title);

 return v;