Хранение данных SQLite

SQLite, Preferences, файлы, SD, Content Provider, XML, JSON
Ответить
tolyan
Сообщения: 10
Зарегистрирован: 15 фев 2014, 00:38

Хранение данных SQLite

Сообщение tolyan » 30 мар 2014, 17:29

Привет всем. У меня возникли трудности с бд, кто в этом вопросов понимается помогите пожалуйста. Я смотрел урок http://startandroid.ru/ru/uroki/vse-uro ... qlite.html, но все равно не получается сделать. Недавно начал изучать android. Хочу, чтобы бд выглядела так как на картинкеИзображение
тип всех полей string. Хочу, чтобы при нажиме кнопки поля которые были заполнении хранились в бд.
Буду очень благодарен за помощь.
ПС.
Вот код main.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" >

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#DAC3C3"
        android:orientation="horizontal" >

        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#FFFFFF"
            android:orientation="vertical"
            android:layout_marginLeft="30px"
            android:layout_marginTop="50px" >

            <TextView
                android:id="@+id/textDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Прізвище,Ім'я:"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_marginTop="25px" />

            <EditText
                android:id="@+id/editName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="15"
                android:inputType="textPersonName" 
                android:layout_marginTop="10px"/>

            <TextView
                android:id="@+id/textTelephone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Телефон:"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_marginTop="25px" />

            <EditText
                android:id="@+id/editTelephone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:layout_marginTop="10px" />

            <TextView
                android:id="@+id/textDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Дата:"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_marginTop="15px" />

            <EditText
                android:id="@+id/editDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="date"
                android:layout_marginTop="10px" />
        </RadioGroup>

        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100px"
            android:background="#FFFFFF"
            
            android:layout_marginTop="100px"  >

            <TextView
                android:id="@+id/textMaster"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Майстер:"
                android:textAppearance="?android:attr/textAppearanceMedium" 
                android:layout_marginTop="25px"/>

            <Spinner
                android:id="@+id/spinnerMaster"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1" 
                 android:layout_marginTop="10px"
              
                />

            <TextView
                android:id="@+id/textTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Час:"
                android:textAppearance="?android:attr/textAppearanceMedium" 
                android:layout_marginTop="25px"/>

            <Spinner
                android:id="@+id/spinnerTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                 android:layout_marginTop="10px" />

            <Button
                android:id="@+id/buttonWrite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Записатись" />
        </RadioGroup>
    </RadioGroup>

</LinearLayout>
Код MainActivity

Код: Выделить всё


package com.pr4_sql;


import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class MainActivity extends Activity  {
	
	 final String LOG_TAG = "myLogs";
	 
	  String[] SSpinnerMaster = {"Вася", "Петя", "Федя", "Коля", "Ваня"};
	  String[] SSpinnerTime = {"9:00", "10:00", "11:00", "12:00"};
	  
		final String View = "short";
		
		String SEditName;
		String SEditTelephone;
		String SEditDate;
	
		DBHelper dbHelper;
		
	  @Override
	  protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);	    
	    setContentView(R.layout.main);	    
	   
	    dbHelper = new DBHelper(this);
	    
	    //adapter
	    ArrayAdapter<String> AdapterSpinnerMaster = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SSpinnerMaster);
        AdapterSpinnerMaster.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        ArrayAdapter<String> AdapterSpinnerTime = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, SSpinnerTime);
        AdapterSpinnerTime.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        final Spinner SpinnerMaster = (Spinner)findViewById(R.id.spinnerMaster);
        SpinnerMaster.setAdapter(AdapterSpinnerMaster);
        SpinnerMaster.setPrompt("Master");
        SpinnerMaster.setSelection(0);
     
        SpinnerMaster.setOnItemSelectedListener(new OnItemSelectedListener() {
        	 @Override
        	 	public void onItemSelected(AdapterView<?> parent, View view,
                 int position, long id) {
                }
             @Override
             public void onNothingSelected(AdapterView<?> arg0) {
             }
		});
        
        final Spinner SpinnerTime = (Spinner)findViewById(R.id.spinnerTime);
        SpinnerTime.setAdapter(AdapterSpinnerTime);
        SpinnerTime.setPrompt("Time");
        SpinnerTime.setSelection(0);
        
        SpinnerTime.setOnItemSelectedListener(new OnItemSelectedListener() {
       	 @Override
       	 	public void onItemSelected(AdapterView<?> parent, View view,
                int position, long id) {
               }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
		});
       
        
        
        
	    Button ButtonWrite = (Button)findViewById(R.id.buttonWrite);
	    
	    final EditText EditName = (EditText)findViewById(R.id.editName);
	    final EditText EditTelephone = (EditText)findViewById(R.id.editTelephone);
	    final EditText EditDate = (EditText)findViewById(R.id.editDate);
	    
	    
	    
	    ButtonWrite.setOnClickListener(new OnClickListener() {		   
		@Override
		public void onClick(View v) {
		
			ContentValues cv = new ContentValues();
			
			SEditDate = EditDate.getText().toString();
			SEditTelephone = EditTelephone.getText().toString();
			SEditName = EditName.getText().toString();
			String SEditMaster = SpinnerMaster.getSelectedItem().toString();
			String SEditTime = SpinnerTime.getSelectedItem().toString();

		    // подключаемся к БД
		    SQLiteDatabase db = dbHelper.getWritableDatabase();
		    
		    
		    switch (v.getId())
		    {
		    case R.id.buttonWrite:
		    	{
		    		Log.d(LOG_TAG, "--- Insert in mytable: ---");
		    		// подготовим данные для вставки в виде пар: наименование столбца - значение
		      
		    		cv.put("name", SEditName);
		    		cv.put("telephone", SEditTelephone);
		    		cv.put("date", SEditDate );
		    		cv.put("master", SEditMaster);
		    		cv.put("time", SEditTime);
		    		cv.put("view", "test number of one");
		    		// вставляем запись и получаем ее ID
		    		long rowID = db.insert("mytable", null, cv);
		    		Log.d(LOG_TAG, "row inserted, ID = " + rowID);
		    		
		    		
		    		
		    		
		    		///виведення
		    		 Log.d(LOG_TAG, "--- Rows in mytable: ---");
		    	      // делаем запрос всех данных из таблицы mytable, получаем Cursor 
		    	      Cursor c = db.query("mytable", null, null, null, null, null, null);

		    	      // ставим позицию курсора на первую строку выборки
		    	      // если в выборке нет строк, вернется false
		    	      if (c.moveToFirst()) {

		    	        // определяем номера столбцов по имени в выборке
		    	        int idColIndex = c.getColumnIndex("id");
		    	        int nameColIndex = c.getColumnIndex("name");
		    	        int telephoneColIndex = c.getColumnIndex("telephone");
		    	        int dateColIndex = c.getColumnIndex("date");
		    	        int masterColIndex = c.getColumnIndex("master");
		    	        int timeColIndex = c.getColumnIndex("time");
		    	        int viewColIndex = c.getColumnIndex("view");
		    	        do {
		    	          // получаем значения по номерам столбцов и пишем все в лог
		    	          Log.d(LOG_TAG,
		    	              "ID = " + c.getInt(idColIndex) + 
		    	              ", name = " + c.getString(nameColIndex) + 
		    	               ", telephone = " + c.getString(telephoneColIndex) + 
		    	                ", date = " + c.getString(dateColIndex) + 
		    	                 ", master = " + c.getString(masterColIndex) + 
		    	                 ", time = " + c.getString(timeColIndex) +  
		    	              ", view = " + c.getString(viewColIndex));
		    	          // переход на следующую строку 
		    	          // а если следующей нет (текущая - последняя), то false - выходим из цикла
		    	        } while (c.moveToNext());
		    	      } else
		    	        Log.d(LOG_TAG, "0 rows");
		    	      c.close();
		    		
		    		
		    	      ////////////// видалення
		    	      if(3<6)
		    	      {
		    	    	  Log.d(LOG_TAG, "--- Clear mytable: ---");
		    	          // удаляем все записи
		    	          int clearCount = db.delete("mytable", null, null);
		    	          Log.d(LOG_TAG, "deleted rows count = " + clearCount);
		    	      }
		    	      
		    	      
		    		
		    		
		    		
		    		break;
		    	}
		    	
		    	default:
		    		break;
		    	
		    }
		    
		    
		    
		    
		    dbHelper.close();  
		    
		}
		 
	});
		
	    
	    	    
	  }//oncreate
	
	
}



class DBHelper extends SQLiteOpenHelper {

    private static final String LOG_TAG = null;

	public DBHelper(Context context) {
      // конструктор суперкласса
      super(context, "myDB", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      Log.d(LOG_TAG, "--- onCreate database ---");
      // создаем таблицу с полями
      db.execSQL("create table mytable ("
          + "id integer primary key autoincrement," 
          + "name text,"
          + "telephone text,"
          + "date text,"
          + "master text,"
          + "time text,"
          + "view text" + ");");
    }

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

    }
  }

Вложения
Безымянный.png
Безымянный.png (19.36 КБ) 1734 просмотра

Ответить