Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

android - Questions regarding CRUD operations

I am new to Android Studio and I am training to do a CRUD. When I try to insert a plant in the database, the message "Plant inserted" does not appear. Do you have an idea of ??the problem ? However, I display the message with the following code: Toast.makeText(AddActivity.this, "Plant inserted", Toast.LENGTH_SHORT).show();

Class PlantDataSource :

public class PlantDataSource extends SQLiteOpenHelper {

    private SQLiteDatabase db;
    private DatabasePlant dbPlant;

    public PlantDataSource(Context context) {
        super(context, "dbPlant", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String strReq = "CREATE TABLE tab_plant (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)";
        db.execSQL(strReq);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS tab_plant");
        onCreate(db);
    }


    public boolean insertPlant (Plant plant) {
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", plant.getNom());
        long result = db.insert("tab_plant", null, values);
        boolean insert = result == -1 ? false : true;
        return insert;
    }

    public Cursor getAllPlants() {
        db = this.getWritableDatabase();
        Cursor res = db.rawQuery("SELECT * FROM tab_plant", null);
        return res;
    }

}

Class ViewActivity :

public class ViewActivity extends AppCompatActivity {

    private PlantDataSource plantBdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view);
        plantBdd = new PlantDataSource(this);
        viewAll();
    }

    public void viewAll() {
        Cursor res = plantBdd.getAllPlants();
        if (res.getCount() == 0) {
            showMessage("Error", "No plants to display");

        }
        StringBuffer buffer = new StringBuffer();
        while (res.moveToNext()) {
            buffer.append("ID " + res.getString(0) + "
");
            buffer.append("NAME " + res.getString(1) + "
");
        }
        showMessage("Data", buffer.toString());
    }

    public void showMessage(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.show();
    }
}

Class AddActivity :

public class AddActivity extends AppCompatActivity {
    private EditText mPlantname;
    private Button mAddBtn;
    private  PlantDataSource plantBdd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        mPlantname = (EditText) findViewById(R.id.activity_add_plantname);
        mAddBtn = (Button) findViewById(R.id.activity_add_addBtn);
        plantBdd = new PlantDataSource(this);
        addPlant();
    }

    public void addPlant() {
        mAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Plant plant = new Plant(mPlantname.getText().toString());
                    boolean isInserted = plantBdd.insertPlant(plant);
                    Log.i("***", String.valueOf(isInserted));
                    Log.i("xxx", String.valueOf(plant));

                    if (isInserted) {
                        Toast.makeText(AddActivity.this, "Plant inserted", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

Here is the display when I run:

01/04 10:35:01: Launching 'app' on No Devices.
Install successfully finished in 797 ms.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.view.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 6163 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
    Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xe8dfff60, tid 6212
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xe8dff9b0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xe8dff9b0: ver 3 0 (tinfo 0xe913aa10) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xe8dff390, tid 6212
D/goldfish-address-space: allocate: Ask for block of size 0x100
    allocate: ioctl allocate returned offset 0x3fc684000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0 
I/Choreographer: Skipped 31 frames!  The application may be doing too much work on its main thread.
I/AssistStructure: Flattened final assist data: 1392 bytes, containing 1 windows, 8 views
I/***: true
I/xxxxxxxxxxxxxxxxx: Plant{name='clementinier'}
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10154; state: ENABLED
I/***: true
I/xxxxxxxxxxxxxxxxx: Plant{name='cactus'} 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...