如何在片段中更新SQLite数据库? Android的

时间:2014-12-29 22:18:55

标签: android sqlite android-fragments

我在listview中以片段形式显示我的数据库。我还在对话框中添加了一个新数据。 当我在对话框中添加一些数据时,我有一些关于更新数据库的问题,当我返回到我在listview中显示我的数据库的片段时,没有我最近添加的数据。当我关闭并重新打开我的应用程序时,数据会显示在列表视图中。

我想你了解我的问题。

这是我的代码。

这是我的MainActivity,它有一个按钮和一个片段。

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ImageButton addBirthdate;

private DB database = new DB(this);

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

    // Initilization
    viewPager = (ViewPager) findViewById(R.id.pager);
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(mAdapter);

    addBirthdate = (ImageButton)findViewById(R.id.buttonAddBirthday);
    addBirthdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AddBirthdayDialog dialog = new AddBirthdayDialog(MainActivity.this);
            dialog.show();
        }
    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

}


}

这是我在listview中显示数据库的片段。

public class JanuaryFragment extends Fragment {

private DB myDB;
private List<Person> people;
private ListView listView;
private Context mContext;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.january_fragment, container, false);

    mContext = getActivity();

    myDB = new DB(mContext);
    people = getThisMonthsPeople( myDB.getAllPeople());

    listView = (ListView)rootView.findViewById(R.id.listViewOfBirthdays);
    listView.setAdapter(new PersonAdapter(mContext, people));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            EditBirthdayDialog dialog = new EditBirthdayDialog(mContext, people.get(position));
            dialog.show();
        }
    });

    return rootView;
}

public List<Person> getThisMonthsPeople(List<Person> allPeople){
    List<Person> resultPeople = new LinkedList<Person>();
    for(int i = 0; i< allPeople.size(); i++){
        if(allPeople.get(i).getMonth()==1){
            resultPeople.add(allPeople.get(i));
        }
    }
    return resultPeople;
}
}

这是我添加新数据的对话框。

public class AddBirthdayDialog extends Dialog {

private Context context;
String name;
String sname;
private int day;
private int month;
private int year;

final EditText textName;
final EditText textSname;
final DatePicker birthDate;

private DB myDB;
private SQLiteDatabase database;
private Person person = new Person();

public AddBirthdayDialog(Context context) {
    super(context);
    this.context = context;

    setCanceledOnTouchOutside(false);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.addbirthday_layout);


    myDB = new DB(context);


    textName = (EditText) findViewById(R.id.editTextname);
    textSname = (EditText) findViewById(R.id.editTextsname);
    birthDate = (DatePicker) findViewById(R.id.datePicker);



    Button cancelButton = (Button) findViewById(R.id.cancelbutton);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            clearForm();
            dismiss();

        }
    });

    Button save = (Button) findViewById(R.id.buttonadd);
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            name = textName.getText().toString();
            sname = textSname.getText().toString();

            day = birthDate.getDayOfMonth();
            month = birthDate.getMonth()+1;
            year = birthDate.getYear();
            final String dayStr = String.valueOf(day);
            final String monthStr = String.valueOf(month+1);
            final String yearStr = String.valueOf(year);

            person.setName(name);
            person.setSname(sname);
            person.setDay(day);
            person.setMonth(month);
            person.setYear(year);
            person.setDateStr(dayStr + "/" + monthStr + "/" + yearStr);

            myDB.addBirthday(person);
            clearForm();
            dismiss();
        }
    });
}

public void setDatePicker(int day, int month, int year){
    birthDate.updateDate(day,month,year);
}

//Cleans the form
public void clearForm(){
    textName.setText("");
    textSname.setText("");
    textSname.setText("");
}
}

这是我的对话框,我可以在列表视图中编辑我的数据。

public class EditBirthdayDialog extends Dialog {

private Context context;
String name;
String sname;
private int day;
private int month;
private int year;

final EditText textName;
final EditText textSname;
final DatePicker birthDate;

private DB myDB;
private SQLiteDatabase database;
private Person person;

public EditBirthdayDialog(Context context, final Person person) {
    super(context);
    this.context = context;
    this.person = person;

    setCanceledOnTouchOutside(false);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.editbirthday_layout);


    myDB = new DB(context);


    textName = (EditText) findViewById(R.id.editTextname);
    textName.setText(person.getName());
    textSname = (EditText) findViewById(R.id.editTextsname);
    textSname.setText(person.getSname());
    birthDate = (DatePicker) findViewById(R.id.datePicker);
    birthDate.updateDate(person.getYear(),person.getMonth()-1,person.getDay());

    Button cancelButton = (Button) findViewById(R.id.cancelbutton);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            clearForm();
            dismiss();

        }
    });

    Button save = (Button) findViewById(R.id.buttonadd);
    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name = textName.getText().toString();
            sname = textSname.getText().toString();

            day = birthDate.getDayOfMonth();
            month = birthDate.getMonth()+1;
            year = birthDate.getYear();
            final String dayStr = String.valueOf(day);
            final String monthStr = String.valueOf(month);
            final String yearStr = String.valueOf(year);

            person.setName(name);
            person.setSname(sname);
            person.setDay(day);
            person.setMonth(month);
            person.setYear(year);
            person.setDateStr(dayStr + "/" + monthStr + "/" + yearStr);

            myDB.updateBirthday(person);
            clearForm();
            dismiss();
        }
    });

    Button buttonDelete = (Button) findViewById(R.id.buttondelete);
    buttonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myDB.deleteBirthday(person);
            clearForm();
            dismiss();
        }
    });
}

public void setDatePicker(int day, int month, int year){
    birthDate.updateDate(day,month,year);
}

//Cleans the form
public void clearForm(){
    textName.setText("");
    textSname.setText("");
}
}

编辑。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

关闭对话框时重新加载数据。您只是在数据库中添加数据,而不是刷新列表视图。

在片段中添加此方法

public void reload()
{
    myDB = new DB(mContext);
    people = getThisMonthsPeople( myDB.getAllPeople());
    myAdapter = new PersonAdapter(mContext, people)
    listView.setAdapter(myAdapter);
    if(myAdapter != null)
        myAdapter.notifyDataSetChanged();
}

onCreateView()

中删除这三行
myDB = new DB(mContext);
people = getThisMonthsPeople( myDB.getAllPeople());
listView.setAdapter(new PersonAdapter(mContext, people));

在您的活动中

@Override
public void onResume()
{
    super.onResume();
    JanuaryFragment fragment = (JanuaryFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.layout); // Replace "layout" with your layout where you are loading the fragment
    if (fragment != null) {
        fragment.reload();
    }
}

修改

在调用AddBirthdayDialog

之前,在dismiss()点击保存按钮时添加此项
if(context instanceOf MainActivity)
    ((MainActivity)context).onResume();

注意:

我建议您使用Interface来实现这些行为。如果您想要使用Interfaces获得更好的解决方案,请参阅我的答案。 Communicating my Dialog with Main Activity