0

我在 android 中制作了一个简单的应用程序用于数据库练习,因为我不知道Sqlite database我已经为它浏览了这么多链接,但其中大多数都很复杂,我创建了 4 个活动第一个(mainActivity)包含 3 个Buttons“添加”第二个活动(AddActivity)中的“编辑”和“查看”我已经将 3 个EditTexts输入的值存储在数据库中。那么你能告诉我做同样事情的简单步骤吗?

MainActivity.java

package com.example.db;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button add=(Button)findViewById(R.id.button1);
        Button edit=(Button)findViewById(R.id.button2);
        Button view=(Button)findViewById(R.id.button3);

        add.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub]
            Intent i=new Intent(MainActivity.this,AddActivity.class);
            startActivity(i);

        }
    });
    edit.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i=new Intent(MainActivity.this,EditActivity.class);
            startActivity(i);

        }
    });

    view.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i=new Intent(MainActivity.this,ViewActivity.class);
            startActivity(i);
        }
    });
    }

    }

AddActivity.java

 package com.example.db;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class AddActivity extends Activity {
EditText name,addres,phon;
Button ad,cn;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);

        name = (EditText)findViewById(R.id.name);
        addres=(EditText)findViewById(R.id.address);
        phon = (EditText)findViewById(R.id.phone);

        ad =(Button)findViewById(R.id.add);
        cn=(Button)findViewById(R.id.cancel);
        final SQLiteDatabase db = openOrCreateDatabase("Mydb",MODE_PRIVATE, null);
        db.execSQL("create table if not exists simple(name varchar,address varchar,phone varchar");
        ad.setOnClickListener(new OnClickListener() {
            String n=name.getText().toString();
            String a=addres.getText().toString();
            String p= phon.getText().toString();
            @Override
            public void onClick(View v) {

                db.execSQL("insert into simple values('n','a','p')");
                Cursor c =db.rawQuery("select * from simple",null);
                c.moveToFirst();

            }
        });

        cn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i =new Intent(AddActivity.this,MainActivity.class);
                startActivity(i);
            }
        });
    }
}

主要的.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="92dp"
        android:text="Add" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="28dp"
        android:text="Edit" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="37dp"
        android:text="View" />

</RelativeLayout>

添加.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AddActivity" >

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="60dp"
        android:text="phone"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView3"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="14dp"
        android:text="Name"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView1"
        android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentRight="true"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="80dp"
        android:layout_toLeftOf="@+id/editText2"
        android:text="Address"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView2"
        android:ems="10"
        android:inputType="textPostalAddress" />

    <EditText
        android:id="@+id/phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignParentRight="true"
        android:ems="10"
        android:inputType="phone" />

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/phone"
        android:layout_marginTop="62dp"
        android:layout_toRightOf="@+id/textView1"
        android:text="Add" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/add"
        android:layout_marginLeft="36dp"
        android:layout_toRightOf="@+id/add"
        android:text="Cancel" />

</RelativeLayout>
4

2 回答 2

0

好的,我想您想将编辑文本的值添加到您的数据库中

 package com.example.databasesample;
 import java.util.ArrayList;
 import android.app.Activity;
 import android.content.ContentValues;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Bundle;
 import android.view.Menu;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.AdapterView;
 import android.widget.AdapterView.OnItemClickListener;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener {
static EditText edtAdd;
Button btnAdd, btnShow;
ListView listName;
static DataBaseSqlLiteHelper mBaseSqlLiteHelper;
DBModel mDbModel;
ArrayList<DBModel> mArrayList;
ListAdapter mAdapter;

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

    mArrayList = new ArrayList<DBModel>();
    mBaseSqlLiteHelper = new DataBaseSqlLiteHelper(MainActivity.this);
    mBaseSqlLiteHelper.getReadableDatabase();
    mBaseSqlLiteHelper.getWritableDatabase();

}

public void initialize() {
    edtAdd = (EditText) findViewById(R.id.edtEnterName);
    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnAdd.setOnClickListener(this);
    btnShow = (Button) findViewById(R.id.btnShow);
    btnShow.setOnClickListener(this);
    listName = (ListView) findViewById(R.id.listName);
    listName.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            deleteItem(mArrayList.get(arg2).getId());

        }
    });
}

@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 void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.btnAdd:
        addName(edtAdd.getText().toString());
        break;
    case R.id.btnShow:
        showNames();
        break;
    default:
        break;
    }

}
    // for adding values
public void addName(String name) {
    SQLiteDatabase mOpenHelper = mBaseSqlLiteHelper.getWritableDatabase();
    ContentValues mContentValues = new ContentValues();
    mContentValues.put("name", name);
    mOpenHelper.insert("NAMES", null, mContentValues);
    mOpenHelper.close();
}
    //showing values in list
public void showNames() {
    String selectQuery = "SELECT * FROM NAMES";
    SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
    Cursor mCursor = mDatabase.rawQuery(selectQuery, null);
    if (mCursor.moveToFirst()) {
        do {
            mDbModel = new DBModel();
            mDbModel.setId(mCursor.getString(0));
            mDbModel.setName(mCursor.getString(1));
            mArrayList.add(mDbModel);

        } while (mCursor.moveToNext());
    }
    mAdapter = new ListAdapter(MainActivity.this, mArrayList);
    listName.setAdapter(mAdapter);
}
     deleteing values
public void deleteItem(String id) {
    SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();

    String delete = "Delete from NAMES Where _id =" + id;

    mDatabase.execSQL(delete);
    mDatabase.close();
    mAdapter.notifyDataSetChanged();
    mArrayList.remove(id);

}
    //updating item
public static void updateItem(String id) {
    SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();

    String update = "Update NAMES set name=\""
            + edtAdd.getText().toString() + "\" where _id=" + id;
    mDatabase.execSQL(update);
    mDatabase.close();
}

}

 package com.example.databasesample;
 public class DatabaseConstants {

public static final String CREATE_TABLE_PROFILE_QUERY = "CREATE TABLE NAMES("
        + " _id integer primary key autoincrement," + " name VARCHAR"

        + ")";

}

  package com.example.databasesample;
  import android.content.Context;
  android.database.sqlite.SQLiteDatabase;
  import android.database.sqlite.SQLiteOpenHelper;
  public class DataBaseSqlLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "My Sample DataBase";
private static final int DATABASE_VERSION = 1;

public DataBaseSqlLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) 
{
    db.execSQL(DatabaseConstants.CREATE_TABLE_PROFILE_QUERY);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

  package com.example.databasesample;
  public class DBModel {
String id;
String name;
public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

}

  package com.example.databasesample;
  import java.util.ArrayList;
  import android.content.Context;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.view.ViewGroup;
  import android.widget.BaseAdapter;
  import android.widget.Button;
  import android.widget.TextView;

公共类 ListAdapter 扩展 BaseAdapter {

Context mContext;
ArrayList<DBModel> mArrayList;

public ListAdapter(Context mContext, ArrayList<DBModel> models) {
    // TODO Auto-generated constructor stub
    this.mArrayList = models;
    this.mContext = mContext;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return mArrayList.size();
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return arg0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    if (convertView == null) {
        LayoutInflater mLayoutInflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = mLayoutInflater.inflate(R.layout.list_layout, parent,
                false);
        TextView txtId = (TextView) convertView.findViewById(R.id.txtId);
        txtId.setText(mArrayList.get(position).getId());
        TextView txtName = (TextView) convertView
                .findViewById(R.id.txtName);
        txtName.setText(mArrayList.get(position).getName());
        Button btnUpdate=(Button)convertView.findViewById(R.id.btnUpdate);
        btnUpdate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                MainActivity.updateItem(mArrayList.get(position).getId());
            }
        });

    }
    return convertView;
}

}

//activity_main.xml

   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
    android:id="@+id/edtEnterName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Enter Name" />

<Button
    android:id="@+id/btnAdd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/edtEnterName"
    android:text="Add to Database" />

<Button
    android:id="@+id/btnShow"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/btnAdd"
    android:text="Show" />

<ListView
    android:id="@+id/listName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/btnShow" >
</ListView>

//listlayout.xml
  <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/txtId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/txtName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dp"
    android:layout_toRightOf="@+id/txtId" />

<Button
    android:id="@+id/btnUpdate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtName"
    android:text="Update" />

在这里,我制作了一个应用程序,您可以在其中添加、编辑和更新您的数据库。我使用两个主要类第一个 DataBaseSqlLiteHelper.java 来创建数据库和 DatabaseConstants.java 来创建表。要从数据库中删除项目,请单击列表并进行更新,如果您需要进一步的帮助,请先在编辑 text.comment 中输入值。

于 2013-05-08T13:31:53.803 回答
0

好的,如果您只想在数据库上显示一个值,那么您可以像这样使用 textView

TextView txtName;

在我上面的 initialize() 方法中初始化它;然后制作一个方法来获取单个值

   // Getting single Name to textView
public void getContact(String id) {
    SQLiteDatabase db = mBaseSqlLiteHelper.getReadableDatabase();
    String select="Select name from NAMES Where _id ="+id;
    Cursor mCursor=db.rawQuery(select,null);
    if (mCursor!=null) {
        mCursor.moveToFirst();
        String name=mCursor.getString(0);
        txtName.setText(name);
    }
    db.close();
}

然后在单击某个按钮时调用此方法并传递您要选择的行的 ID。

于 2013-05-09T04:42:28.763 回答