从两个类添加到sqlite数据库

时间:2014-10-28 20:45:10

标签: java android sqlite android-intent

我从可以向我的数据库添加对象的人那里获得了这个活动AddFood。 当我从一个类打开活动时(该类后来在列表视图中显示数据库内容)一切正常。

但是当我从我的主课程中打开AddFood活动时,请填写该字段并单击添加,当我在显示列表视图的类中查找它时,它会显示。

这是我的AddFood类减去了导入。

package com.example.mappe3;

public class AddFood extends Activity implements OnClickListener{

private HousekeepingDBHelper hkDBhelper;

private EditText itemFood, itemWeight, itemPrice, itemBrand, itemCategory;
private String setFood, setWeight, setPrice, setBrand, setCategory;
private Spinner catagorySpinner;
private Button addButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_food);
    hkDBhelper = new HousekeepingDBHelper(this);

    itemFood = (EditText)findViewById(R.id.itemFood);
    itemWeight = (EditText)findViewById(R.id.itemWeight);
    itemPrice = (EditText)findViewById(R.id.itemPrice);
    itemBrand = (EditText)findViewById(R.id.itemBrand);
    itemCategory = (EditText)findViewById(R.id.itemCategory);

    catagorySpinner = (Spinner)findViewById(R.id.catagory_spinner);


    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.catagory_array, android.R.layout.simple_spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    catagorySpinner.setAdapter(adapter);

    addButton = (Button)findViewById(R.id.addButton);
    addButton.setOnClickListener(this);
}

public void addItem(){
    setFood = itemFood.getText().toString();
    setWeight = itemWeight.getText().toString();
    setPrice = itemPrice.getText().toString();
    setBrand = itemBrand.getText().toString();
    setCategory = catagorySpinner.getSelectedItem().toString();


    if(setFood.length() != 0 && setWeight.length() != 0 && setPrice.length() != 0
            && setBrand.length() != 0 && setCategory.length() != 0){
        Intent newIntent = getIntent();
        newIntent.putExtra("tag_grocery_foodItem", setFood);
        newIntent.putExtra("tag_grocery_weight", setWeight);
        newIntent.putExtra("tag_grocery_price", setPrice);
        newIntent.putExtra("tag_grocery_brand", setBrand);
        newIntent.putExtra("tag_grocery_category", setCategory);

        this.setResult(RESULT_OK, newIntent);
        finish();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.add_food, 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 onClick(View v) {
    if(v.getId() == R.id.addButton){
        addItem();
    }
}
}

继承了显示内容的类,以及我可以使用Addfood类的地方:

package com.example.mappe3;

public class DatabaseActivity extends Activity {

private HousekeepingDBHelper hkDBhelper;
private HousekeepingCursorAdapter hkCursorA;
private static final int ENTER_DATA_REQUEST_CODE = 1;

private ListView foodList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_database);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    hkDBhelper = new HousekeepingDBHelper(this);
    foodList = (ListView)findViewById(R.id.food_data);

    runner();
}

public void runner(){
    new Handler().post(new Runnable(){
        @Override
        public void run(){
            hkCursorA = new HousekeepingCursorAdapter(DatabaseActivity.this, hkDBhelper.listAll());
            foodList.setAdapter(hkCursorA);
        }
    });
}

@Override
protected void onActivityResult(int reqCode, int resCode, Intent data){
    super.onActivityResult(reqCode, resCode, data);

    if(reqCode == ENTER_DATA_REQUEST_CODE && resCode == RESULT_OK){
        hkDBhelper.addItem(data.getExtras().getString("tag_grocery_foodItem"),
                            data.getExtras().getString("tag_grocery_weight"),
                            data.getExtras().getString("tag_grocery_price"),
                            data.getExtras().getString("tag_grocery_brand"),
                            data.getExtras().getString("tag_grocery_category"));
        hkCursorA.changeCursor(hkDBhelper.listAll());
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.database, menu);
    return true;
}   

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    case R.id.addItem:
        startActivityForResult(new Intent(this, AddFood.class), ENTER_DATA_REQUEST_CODE);
        return true;            
    }
    return super.onOptionsItemSelected(item);
}
}

当我填写我的AddFood类中的字段时,它运行finish();并转到上一个活动(DatabaseActivity),我可以在列表中查看新对象。

这是我的MainActivity.java。这是我遇到麻烦的地方。

package com.example.mappe3;

public class MainActivity extends Activity implements OnClickListener{

private Button databaseB;
private static final int ENTER_DATA_REQUEST_CODE = 1;

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

    databaseB = (Button)findViewById(R.id.food_db_button);
    databaseB.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

//THIS IS WHAT I THOUGT WAS ENOUGH TO DO THE SAME THING IN THIS CLASS
    if (id == R.id.addItem) {
        startActivityForResult(new Intent(this, AddFood.class), ENTER_DATA_REQUEST_CODE);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    if(v.getId() == R.id.food_db_button){
        Intent startIntent = new Intent(this, DatabaseActivity.class);
        this.startActivityForResult(startIntent, 1);
    }

}
}

在我完成从MainActivity添加AddFood类后,它返回到MainActivity,这就是我想要的。但是,当我打开DatabaseActivity去寻找它时,它不在那里。我仍然可以看到从其他课程中添加的所有项目,但不是我刚刚添加的项目。

希望我的解释对任何人都有意义。

有人能看出我做错了吗?

编辑:MainActivity中的onActivityResult()

    @Override
protected void onActivityResult(int reqCode, int resCode, Intent data){
    super.onActivityResult(reqCode, resCode, data);

    if(reqCode == ENTER_DATA_REQUEST_CODE && resCode == RESULT_OK){
        hkDBhelper.addItem(data.getExtras().getString("tag_grocery_foodItem"),
                            data.getExtras().getString("tag_grocery_weight"),
                            data.getExtras().getString("tag_grocery_price"),
                            data.getExtras().getString("tag_grocery_brand"),
                            data.getExtras().getString("tag_grocery_category"));
        hkCursorA.changeCursor(hkDBhelper.listAll());
    }
}

错误日志:

10-29 11:13:29.538: E/AndroidRuntime(28521): FATAL EXCEPTION: main
10-29 11:13:29.538: E/AndroidRuntime(28521): Process: com.example.s188094_mappe3, PID: 28521
10-29 11:13:29.538: E/AndroidRuntime(28521): java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=1, result=-1, data=Intent { cmp=com.example.s188094_mappe3/.AddFood
(has extras) }} to activity {com.example.s188094_mappe3/com.example.s188094_mappe3.MainActivity}:
java.lang.NullPointerException
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.app.ActivityThread.deliverResults(ActivityThread.java:3928)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.app.ActivityThread.handleSendResult(ActivityThread.java:3978)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.app.ActivityThread.access$1300(ActivityThread.java:156)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.os.Handler.dispatchMessage(Handler.java:102)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at android.os.Looper.loop(Looper.java:157)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.app.ActivityThread.main(ActivityThread.java:5867)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at java.lang.reflect.Method.invokeNative(Native
Method)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at java.lang.reflect.Method.invoke(Method.java:515)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at dalvik.system.NativeStart.main(Native Method)
10-29 11:13:29.538: E/AndroidRuntime(28521): Caused by: java.lang.NullPointerException
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
com.example.s188094_mappe3.MainActivity.onActivityResult(MainActivity.java:40)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.app.Activity.dispatchActivityResult(Activity.java:5535)
10-29 11:13:29.538: E/AndroidRuntime(28521):    at
android.app.ActivityThread.deliverResults(ActivityThread.java:3924)
10-29 11:13:29.538: E/AndroidRuntime(28521):    ... 11 more

1 个答案:

答案 0 :(得分:0)

AddFood课程中,您创建了一个Intent并用数据填充,然后将此Intent传递回已启动AddFood的活动。如果从AddFood启动DatabaseActivity,则返回的Intent用于将项目添加到onActivityResult()中的数据库。

但是,如果从AddFood启动MainActivity,则返回的Intent不会执行任何操作,因为您在onActivityResult()中未实施MainActivity