【问题标题】:How to get the selected item's ID from dropdown and send to sqlite android?如何从下拉列表中获取所选项目的 ID 并发送到 sqlite android?
【发布时间】:2018-11-23 03:30:02
【问题描述】:

我有一个自动完成文本视图列表,我在其中填充来自 SQLite 的数据。当我从列表中选择一个名称时,我想获取该特定名称的 ID/主键,然后在单击按钮时将其插入数据库。我怎么做? 这是我在自动完成文本视图中填充数据的代码。

package com.example.user.paperflyv0;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewOrder extends AppCompatActivity {

    String[] executive_num_list;
    public static final String MERCHANT_NAME = "Merchant Name";
    private String EXECUTIVE_URL = "http://paperflybd.com/executiveList.php";
    private String INSERT_URL = "http://192.168.0.117/new/insertassign.php";
    //private String MERCHANT_URL= "http://192.168.0.117/new/merchantlistt.php";
    private String MERCHANT_URL = "http://paperflybd.com/merchantAPI.php";
    private AssignExecutiveAdapter assignExecutiveAdapter;
    List<AssignManager_ExecutiveList> executiveLists;
    List<AssignManager_Model> assignManager_modelList;
    Database database;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_order);
        database = new Database(getApplicationContext());
        database.getWritableDatabase();
        executiveLists = new ArrayList<>();
        assignManager_modelList = new ArrayList<>();

        //Fetching email from shared preferences
        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String username = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
        String user = username.toString();
        getallmerchant();
        getallexecutives();

        final AutoCompleteTextView actv_m_name = findViewById(R.id.auto_m_name);
        final AutoCompleteTextView actv_exe_name = findViewById(R.id.auto_exe_name);
        final EditText count = findViewById(R.id.editText);
        button = findViewById(R.id.btn_assign);

        List<String> merchantnames = new ArrayList<String>();
        List<String> executivenames = new ArrayList<String>();

        for (int z = 0; z < assignManager_modelList.size(); z++) {
            merchantnames.add(assignManager_modelList.get(z).getM_names());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(NewOrder.this,
                android.R.layout.simple_list_item_1, merchantnames);
        /*       adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);*/
        actv_m_name.setAdapter(adapter);


        for (int k = 0; k < executiveLists.size(); k++) {
            executivenames.add(executiveLists.get(k).getExecutive_name());
        }
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(NewOrder.this,
                android.R.layout.simple_list_item_1, executivenames);
        /*       adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);*/
        actv_exe_name.setAdapter(adapter1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                database.insertneworder(actv_m_name.getText().toString(),actv_exe_name.getText().toString(),count.getText().toString());
            }
        });



        }



    private void getallmerchant() {
        try {

            SQLiteDatabase sqLiteDatabase = database.getReadableDatabase();
            Cursor c = database.get_merchantlist(sqLiteDatabase);
            while (c.moveToNext()) {
                String merchantName = c.getString(0);
                String merchantCode = c.getString(1);
                String assigned = c.getString(2);

                AssignManager_Model todaySummary = new AssignManager_Model(merchantName, merchantCode, assigned);
                assignManager_modelList.add(todaySummary);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getallexecutives() {
        try {

            SQLiteDatabase sqLiteDatabase = database.getReadableDatabase();
            Cursor c = database.get_executivelist(sqLiteDatabase);
            while (c.moveToNext()) {
                String empName = c.getString(0);
                String empCode = c.getString(1);
                AssignManager_ExecutiveList assignManager_executiveList = new AssignManager_ExecutiveList(empName, empCode);
                executiveLists.add(assignManager_executiveList);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}

【问题讨论】:

    标签: java android autocomplete


    【解决方案1】:

    覆盖onItemClick方法,检查如下

    @Override
    public void onItemClick(AdapterView<?> av, View view, int pos,long arg3) {
       String selectedText = (String) av.getItemAtPosition(pos);
      //or av.getAdapter().getItem(pos);
    }
    

    【讨论】:

    • 只需浏览以下资源link
    • 是的,我已经拿到了所选项目。并举杯祝酒。那么我如何获得该选定项目的主键?我应该运行数据库查询吗?
    【解决方案2】:

    使用 SQLiteDatabase 时,最好使用 SQLiteOpenHelper 类。

        package com.homemedia.home.stackanswers;
    
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.DatabaseErrorHandler;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    import java.util.ArrayList;
    
    public class DBHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "homemedia.db";
    public DBHelper(Context context){
        super(context, DATABASE_NAME, null, 1);
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
            //create your tables here
    }
    public void addValues(String values){
        //now get writable db here
        SQLiteDatabase db = this.getWritableDatabase();
        //Use content values to enable you enter the values to db
        ContentValues cvalues = new ContentValues();
        cvalues.put("name", values);
        db.insert("tablenamehere", null, cvalues);
        //
    }
    public ArrayList<String> getValues(String queryCriteria){
        //now get readable db here
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<String> itemValues = new ArrayList<>();
        //use cursor to query db
        Cursor cursor = db.rawQuery("Select * from tablename", null);
        cursor .moveToFirst(); //moves to 1st positon
        //goes through all items
        while (!cursor.isAfterLast()){
            // get particular values here and add to arraylist
            itemValues.add(cursor.getString(cursor.getColumnIndex("columnin table")));
            cursor.moveToNext();
        }
        cursor.close();
        return itemValues; //if you need int values, put int ArrayList<int>
    }
    public ArrayList<Integer> empIDs(String criteria){
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<Integer> itemValues = new ArrayList<>();
        //use cursor to query db
        Cursor cursor = db.rawQuery("Select * from tablename WHERE columnValue = criteria ", null);
        cursor .moveToFirst(); //moves to 1st positon
        //goes through all items
        while (!cursor.isAfterLast()){
            // get particular values here and add to arraylist
            itemValues.add(cursor.getInt(cursor.getColumnIndex("primarykey col")));
            //if getting integer is difficult, get as string and convert to int
            cursor.moveToNext();
        }
        cursor.close();
        return itemValues;
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
    }
    

    }

    然后在主Activity中

        public class MainActivity extends AppCompatActivity {
    DBHelper mydb;
    ArrayList<String> mylist;
    ArrayList<Integer> myIDs;
    Spinner myspinner;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mydb =  new DBHelper(this);
        myIDs = mydb.empIDs("search criteria");
        mylist = mydb.getValues("search Criteria");
        // to add info
        mydb.addValues("value to be added");
    myspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String stringId = String.valueOf(myIDs.get(position));
            mydb.addValues(stringId);
        }
    

    我希望这对你有用!

    【讨论】:

    • 在你的情况下;使用 onItemClickListener
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 2017-02-20
    • 2023-03-29
    相关资源
    最近更新 更多