来自数据库onitemselectedlistener的微调器数据不起作用

时间:2013-08-05 07:55:09

标签: android android-activity spinner android-sqlite

从数据库中单击一个微调器数据然后它会显示一些文本。但是我无法实现这一点。使用数据库将微分数据成功添加到微调器中。 这是我的java类文件。我在onItemSelected监听器编码中有错误。请告诉我如何解决这个问题。 主要活动:

package com.samir.spinner;

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

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
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;
import android.widget.TextView;
import android.widget.Toast;

public abstract class MainActivity extends Activity implements OnClickListener,
        OnItemSelectedListener {

    private EditText edittext;
    private Button btnAdd;
    private Spinner spinner;
    DatabaseHelper db;
    List<String> list;
    ArrayAdapter<String> adapter;
    TextView tv;
    Set<String> s;
    protected Cursor c;

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

        db = new DatabaseHelper(MainActivity.this);

        edittext = (EditText) findViewById(R.id.editText1);
        btnAdd = (Button) findViewById(R.id.btnadd);
        spinner = (Spinner) findViewById(R.id.spinner1);

        btnAdd.setOnClickListener(this);
        spinner.setOnItemSelectedListener(this);
    }

    @Override
    public void onClick(View v) {

        String name = edittext.getText().toString().trim();

        if (TextUtils.isEmpty(name)) {
            // showToast("Please Enter Your Name");
            edittext.setError("Please Enter Your Name");
            edittext.requestFocus();
        } else {
            db.insertData(name);
            edittext.setText("");

            // Hiding the keyboard
            InputMethodManager inputmangager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmangager.hideSoftInputFromWindow(edittext.getWindowToken(), 0);

            loadSpinner();
        }

    }

    private void loadSpinner() {
        // here i used Set Because Set doesn't allow duplicates.
        Set<String> set = db.getAllData();

        List<String> list = new ArrayList<String>(set);

        adapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_spinner_item, list);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);
        spinner.setWillNotDraw(false);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View v,
                    int position, long id) {

              Object item=parent.getItemAtPosition(position);
              tv=(TextView) findViewById(R.id.txt);
              tv.setText((CharSequence) item);
            }

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

            }

        });
    }
}

这是我的logcat输出: logcat的:

08-05 08:34:51.647: E/AndroidRuntime(1586): FATAL EXCEPTION: main
08-05 08:34:51.647: E/AndroidRuntime(1586): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.samir.spinner/com.samir.spinner.MainActivity}: java.lang.InstantiationException: can't instantiate class com.samir.spinner.MainActivity
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.os.Looper.loop(Looper.java:137)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.app.ActivityThread.main(ActivityThread.java:5041)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at java.lang.reflect.Method.invokeNative(Native Method)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at java.lang.reflect.Method.invoke(Method.java:511)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at dalvik.system.NativeStart.main(Native Method)
08-05 08:34:51.647: E/AndroidRuntime(1586): Caused by: java.lang.InstantiationException: can't instantiate class com.samir.spinner.MainActivity
08-05 08:34:51.647: E/AndroidRuntime(1586):     at java.lang.Class.newInstanceImpl(Native Method)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at java.lang.Class.newInstance(Class.java:1319)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-05 08:34:51.647: E/AndroidRuntime(1586):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
08-05 08:34:51.647: E/AndroidRuntime(1586):     ... 11 more
08-05 08:37:09.820: I/Process(1586): Sending signal. PID: 1586 SIG: 9

这是我的DatabaseHelper类。 DatabaseHelper.java:

package com.samir.spinner;

import java.util.HashSet;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "mydb";
    private static final String TABLE_NAME = "mytable";
    private static final String _id = "_id";
    private static final String name = "name";

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTableQuery = "create table " + TABLE_NAME + "(" + _id
                + " INTEGER PRIMARY KEY," + name + " TEXT)";
        db.execSQL(createTableQuery);
    }

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

        db.execSQL("drop table if exists " + TABLE_NAME);

        onCreate(db);
    }

    public void insertData(String label) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(name, label);
        db.insert(TABLE_NAME, null, values);
        db.close();
    }


    public Set<String> getAllData() {
        Set<String> set = new HashSet<String>();

        String selectQuery = "select * from " + TABLE_NAME;

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

        if (cursor.moveToFirst()) {
            do {
                set.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }

        cursor.close();
        db.close();

        return set;
    }
}

2 个答案:

答案 0 :(得分:0)

您正在将微调器的onitemselected侦听器设置为“this”上下文。这根本不起作用,这是一个无效的论点。试试这个:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Object item = parent.getItemAtPosition(position);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

编辑:根据以下评论,我认为您的错误可能在这里:

tv.setText((CharSequence) item);

尝试执行item.getText()。toString()。如果这不起作用,省略getText()并执行toString()。不过我不确定。

答案 1 :(得分:0)

更改

Object item=parent.getItemAtPosition(position);

来自

String item = (String) parent.getItemAtPosition(position);

然后简单地写

tv.setText(item); rather then 


tv.setText((CharSequence) item);