以下是一个简单的布局代码示例,用于将新闻保存到SQLite数据库:

<!-- activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editTextTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="标题" />

    <EditText
        android:id="@+id/editTextContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="内容" />

    <Button
        android:id="@+id/buttonSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存" />

</LinearLayout>
// MainActivity.java
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText editTextTitle;
    private EditText editTextContent;
    private Button buttonSave;

    private NewsDbHelper dbHelper;

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

        dbHelper = new NewsDbHelper(this);

        editTextTitle = findViewById(R.id.editTextTitle);
        editTextContent = findViewById(R.id.editTextContent);
        buttonSave = findViewById(R.id.buttonSave);

        buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveNews();
            }
        });
    }

    private void saveNews() {
        String title = editTextTitle.getText().toString().trim();
        String content = editTextContent.getText().toString().trim();

        SQLiteDatabase db = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(NewsContract.NewsEntry.COLUMN_TITLE, title);
        values.put(NewsContract.NewsEntry.COLUMN_CONTENT, content);

        long newRowId = db.insert(NewsContract.NewsEntry.TABLE_NAME, null, values);

        if (newRowId == -1) {
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
        }
    }
}

以上代码示例中,布局文件包含一个标题输入框、一个内容输入框和一个保存按钮。当用户点击保存按钮时,会调用saveNews()方法将新闻标题和内容保存到SQLite数据库中。NewsDbHelper是一个自定义的数据库帮助类,用于创建和管理数据库。NewsContract是一个自定义的合同类,用于定义数据库表和列的常量。

android新闻系统开发把新闻保存到SQLite数据库的布局代码

原文地址: http://www.cveoy.top/t/topic/hCar 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录