繁体   English   中英

Android-SQLite3多列

[英]Android - SQLite3 Multiple Columns

我在将代码从两个文本框中插入两个单独的列的代码时遇到麻烦。

输入:

名称= 1等级= 2

电流输出:

(第1行)名称= 11等级=空

所需的输出:

(第1行)名称= 1等级= 2

任何帮助将不胜感激。

添加页面上的代码(文本框+保存按钮):

package org.x.x;

import org.x.x.R;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Add extends Foundation {

 private EditText input, input2;
 private Button saveButton;

 @Override
 public void onCreate(final Bundle savedInstanceState) {
  Log.d(MyApplication.APP_NAME, "onCreate");
     super.onCreate(savedInstanceState);

     this.setContentView(R.layout.add);

     // get "Application" object for shared state or creating of expensive resources - like DataHelper
     // (this is not recreated as often as each Activity)
     this.application = (MyApplication) this.getApplication();

     // inflate views
     this.input = (EditText) this.findViewById(R.id.Beverage_Txt);
     this.input2 = (EditText) this.findViewById(R.id.Rank_Txt);
     this.saveButton = (Button) this.findViewById(R.id.save_button);
     //this.deleteButton = (Button) this.findViewById(R.id.del_button);
     //this.output = (TextView) this.findViewById(R.id.out_text);

     // save new data to database (when save button is clicked)
     this.saveButton.setOnClickListener(new OnClickListener() {
       public void onClick(final View v) {
        new InsertDataTask().execute(Add.this.input.getText().toString(), Add.this.input2.getText().toString());
          Add.this.input.setText("");
          Add.this.input2.setText("");
       }
       });
 }

 @Override
 public void onSaveInstanceState(final Bundle b) {
  Log.d(MyApplication.APP_NAME, "onSaveInstanceState");
     if ((this.input.getText().toString() != null) && (this.input.getText().toString().length() > 0)) {
      b.putString(Add.NAME, this.input.getText().toString());
     }
     if ((this.input2.getText().toString() != null) && (this.input2.getText().toString().length() > 0)) {
      b.putString(Add.RANK, this.input2.getText().toString());
     }
     super.onSaveInstanceState(b);
 }

 @Override
 public void onRestoreInstanceState(final Bundle b) {
  super.onRestoreInstanceState(b);
  Log.d(MyApplication.APP_NAME, "onRestoreInstanceState");
  String name = b.getString(Foundation.NAME);
  String rank = b.getString(Foundation.RANK);
  if (name != null) {
      // use onSaveInstanceState/onRestoreInstance state to manage state when orientation is changed (and whenever restarted)
         // put some text in input box, then rotate screen, text should remain
         // COMMENT this out, and try again, text won't be there - you need to maintain this state - esp for orientation changes
         // (you can rotate the screen in the emulator by pressing 9 on numeric keypad)
         this.input.setText(name);
  }
  if (rank != null) {
      // use onSaveInstanceState/onRestoreInstance state to manage state when orientation is changed (and whenever restarted)
         // put some text in input box, then rotate screen, text should remain
         // COMMENT this out, and try again, text won't be there - you need to maintain this state - esp for orientation changes
         // (you can rotate the screen in the emulator by pressing 9 on numeric keypad)
         this.input2.setText(rank);
  }
 }

 private class InsertDataTask extends AsyncTask<String, Void, Void> {
       private final ProgressDialog dialog = new ProgressDialog(Add.this);

       // can use UI thread here
       protected void onPreExecute() {
          this.dialog.setMessage("Inserting data...");
          this.dialog.show();
       }

       // automatically done on worker thread (separate from UI thread)
       protected Void doInBackground(final String... args) {
          Add.this.application.getDataHelper().insert(args[0], args[0]);
          return null;
       }

       // can use UI thread here
       protected void onPostExecute(final Void unused) {
          if (this.dialog.isShowing()) {
             this.dialog.dismiss();
          }
          // reset the output view by retrieving the new data
          // (note, this is a naive example, in the real world it might make sense
          // to have a cache of the data and just append to what is already there, or such
          // in order to cut down on expensive database operations)
          //new SelectDataTask().execute();
       }
 }

 @Override
 public void onBackPressed() {
  this.startActivity(new Intent(Add.this, Compare.class));
 }
}

Datahelper代码:

package org.x.x;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DataHelper {

   private static final String DATABASE_NAME = "example.db";
   private static final int DATABASE_VERSION = 1;
   private static final String TABLE_NAME = "table1";

   private Context context;
   private SQLiteDatabase db;

   private SQLiteStatement insertStmt;

   private static final String INSERT = "insert into " + TABLE_NAME + "(name, rank) values (?, ?)";

   public DataHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
   }

   public SQLiteDatabase getDb() {
      return this.db;
   }

   public long insert(String name, String rank) {
      this.insertStmt.bindString(1, name + rank);

      return this.insertStmt.executeInsert();
   }

   public void deleteAll() {
      this.db.delete(TABLE_NAME, null, null);
   }

   public List<String> selectAll() {
      List<String> list = new ArrayList<String>();
      Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name", "rank" }, null, null, null, null, "id desc");
      if (cursor.moveToFirst()) {
         do {
            list.add(cursor.getString(0));
            list.add(cursor.getString(1)); 
         } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }
      return list;
   }

   private static class OpenHelper extends SQLiteOpenHelper {

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

      @Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, name TEXT, rank TEXT)");
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         Log.w("Example", "Upgrading database, this will drop tables and recreate.");
         db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
         onCreate(db);
      }
   }
}

模板代码(共享资源):

package org.x.x;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.TextView;

public class Foundation extends Activity {

   public static final String NAME = "NAME";
   public static final String RANK = "RANK";

   public MyApplication application;

   public TextView output;

   public class SelectDataTask extends AsyncTask<String, Void, String> {
       private final ProgressDialog dialog = new ProgressDialog(Foundation.this);

       // can use UI thread here
       protected void onPreExecute() {
          this.dialog.setMessage("Selecting data...");
          this.dialog.show();
       }

       // automatically done on worker thread (separate from UI thread)
       protected String doInBackground(final String... args) {
          List<String> names = Foundation.this.application.getDataHelper().selectAll();
          /*List<String> ranks = Foundation.this.application.getDataHelper().selectAll();*/
          StringBuilder sb = new StringBuilder();
          for (String name : names) {
             sb.append(name + "\n");
          }
          /*for (String rank : ranks) {
        sb.append(rank + "\n");
       }*/
          return sb.toString();
       }

       // can use UI thread here
       protected void onPostExecute(final String result) {
          if (this.dialog.isShowing()) {
             this.dialog.dismiss();
          }
          Foundation.this.output.setText(result);
       }
 }
}

MyApplication代码:

package org.x.x;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

   public static final String APP_NAME = "x";  

   private DataHelper dataHelper;   

   @Override
   public void onCreate() {
      super.onCreate();
      Log.d(APP_NAME, "APPLICATION onCreate");
      this.dataHelper = new DataHelper(this);      
   }

   @Override
   public void onTerminate() {
      Log.d(APP_NAME, "APPLICATION onTerminate");      
      super.onTerminate();      
   }

   public DataHelper getDataHelper() {
      return this.dataHelper;
   }

   public void setDataHelper(DataHelper dataHelper) {
      this.dataHelper = dataHelper;
   }
}

您只是在插入对象上调用bindString仅绑定一个值。 通过以下方式在DataHelper中尝试insert():

   public long insert(String name, String rank) {
      this.insertStmt.bindString(1, name);
      this.insertStmt.bindString(2, rank);

      return this.insertStmt.executeInsert();
   }

我发现了问题,已更改(在“添加”页面上):

      protected Void doInBackground(final String... args) {
         Add.this.application.getDataHelper().insert(args[0], args[0]);
         return null;
      }

至:

      protected Void doInBackground(final String... args) {
         Add.this.application.getDataHelper().insert(args[0], args[1]);
         return null;
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM