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

时间:2015-07-08 08:06:18

标签: java android sqlite listview android-custom-view

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

有我的Permission类,我处理所有编辑文本字段,按钮确定将所有字符串添加到列表中。

  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>

这是我的详细课程,它使用后退和清除按钮处理列表视图,所以在这个地方我想制作R.layout.simple_expandable_list_item_1自定义,我不知道如何?正如我所说,Name将是Item,姓氏为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));
                    }
            });


    }

 }

详细活动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" >

 <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>

我的列表看起来像那样

enter image description here

并注册字段

enter image description here

1 个答案:

答案 0 :(得分:0)

首先,对于SQLite,你需要为你的用户创建一个表,然后你需要1个coulmn by element(1为姓,1为名,......),除非你放在那里类似于包含用户的JSONObject。

例如:

此类是表格的定义及其字段

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 = ",";

以下是指向Google's tutorial for SQLite Databases

的链接

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