How to get the selected item's ID from dropdown and send to sqlite android?












0















I have an Autocomplete textview list where I am populating data from SQLite. When I am selecting one name from the list I want to get the ID/primary key of that particular name and then insert it to the database when a button is clicked. How do I do that?
This is my code by which I am populating data in the Autocomplete text view.



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




}









share|improve this question



























    0















    I have an Autocomplete textview list where I am populating data from SQLite. When I am selecting one name from the list I want to get the ID/primary key of that particular name and then insert it to the database when a button is clicked. How do I do that?
    This is my code by which I am populating data in the Autocomplete text view.



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




    }









    share|improve this question

























      0












      0








      0








      I have an Autocomplete textview list where I am populating data from SQLite. When I am selecting one name from the list I want to get the ID/primary key of that particular name and then insert it to the database when a button is clicked. How do I do that?
      This is my code by which I am populating data in the Autocomplete text view.



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




      }









      share|improve this question














      I have an Autocomplete textview list where I am populating data from SQLite. When I am selecting one name from the list I want to get the ID/primary key of that particular name and then insert it to the database when a button is clicked. How do I do that?
      This is my code by which I am populating data in the Autocomplete text view.



      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






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 21 '18 at 6:52









      nawshin.ahmednawshin.ahmed

      107




      107
























          2 Answers
          2






          active

          oldest

          votes


















          0














          override the onItemClick method and check as follows



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





          share|improve this answer
























          • just go through the following resources link

            – Chamila Lakmal
            Nov 21 '18 at 7:06











          • yes i have got the selected item. and showing it to a toast. Then how do i get the primary key of that selected item? should i run a database query?

            – nawshin.ahmed
            Nov 21 '18 at 7:43



















          0














          When working with SQLiteDatabase, it is best to use SQLiteOpenHelper class.



              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) {

          }


          }



          Then in main 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);
          }


          I hope this works for you!






          share|improve this answer
























          • In your case; use onItemClickListener

            – Amale Balla Sunday
            Nov 22 '18 at 19:38











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53406677%2fhow-to-get-the-selected-items-id-from-dropdown-and-send-to-sqlite-android%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          override the onItemClick method and check as follows



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





          share|improve this answer
























          • just go through the following resources link

            – Chamila Lakmal
            Nov 21 '18 at 7:06











          • yes i have got the selected item. and showing it to a toast. Then how do i get the primary key of that selected item? should i run a database query?

            – nawshin.ahmed
            Nov 21 '18 at 7:43
















          0














          override the onItemClick method and check as follows



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





          share|improve this answer
























          • just go through the following resources link

            – Chamila Lakmal
            Nov 21 '18 at 7:06











          • yes i have got the selected item. and showing it to a toast. Then how do i get the primary key of that selected item? should i run a database query?

            – nawshin.ahmed
            Nov 21 '18 at 7:43














          0












          0








          0







          override the onItemClick method and check as follows



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





          share|improve this answer













          override the onItemClick method and check as follows



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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 7:01









          Chamila LakmalChamila Lakmal

          6125




          6125













          • just go through the following resources link

            – Chamila Lakmal
            Nov 21 '18 at 7:06











          • yes i have got the selected item. and showing it to a toast. Then how do i get the primary key of that selected item? should i run a database query?

            – nawshin.ahmed
            Nov 21 '18 at 7:43



















          • just go through the following resources link

            – Chamila Lakmal
            Nov 21 '18 at 7:06











          • yes i have got the selected item. and showing it to a toast. Then how do i get the primary key of that selected item? should i run a database query?

            – nawshin.ahmed
            Nov 21 '18 at 7:43

















          just go through the following resources link

          – Chamila Lakmal
          Nov 21 '18 at 7:06





          just go through the following resources link

          – Chamila Lakmal
          Nov 21 '18 at 7:06













          yes i have got the selected item. and showing it to a toast. Then how do i get the primary key of that selected item? should i run a database query?

          – nawshin.ahmed
          Nov 21 '18 at 7:43





          yes i have got the selected item. and showing it to a toast. Then how do i get the primary key of that selected item? should i run a database query?

          – nawshin.ahmed
          Nov 21 '18 at 7:43













          0














          When working with SQLiteDatabase, it is best to use SQLiteOpenHelper class.



              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) {

          }


          }



          Then in main 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);
          }


          I hope this works for you!






          share|improve this answer
























          • In your case; use onItemClickListener

            – Amale Balla Sunday
            Nov 22 '18 at 19:38
















          0














          When working with SQLiteDatabase, it is best to use SQLiteOpenHelper class.



              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) {

          }


          }



          Then in main 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);
          }


          I hope this works for you!






          share|improve this answer
























          • In your case; use onItemClickListener

            – Amale Balla Sunday
            Nov 22 '18 at 19:38














          0












          0








          0







          When working with SQLiteDatabase, it is best to use SQLiteOpenHelper class.



              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) {

          }


          }



          Then in main 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);
          }


          I hope this works for you!






          share|improve this answer













          When working with SQLiteDatabase, it is best to use SQLiteOpenHelper class.



              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) {

          }


          }



          Then in main 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);
          }


          I hope this works for you!







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 19:30









          Amale Balla SundayAmale Balla Sunday

          11




          11













          • In your case; use onItemClickListener

            – Amale Balla Sunday
            Nov 22 '18 at 19:38



















          • In your case; use onItemClickListener

            – Amale Balla Sunday
            Nov 22 '18 at 19:38

















          In your case; use onItemClickListener

          – Amale Balla Sunday
          Nov 22 '18 at 19:38





          In your case; use onItemClickListener

          – Amale Balla Sunday
          Nov 22 '18 at 19:38


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53406677%2fhow-to-get-the-selected-items-id-from-dropdown-and-send-to-sqlite-android%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Guess what letter conforming each word

          Port of Spain

          Run scheduled task as local user group (not BUILTIN)