如何将多个值添加到 sql 中的一列中?

How can i add multiple values into one column in sql?

我正在创建应用程序,您可以在其中注册一个人,然后将其添加到列表中,接下来您可以查看此列表,其中包含姓名、姓氏、时间、日期等所有信息。但我不知道该怎么做?首先,我正在解决一个 sqlite 异常问题,即我无法为一列设置 4 个值。其次,我不知道如何制作自定义列表视图,我可以在一列中将名称设置为项目,将姓氏设置为子项目。

有我的许可 class,我在其中处理所有编辑文本字段和按钮“确定”以将所有字符串添加到列表。

  package com.example.pass;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;




public class Permission extends ActionBarActivity{
 EditText Date;
 EditText Time;
 EditText userName;
 EditText userSurname;

 EditText Name;
 String Surname;

 //INITIALIZING THE VARIABLES...
 Button b1,b2;
 EditText e1;
 String text,u,text2,text3,text4;
 String un[]={"","","","","","","","","","","","","","",""};
 String pas;
 Cursor c;
 int i=0;
 String s,sqlquery;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_permission);

    Button add = (Button) findViewById(R.id.add);
    Button cancel = (Button) findViewById(R.id.cancel);


    // Create custom dialog object          
    // set values for custom dialog components - text, image and button
    userName = (EditText) findViewById(R.id.dialog_username);
    userSurname = (EditText)findViewById(R.id.dialog_usersurname);
    Time = (EditText)findViewById(R.id.dialog_time2);
    Date = (EditText)findViewById(R.id.dialog_date2);   


           Date.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //To show current date in the datepicker
                    Calendar mcurrentDate=Calendar.getInstance();
                    int mYear = mcurrentDate.get(Calendar.YEAR);
                    int mMonth = mcurrentDate.get(Calendar.MONTH);
                    int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog mDatePicker=new DatePickerDialog(Permission.this, new OnDateSetListener() {                  
                        public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
                            // TODO Auto-generated method stub                      
                            /*      Your code   to get date and time    */
                            Date.setText(selectedyear+"-"+(selectedmonth+1)+"-"+selectedday);
                        }
                    },mYear, mMonth, mDay);
                    mDatePicker.setTitle("Select date");                
                    mDatePicker.show();  }
            });


           Time.setOnClickListener(new OnClickListener() {
               @Override
               public void onClick(View v) {
                   // TODO Auto-generated method stub
                   //To show current date in the datepicker

                   Calendar mcurrentTime=Calendar.getInstance();
                   int mHour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                   int mMinute = mcurrentTime.get(Calendar.MINUTE);


                   TimePickerDialog mTimePicker=new TimePickerDialog(Permission.this, new OnTimeSetListener() {                  
                       public void onTimeSet(TimePicker timepicker, int selectedhour, int selectedminute ) {
                           // TODO Auto-generated method stub                      
                           /*      Your code   to get date and time    */
                          if (selectedminute<10){
                              Time.setText(selectedhour+":"+"0"+(selectedminute)+""+"val");
                          }
                          else
                        Time.setText(selectedhour+":"+(selectedminute));
                       }
                   },mHour, mMinute, false);
                   mTimePicker.setTitle("Select date");                
                   mTimePicker.show();  }
           });


          cancel.setOnClickListener(new OnClickListener() {
               @Override
               public void onClick(View v) {
                   // TODO Auto-generated method stub
                   //To show current date in the datepicker
                    startActivity(new Intent(Permission.this, Choose.class));
                  Permission.this.finish();
               }     
           });

          add.setOnClickListener(new OnClickListener() {
              @Override
              public void onClick(View arg0) {
                  // TODO Auto-generated method stub
                  text=userName.getText().toString();
                  text2=userSurname.getText().toString();
                  text3=Date.getText().toString();
                  text4=Time.getText().toString();
                  //CREATING A DATABASE OBJECT..HERE db is SQLITEDATABASE OBJECT AND
                  // todo is our database name AND
                  //WE ARE USING IT IN WRITE MODE
                  SQLiteDatabase db=openOrCreateDatabase("todo", Context.MODE_WORLD_WRITEABLE, null);

                  text="'"+text+"'";
                  text2="'"+text2+"'";
                  text3="'"+text3+"'";
                  text4="'"+text4+"'";

          //SQL QUERY TO CREATE TABLE
          s="CREATE TABLE if not exists TODOLIST"+" ("+ "list" +" VARCHAR(100)"+");";
                  db.execSQL(s);

                  // QUERY TO INSERT THE DATA INTO TABLE
                  sqlquery="INSERT INTO TODOLIST"+ " VALUES"+"("+text+","+text2+","+text3+","+text4+");";
                  db.execSQL(sqlquery);
                  userName.setText("");

                  Toast.makeText(getApplicationContext(), "TASK ADDED IN LIST", Toast.LENGTH_SHORT).show();
              }     
          });

        }


    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.permission, 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);
}









  }

这是我允许的 xml 文件。

  <?xml version="1.0" encoding="utf-8"?>
  <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/dialog_username"
    android:hint="Name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

  </EditText>
  <EditText
    android:id="@+id/dialog_usersurname"
    android:hint="Surname"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
  </EditText>
  <EditText
    android:id="@+id/dialog_date2"
    android:hint="Enter date"
    android:focusable="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
  </EditText>
  <EditText
    android:id="@+id/dialog_time2"
    android:hint="Enter time"
    android:focusable="false"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
 </EditText>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Cancel" />

</LinearLayout>


   </LinearLayout>

这是我的详细信息 class,它处理带有后退和清除按钮的列表视图,所以在这个地方我想自定义 R.layout.simple_expandable_list_item_1 但我不知道如何?正如我所说,Name 将是 Item,surname 是 subItem,并将它们显示在一列中。

   package com.example.pass;

 import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.AdapterView;
 import android.widget.AdapterView.OnItemLongClickListener;
 import android.widget.ArrayAdapter;
 import android.widget.Button;
 import android.widget.ListView;
 import android.widget.Toast;

 public class Detail extends Activity {

    Button b, clr;
    ListView lv;
    String query;
    Cursor c;
    String uns[] = { "", "", "", "", "", "", "","","",""};
    int i = 0;
    int t = 0;
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.detail);
            b = (Button) findViewById(R.id.btn);
            clr = (Button) findViewById(R.id.clear);
            lv = (ListView) findViewById(R.id.listView1);

            // Declaring arrayadapter to store the items and return them as a view
            final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_expandable_list_item_1, uns);

            db = openOrCreateDatabase("todo", Context.MODE_WORLD_READABLE, null);

            //READING THE DATA FROM THE TABLE TODOLIST AND SETTING IN AN      ARRAYADAPTER...HERE C IS A CURSOR...
            //WHICH POINTS TO A ROW..AND MOVE TO THE NEXT ROW....
            c = db.rawQuery("SELECT * FROM TODOLIST; ", null);
            i = 0;
            while (c.moveToNext()) {

                    uns[i] = c.getString(0);
                    i++;
            }
            t = i;

            lv.setAdapter(adapter);

            // clear all the data from table..
            clr.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub

                            db = openOrCreateDatabase("todo",     Context.MODE_WORLD_WRITEABLE,
                                            null);

                            //QUERY TO DELETE ALL THE DATA FROM TABLE
                            db.delete("TODOLIST", null, null);

                            db.close();

                            for (int j = 0; j < t; j++) {
                                    uns[j] = "";
                                    lv.setAdapter(adapter);
                            }

                    }
            });

            //GOING BACK TO MAIN ACTIVITY
            b.setOnClickListener(new OnClickListener() {

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


    }

 }

详细信息activityxml文件

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

 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back" />

    <Button
        android:id="@+id/clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear all" />

 </LinearLayout>

 <ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</ListView>

 </LinearLayout>

我的列表看起来像那样

和注册字段

首先,对于 SQLite,您需要为您的用户创建一个 table,然后您需要 1 个要放置的元素的列(1 个用于姓氏,1 个用于名称,...)除非你在其中放入包含用户的 JSONObject 之类的东西。

例如:

此 class 是您的 table 及其字段的定义

public final class SQLiteContract{

// this shouldn't be instantiate
public SQLiteContract(){}

public static abstract class UserContract implements BaseColumns {

    /*                              TableName                           */

    public static final String TABLE_NAME = "USER";

    /*                              Fields                             */

    public static final String COLUMN_NAME_NAME = "Name";
    public static final String COLUMN_NAME_SURNAME = "Surname";
    public static final String COLUMN_NAME_TIME = "Time";
    public static final String COLUMN_NAME_DATE = "Date";
}

您应该使用第一个,因为在 sqlite 中有 4 个字段。如果您更喜欢只有一个,则需要更改该部分

    public static final String COLUMN_NAME_NAME = "Name";
    public static final String COLUMN_NAME_SURNAME = "Surname";
    public static final String COLUMN_NAME_TIME = "Time";
    public static final String COLUMN_NAME_DATE = "Date";

进入

    public static final String COLUMN_NAME_USER_JSONOBJECT = "UserObject";

那么第一个 SQLite 应该看起来像这样

private void dbCreateUser(SQLiteDatabase db)
{
    SQL_CREATE_USER = "CREATE TABLE " + UserContract.TABLE_NAME + " (";
    SQL_CREATE_USER += UserContract._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";


    SQL_CREATE_USER += UserContract.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP;
    SQL_CREATE_USER += UserContract.COLUMN_NAME_SURNAME + TEXT_TYPE + COMMA_SEP;
    SQL_CREATE_USER += UserContract.COLUMN_NAME_TIME + TEXT_TYPE + COMMA_SEP;
    SQL_CREATE_USER += UserContract.COLUMN_NAME_DATE_TOUR + TEXT_TYPE;
    SQL_CREATE_USER += " )";
}

第二个只喜欢

private void dbCreateUser(SQLiteDatabase db)
{
    SQL_CREATE_USER = "CREATE TABLE " + UserContract.TABLE_NAME + " (";
    SQL_CREATE_USER += UserContract._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,";
    SQL_CREATE_USER += UserContract. COLUMN_NAME_USER_JSONOBJECT+ TEXT_TYPE;
    SQL_CREATE_USER += " )";
}

请注意,这可能需要一些更新,具体取决于您想要存储数据的方式(如 INT/BLOB/TEXT 等)

此外,变量TEXT_TYPE和COMMA_SEP是这些:

private static final String TEXT_TYPE = " TEXT";
private static final String INTEGER_TYPE = " INTEGER";
private static final String COMMA_SEP = ",";

这里是Link到Google's tutorial for SQLite Databases

然后对于列表视图,您需要创建一个将在列表视图中显示的自定义布局,也许您应该看看 that tutorial