2016-03-23 7 views
-1

私は、SQLite DBからテキストのリストを取得するスピナーを持っていますが、1列目、2列目(最初のID)を引っ張っています。私はDBから引き出すためのコードのほとんどを書いていない、私はチュートリアルを見つけ、私が必要なものに合わせてそれを修正した。私が望むのは、2行目と3列目の最初の行を引っ張ってから、すべての行が入力されるまで2行目に移動することです。私のDBはID、BARNAME、BARCITYです。 BARNAMEを引っ張ってカンマをつけて、BARCITYを引っ張りたいのですが。すべての助けに感謝します。私は私のために書かれたコードを持っているつもりはない、私は私が見つけたコードと私のプログラムのためにそれを変更することができますどのように動作しているかを理解しようとしています。Android Spinnerリストのみ1列を引く

MainActivity.java

package com.example.sixth; 
import java.io.IOException; 
import java.util.List; 
import android.app.Activity; 
import android.database.SQLException; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.Spinner; 


public class MainActivity extends Activity implements 
OnItemSelectedListener { 
    DBHelper myDB; 
    Button btnSetCity; 
    Spinner spinner; 

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

     myDB = new DBHelper(this); 
     // Spinner element 
     spinner = (Spinner) findViewById(R.id.spinner); 
    // Spinner click listener 
     spinner.setOnItemSelectedListener(this); 



     try { 
      myDB.createDataBase(); 
     } catch (IOException ioe) { 
      throw new Error("Unable to create database"); 
     } 
     try { 
      myDB.openDataBase(); 
     } catch (SQLException sqle) { 
      throw sqle; 
     } 

     // Loading spinner data from database 
     loadSpinnerData(); 
    } 


    private void loadSpinnerData() { 
      // database handler 
      DBHelper db = new DBHelper(getApplicationContext()); 

      // Spinner Drop down elements 
      List<String> lables = db.getAllLabels(); 

      // Creating adapter for spinner 
      ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, 
        android.R.layout.simple_spinner_item, lables); 

      // Drop down layout style - list view with radio button 
      dataAdapter 
        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

      // attaching data adapter to spinner 
      spinner.setAdapter(dataAdapter); 
     } 

    @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 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); 
    } 


    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
     // TODO Auto-generated method stub 

    } 


    @Override 
    public void onNothingSelected(AdapterView<?> parent) { 
     // TODO Auto-generated method stub 

    } 

} 

DBHelper.java

package com.example.sixth; 

import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.ArrayList; 
import java.util.List; 

import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteException; 
import android.database.sqlite.SQLiteOpenHelper; 

public class DBHelper extends SQLiteOpenHelper { 

    private static String DB_PATH = "/data/data/com.example.sixth/databases/"; 
    private static String DB_NAME = "BarSample.db"; 
    private final Context myContext;  
    public static String tableName = "Bars"; 
    public static final String KEY_ROWID = "_id"; 
    public static final String BARNAME = "Bar Name"; 
    public static final String BARCITY = "Bar City"; 
    private SQLiteDatabase myDataBase; 

    public DBHelper(Context context) { 

     super(context, DB_NAME, null, 1); 
     this.myContext = context; 
    } 

    /** 
    * Creates a empty database on the system and rewrites it with your own 
    * database. 
    */ 
    public void createDataBase() throws IOException { 

     boolean dbExist = checkDataBase(); 

     if (dbExist) { 
      // do nothing - database already exist 
     } else { 

      // By calling this method and empty database will be created into 
      // the default system path 
      // of your application so we are gonna be able to overwrite that 
      // database with our database. 
      this.getReadableDatabase(); 

      try { 
       this.close(); 
       copyDataBase(); 

      } catch (IOException e) { 

       throw new Error("Error copying database"); 
      } 
     } 
    } 

    /** 
    * Check if the database already exist to avoid re-copying the file each 
    * time you open the application. 
    * 
    * @return true if it exists, false if it doesn't 
    */ 
    private boolean checkDataBase() { 

     SQLiteDatabase checkDB = null; 

     try { 
      String myPath = DB_PATH + DB_NAME; 
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

     } catch (SQLiteException e) { 
      // database does't exist yet. 
     } 
     if (checkDB != null) { 
      checkDB.close(); 
     } 
     return checkDB != null ? true : false; 
    } 

    /** 
    * Copies your database from your local assets-folder to the just created 
    * empty database in the system folder, from where it can be accessed and 
    * handled. This is done by transfering bytestream. 
    */ 
    private void copyDataBase() throws IOException { 

     // Open your local db as the input stream 
     InputStream myInput = myContext.getAssets().open(DB_NAME); 

     // Path to the just created empty db 
     String outFileName = DB_PATH + DB_NAME; 

     // Open the empty db as the output stream 
     OutputStream myOutput = new FileOutputStream(outFileName); 

     // transfer bytes from the inputfile to the outputfile 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = myInput.read(buffer)) > 0) { 
      myOutput.write(buffer, 0, length); 
     } 

     // Close the streams 
     myOutput.flush(); 
     myOutput.close(); 
     myInput.close(); 

    } 

    public void openDataBase() throws SQLException { 

     // Open the database 
     String myPath = DB_PATH + DB_NAME; 
     myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

    } 

    @Override 
    public synchronized void close() { 

     if (myDataBase != null) 
      myDataBase.close(); 

     super.close(); 

    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 

    } 

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

    } 

    public List<String> getAllLabels(){ 
     List<String> labels = new ArrayList<String>(); 

     // Select All Query 
     String selectQuery = "SELECT * FROM " + tableName; 

     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery, null); 

     // looping through all rows and adding to list 
     if (cursor.moveToFirst()) { 
      do { 
       labels.add(cursor.getString(1)); 
      } while (cursor.moveToNext()); 
     } 

     // closing connection 
     cursor.close(); 
     db.close(); 

     // returning lables 
     return labels; 

    } // will returns all labels stored in database 
} 

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" 
    tools:context=".MainActivity" 
    tools:ignore="HardcodedText" > 

    <TextView 
     android:id="@+id/select_location" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerHorizontal="true" 
     android:layout_centerVertical="true" 
     android:text="@string/select_location" 
     android:textSize="30sp" /> 

    <Spinner 
     android:id="@+id/spinner" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/select_location" 
     android:layout_centerHorizontal="true" 
     android:entries="@array/locations" /> 

    <Button 
     android:id="@+id/btnSetCity" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/spinner" 
     android:layout_centerHorizontal="true" 
     android:text="@string/set_city" 
     android:textSize="30sp" /> 

</RelativeLayout> 
+0

。これはあなたの仕事を行います。..

labels.add(cursor.getString(1) + ", " + cursor.get string(2)); 

を上記の行を変更します。このチュートリアルでコピーしたコードを他の人に修正させるためにここに来た場合は、(1)何も学んでいない、(2)コンサルタントまたはプログラマーが必要です。あなたの質問は広すぎます。あなたがコピーしたコードを理解しようとする - おそらくそれと一緒に散文を読む?次に、必要な変更を自分で行ってください。まだ失敗したら、ここに戻ってきてください! – 323go

+0

ちょうどコードがありました。何の説明も、それがどのように動作するのか、またその理由を示すビデオもありません。私は約4時間の間、他の場所で情報を調べようとしましたが、それをよりよく理解するのに役立つ何かを見つけることができませんでした。だから私がここに来たのは、誰かが私のコードを書くのではなく、理解しやすくすることを望むことを望んでいたからです。 – Inessaria

答えて

0

変更し、あなたの次の行...

labels.add(cursor.getString(1)); 

ここでは、1つの列だけを取得しています。データをBarName、BarCity correctとして表示する必要があります。次のように

その後チュートリアルはあなたに何かを教えるためのものです

+0

たとえば、何らかの理由でIDを表示したい場合は、labels.add(cursor.getString(0)+ "、" + cursor.getString(1)+ "、" + cursor.get string (2)); ? – Inessaria

+0

それは正しいです。数字0,1,2は、データベースの作成中に保存した順番の列番号を指します。 –

+0

優秀です。どうもありがとうございました。私はあなたの助けに感謝します。 – Inessaria