0

好的,伙计们,在我之前,我搜索了论坛和许多其他人,但我似乎没有找到足够的答案,所以我想我可能会问,我创建了这个应用程序来组织一天,它的工作原理是这样的:-我有 2 个活动,一个是显示数据(在列表视图上),另一个只是用于插入,我用startActivityForResult函数打开了第二个活动,然后用onActivityResult功能我将它插入数据库。Eclipse 没有向我显示任何错误,LogCat 也没有,但数据似乎没有插入到 Db 中,所以我在插入数据时插入了一个 try-catch 方法来记录所做的事情,我总是得到数据的异常没有被记录。我是android新手,我认为我做的一切都不对。我发布了应用程序的所有代码,以便您对整个过程有一个概述,但问题(我认为)是创建数据库的地方,或者插入数据的地方,或者当我尝试获取数据从一个到另一个。但我不知道在哪里所以请帮忙!

MainActivity.java:

package com.example.dailyplanner;

import android.R.id;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {


    private SQLiteDatabase db;
    Intent weather;     
    Intent i;
    String text;
    String date;
    String time;
    ListView lv;

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



        db = openOrCreateDatabase("MyDB", MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS TaskTbl (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, text VARCHAR(250), time VARCHAR(20), date VARCHAR(20));");


        Button showBtn = (Button) findViewById(R.id.shTask);
        showBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {



            }
        });


        Button nTaskBtn = (Button) findViewById(R.id.nTask);
        nTaskBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent nTaskScreen = new Intent(getApplicationContext() new_task.class);

                startActivityForResult(nTaskScreen, 100);



            }
        });



        Button wthrBtn = (Button) findViewById(R.id.wthrBtn);
        registerForContextMenu(wthrBtn);


        lv = (ListView) findViewById(id.list);



    }








    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);

        MenuInflater mi = getMenuInflater();
        mi.inflate(R.menu.cities, menu);


    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        return super.onContextItemSelected(item);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode==100)
        {
            i = getIntent();        
        String text = i.getStringExtra("text");
            String date = i.getStringExtra("date");
            String time = i.getStringExtra("time");
                try{


                db.execSQL("INSERT INTO TaskTbl (text,time,date) VALUES("+text+", "+time+", "+date+");");        

                Log.d("db","data was recorded");
            }
            catch (Exception e)
            {
                Log.e("db", "data was not recorded");

            }



        }

    }
}

新任务.java:

package com.example.dailyplanner;

import android.R.string;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.net.UrlQuerySanitizer.ValueSanitizer;
import android.os.Bundle;
import android.renderscript.Sampler.Value;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;

public class new_task extends Activity {

    static final int TIME_DIALOG_ID=0;
    static final int DATE_DIALOG_ID=1;
    public TextView timeText;
    public TextView dateText;
    public EditText taskText;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_task);


        timeText = (TextView) findViewById(R.id.timeTxt);
        dateText = (TextView) findViewById(R.id.dateTxt);
        taskText = (EditText) findViewById(R.id.editText1);

        Button btnSave = (Button) findViewById(R.id.btnSave);
        btnSave.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                Intent i = new Intent(getApplicationContext(),     MainActivity.class);

                i.putExtra("date", dateText.getText().toString());
                i.putExtra("time", timeText.getText().toString());
                i.putExtra("text", taskText.getText().toString());

                setResult(100);

                finish();




            }
        });



        Button btnCancel = (Button) findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                finish();


            }
        });


    Button btnSetTime = (Button) findViewById(R.id.btnSetTime);
        btnSetTime.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                showDialog(TIME_DIALOG_ID);

            }
            });

        Button btnSetDate = (Button) findViewById(R.id.btnSetDate);
        btnSetDate.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                showDialog(DATE_DIALOG_ID);

            }
        });



    }

    TimePickerDialog.OnTimeSetListener mTimeSetListener = new     TimePickerDialog.OnTimeSetListener() {

                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    timeText.setText(hourOfDay+":"+minute);
                    };

    };


    DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {

            dateText.setText(dayOfMonth+"."+monthOfYear+"."+year);

        }
    };


    protected Dialog onCreateDialog(int id){
        switch(id){

        case TIME_DIALOG_ID:
        return new TimePickerDialog(this, mTimeSetListener, 0, 0, true);

        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, 2011, 1, 28);


        }
        return null;

    }


}

这是 LogCat:

10-13 15:57:44.825: D/CLIPBOARD(9334): Hide Clipboard dialog at Starting input: finished by someone else... !
10-13 16:03:17.020: D/dalvikvm(10612): GC_FOR_ALLOC freed 135K, 4% free 12839K/13255K, paused 27ms
10-13 16:03:17.020: I/dalvikvm-heap(10612): Grow heap (frag case) to 13.069MB for 379472-byte allocation
10-13 16:03:17.075: D/dalvikvm(10612): GC_FOR_ALLOC freed <1K, 4% free 13209K/13639K, paused 55ms
10-13 16:03:17.115: D/AbsListView(10612): Get MotionRecognitionManager
10-13 16:03:17.305: D/CLIPBOARD(10612): Hide Clipboard dialog at Starting input: finished by someone else... !
10-13 16:03:21.740: D/dalvikvm(10612): GC_CONCURRENT freed 62K, 2% free 13626K/13895K, paused 3ms+2ms
10-13 16:03:21.790: D/dalvikvm(10612): GC_CONCURRENT freed 6K, 2% free 14073K/14343K, paused 2ms+2ms
10-13 16:03:21.825: D/AbsListView(10612): Get MotionRecognitionManager
10-13 16:03:21.875: D/dalvikvm(10612): GC_FOR_ALLOC freed 80K, 2% free 14324K/14599K, paused 13ms
10-13 16:03:23.130: D/dalvikvm(10612): GC_CONCURRENT freed 175K, 3% free 14678K/15047K, paused 2ms+4ms
10-13 16:03:28.910: D/AndroidRuntime(10612): Shutting down VM
10-13 16:03:28.910: W/dalvikvm(10612): threadid=1: thread exiting with uncaught exception (group=0x40c6f1f8)
10-13 16:03:28.915: E/AndroidRuntime(10612): FATAL EXCEPTION: main
10-13 16:03:28.915: E/AndroidRuntime(10612): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=100, data=null} to activity {com.example.dailyplanner/com.example.dailyplanner.MainActivity}: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2994)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3037)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.app.ActivityThread.access$1100(ActivityThread.java:128)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1191)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.os.Looper.loop(Looper.java:137)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.app.ActivityThread.main(ActivityThread.java:4514)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at java.lang.reflect.Method.invokeNative(Native Method)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at java.lang.reflect.Method.invoke(Method.java:511)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at dalvik.system.NativeStart.main(Native Method)
10-13 16:03:28.915: E/AndroidRuntime(10612): Caused by: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:92)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:2020)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1960)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at com.example.dailyplanner.MainActivity.onActivityResult(MainActivity.java:182)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.app.Activity.dispatchActivityResult(Activity.java:4746)
10-13 16:03:28.915: E/AndroidRuntime(10612):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2990)
10-13 16:03:28.915: E/AndroidRuntime(10612):    ... 11 more
4

1 回答 1

0

在询问异常时,您应该始终从 logcat 发布堆栈跟踪。

但是,我可以看到您的插入失败的原因。文本数据和日期应该用单引号分隔。

INSERT INTO foo VALUES (myTextData)

将失败

INSERT INTO foo VALUES ('myTextData')

将工作。

使用“'”+文字+“'”

db.execSQL("INSERT INTO TaskTbl (text,time,date) VALUES(" + "'" + text + "', '" + time + "', '" + date + "');"); 

在构建这样的字符串时,使用 IDE 编辑器中的语法颜色突出显示来检查引号是否在正确的位置。例如,在我的 IDE 中,字符串显示为绿色,标识符显示为黑色。

[编辑]

约束异常意味着您正在尝试添加重复的行。如果不允许重复,那么您应该相应地处理此异常。如果允许重复,则使用 _id 列作为主要列。我想您可能已经尝试过这样做,但您的 create 语句添加了一个名为“id”的列,而不是“_id”。如果实际上您打算使用“id”,那么您必须在 INSERT 中为该列使用唯一值,因为您已指定它是主键。

于 2012-10-13T12:38:10.830 回答