2016-03-23 6 views
-1

Ich habe einen Spinner, der seine Liste von Text aus einer SQLite DB zieht, aber es zieht nur eine Spalte, die zweite (die erste ID). Ich habe den Großteil des Codes nicht geschrieben, um aus der DB zu ziehen, ich fand ein Tutorial und modifizierte es, um zu passen, was ich brauchte. Was ich möchte ist, dass es die erste Zeile, die Spalten 2 und 3, zieht und dann in der zweiten Zeile weitergeht, bis alle Zeilen eingegeben sind. Meine DB ist ID, BARNAME, BARCITY. Ich möchte BARNAME ziehen, dann ein Komma, dann BARCITY ziehen. Alle Hilfe wird geschätzt. Ich versuche nicht, den Code für mich zu schreiben, ich versuche den Code, den ich gefunden habe, besser zu verstehen und zu verstehen, damit ich ihn für mein Programm modifizieren kann.Android Spinner Liste zieht nur 1 Spalte

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

Ein Tutorial Sie soll etwas lehren. Wenn Sie hierher kommen, um andere Leute daran zu hindern, den Code zu kopieren, den Sie aus diesem Tutorial kopiert haben, dann haben Sie (1) nichts gelernt und (2) Sie brauchen einen Berater oder Programmierer. Deine Frage ist zu weit gefasst. Versuchen Sie, den kopierten Code zu verstehen - lesen Sie vielleicht die dazugehörige Prosa? Versuchen Sie dann, die erforderlichen Änderungen selbst vorzunehmen. Wenn Sie immer noch scheitern, kommen Sie hierher zurück! – 323go

+0

Es gab nur Code. Keine Erklärung, kein Video, wie es funktioniert oder warum. Ich habe versucht, die Informationen woanders zu suchen, für ungefähr 4 Stunden, aber ich konnte nichts finden, was mir half, es besser zu verstehen. Deshalb bin ich hierher gekommen, in der Hoffnung, dass jemand mir helfen könnte, besser zu verstehen, nicht den Code für mich zu schreiben. – Inessaria

Antwort

0

Ändern Sie Ihre folgende Zeile ..

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

Hier holen Sie nur eine Spalte. Sie müssen die Daten als BarName, BarCity korrekt anzeigen.?

dann die obige Zeile wie folgt ändern ..

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

Diese Arbeit tun ..

+0

Und wenn ich zum Beispiel die ID aus irgendeinem Grund zeigen wollte, würde ich labels.add verwenden (cursor.getString (0) + "," + cursor.getString (1) + "," + cursor.get string (2)); ? – Inessaria

+0

Das ist richtig. Die Zahl 0,1,2 bezieht sich auf die Spaltennummern in der Reihenfolge, in der Sie die Datenbank angelegt haben. –

+0

Excellent. Vielen Dank. Ich schätze Ihre Hilfe. – Inessaria