How to get customer id of selected value from spinner - java

I want to get the id of the value selected in the spinner. For example when i add new customer, the customer name is "jack" and id is "4". Then i can select customer name - "jack in spinner", how to get id "4".
The Database:
public List<String> getAllUsers(String userID) {
List<String> userlist = new ArrayList<>();
String status= "Active";
SQLiteDatabase db = this.getReadableDatabase();
String query = "select " + COLUMN_Customer_NAME + " from customer where " + COLUMN_Customer_USERID + "='" + userID + "'"+" AND " + COLUMN_Customer_STATUS + "='" + status + "'";
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
userlist.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return userlist;
}
The implementation code:
prepareData();
allusers.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// clicked item will be shown as spinner
value = parent.getItemAtPosition(position).toString();
custid = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
public void prepareData()
{
users=databaseHelper.getAllUsers(user_id2);
//adapter for spinner
adapter=new ArrayAdapter<String>(AddMobRepairActivity.this,android.R.layout.simple_dropdown_item_1line,android.R.id.text1,users);
//attach adapter to spinner
allusers.setAdapter(adapter);
}

prepareData();
allusers.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// clicked item will be shown as spinner
value = parent.getItemAtPosition(position).toString();
custid = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
public void prepareData()
{
users=databaseHelper.getAllUsers(user_id2);
//adapter for spinner
adapter=new ArrayAdapter<String>(AddMobRepairActivity.this,android.R.layout.simple_dropdown_item_1line,android.R.id.text1,users);
//attach adapter to spinner
allusers.setAdapter();
}

Related

Can't delete an item from list view and the SQLLITE database that have custom adapter

Main activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addButton = findViewById(R.id.addButton);
calendar = findViewById(R.id.calendarButton);
balance = findViewById(R.id.balance);
operationList = findViewById(R.id.operationList);
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
arrayList =dataBaseHelper.getAllData();
myAdapter = new CustomAdapter(MainActivity.this,arrayList);
operationList.setAdapter(myAdapter);
operationList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Operation clickedOperation = (Operation) parent.getItemAtPosition(position);
dataBaseHelper.deleteOne(clickedOperation);
arrayList =dataBaseHelper.getAllData();
myAdapter = new CustomAdapter(MainActivity.this,arrayList);
operationList.setAdapter(myAdapter);
Toast.makeText(MainActivity.this, "You have delete "+ clickedOperation.getName() + "operation", Toast.LENGTH_SHORT).show();
}
});
}
}
deleteOne method from databaseHelper class:
public boolean deleteOne(Operation operation){
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM " + OPERATION_TABLE + " WHERE " + COLUMN_ID + " = " + Operation.getId();
Cursor cursor= db.rawQuery(queryString,null);
if(cursor.moveToFirst()){
return true;
}else{
return false;
}
}
The main activity and the list view where I'm going to delete from
: https://i.stack.imgur.com/pJd1J.png

How to get selected item id from JSON in Spinner?

How to get id From JSON in spinner ?
i want get city id, if i choose item in spinner
example : https://imgur.com/shvfvnO,
if i choose "ACEH BARAT", i'll get id "512"
public void displayCities(List<CityResponse.City> cities) {
for (CityResponse.City city : cities) {
Log.d(TAG, city.getNama());
spinnerItem.add(city.getNama());
adapter.notifyDataSetChanged();
}
}
private void setSpinner(Context context){
adapter = new ArrayAdapter<>(context, R.layout.spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainBinding.spinnerCity.setAdapter(adapter);
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
Toast.makeText(context, "City : " + citySelected, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
You need to create another arraylist to store id
locationId.add(i, response.getData());
now you need to get Id in spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
try {
selectedId = (String) locationId.get(position);
} catch (Exception e) {
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
You need to update mainBinding.spinnerCity.setOnItemSelectedListener() inside setSpinnner() method as I have added below:
private void setSpinner(Context context){
adapter = new ArrayAdapter<>(context, R.layout.spinner_item, spinnerItem);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mainBinding.spinnerCity.setAdapter(adapter);
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Comment by Hari: You have already position available here so why you are doing this..
//String citySelected = parent.getItemAtPosition(position).toString();
/*Comment by Hari: If CityModel is the model of your cities ArrayList then it can be received inside spinner from the same index position as of the item as you are creating spinnerItemList in loop and both the list item position will be synced. */
CityModel cityModel = cities.get(position);
String citySelected = cityModel.getCity(); //Where cities is the main array in your activity class.
String cityId = cityModel.getCityId();
Toast.makeText(context, "City Name: " + citySelected + " // City Id: cityId" + , Toast.LENGTH_LONG).show();
//Do what you want to do next with the cityId here....
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});
}
Change your onItemSelected like this
mainBinding.spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String citySelected = parent.getItemAtPosition(position).toString();
for (CityResponse.City city : cities) {
if(city.getNama().equalsIgnoreCase(citySelected){
String city_id = city.getCityId(); //THIS IS YOUR CITY ID
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Not Selected", Toast.LENGTH_LONG).show();
}
});

How to debug the error "String resource ID #0x0"

I want to get the value of the selected item when I select the item in the list view.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = getText(position).toString();
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
In this code, String data = getText(position).toString(), I get this error:
a String resource ID #0x0
This code is add listview
void DBadd() {
String name = addTxt1.getText().toString();
String info = addTxt2.getText().toString();
if (name.equals("") || info.equals("")) {
Toast.makeText(getApplicationContext(), "정보를 입력해 주세요", Toast.LENGTH_SHORT).show();
return;
} else {
db.execSQL("INSERT INTO tableName VALUES (null, '" + name + "', '" + info + "');");
Toast.makeText(getApplicationContext(), "추가 성공", Toast.LENGTH_SHORT).show();
addTxt1.setText(""); //입력시 EditText에 입력된값 지움
addTxt2.setText("");
cursor = db.rawQuery("SELECT * FROM tableName", null);
startManagingCursor(cursor); //엑티비티의 생명주기와 커서의 생명주기를 같게 한다.
adapter = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_1);
adapter2 = new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_list_item_1);
while (cursor.moveToNext()) {
adapter.add(cursor.getString(1));
adapter2.add(cursor.getString(2));
}
listView.setAdapter(adapter);
listView2.setAdapter(adapter2);
}
}
How do I get the value of a selected item?
Try this, it works for me:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = listView.getItemAtPosition(position).toString();
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
Or, just fetch the string value directly from adapter using .get(postion) like that :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String data = adapter.get(position);
Toast.makeText(Main2Activity.this,data,Toast.LENGTH_SHORT).show();
}
});
Good Luck
I'm not sure did i understood your question correctly, but let me guess the desired behavior:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textViewOfTheClickedRaw = view.findViewById(android.R.id.text1);
String data = textViewOfTheClickedRaw.getText().toString();
Toast.makeText(Main2Activity.this, data, Toast.LENGTH_SHORT).show();
}
});
This is how you can get the value of TextView from android.R.layout.simple_list_item_1
But I really doesn't think this is how things should work in your app

How do I delete an item from an SQ Lite Database in Android?

Sorry for my English. I am new in Android Development. I have an app in which the user make notes. When the user make his note, the note is saved in a SQ Lite Database and is shown in a ListView. When I want to delete the note, the note is removed from the ListView but not from the Database. Could you help me?
MainActivity.java
public class MainActivity extends Activity
{
private InputDbHelper mHelper;
private ListView mListView;
private EditText mEditText;
private Button mButton;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.button);
mEditText = (EditText) findViewById(R.id.editText);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mListView=(ListView)findViewById(R.id.listView);
mListView.setAdapter(adapter);
mHelper = new InputDbHelper(this);
updateUI();
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = mEditText.getText().toString();
if (input.length() > 0) {
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, input);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
deleteTask();
adb.show();
}
});
}
public void deleteTask() {
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{});
db.close();
updateUI();
}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<String>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (adapter== null) {
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,
taskList);
mListView.setAdapter(adapter);
} else {
adapter.clear();
adapter.addAll(taskList);
adapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.example.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
You are not deleting the row in your database.You can do this
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete this note?");
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
db.delete(InputContract.TaskEntry.TABLE, InputContract.TaskEntry._ID + " = ?", new String[] { String.valueOf(positionToRemove)});
list.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
deleteTask();
adb.show();
}
});
try something like:
db.execSQL("DELETE FROM myTable WHERE noteID = 7")
Or more generally:
`int idToDelete = 7; //for example
db.execSQL(
"DELETE FROM "+ InputContract.TaskEntry.TABLE +
" WHERE "+ InputContract.TaskEntry._ID +" = " + idToDelete
)`

How to delete the selected items from the list in android

I have database and I display the contents in a list using the simple_list_item_checked layout. Now I want to delete items that the user chooses from that list. How can I do so?
this is the xml activity:
<ImageButton
android:id="#+id/ib_delete"
android:layout_width="40dp"
android:layout_height="40dp"
android:background="#drawable/delete"
android:layout_centerHorizontal="true"
android:layout_below="#+id/tv_page_mySpace2"
android:layout_marginTop="20dp"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/theuserideaslist"
android:background="#drawable/brain1"
android:layout_below="#id/ib_delete"
android:layout_marginTop="20dp"/>
and this is the remove method they told me to put it my open helper:
public void removeIedas (long id) {
String string = String.valueOf(id);
database.execSQL("DELETE FROM name WHERE _id = '" + string + "'");
}
and this is my java class for the activity:
final MyOpenHelper myOpenHelper = new MyOpenHelper( getApplicationContext());
final ListView theuserideaslist = (ListView) findViewById(R.id.theuserideaslist);
ArrayList<String> n ;
n = myOpenHelper.ShowTheUserIdeas();
final ArrayAdapter<String> myadapter = new ArrayAdapter<String> (getApplicationContext() , android.R.layout.simple_list_item_checked , n ) ;
theuserideaslist.setAdapter(myadapter);
theuserideaslist.setChoiceMode(2);
final ImageButton ib_delete = (ImageButton) findViewById(R.id.ib_delete);
theuserideaslist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, final long id) {
ib_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myOpenHelper.removeIedas(id); //create removemethod in database class
}
});
}
});
/* ib_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
theuserideaslist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ArrayList database = null;
myOpenHelper.removeIedas(id); //create removemethod in database class
}
});
}
});*/
what i want is: when i click on ib_delete delete the checked items.
And I am sorry, i am still new.
Thank You.
Use This:
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
database.remove(id); //Create a remove method in your database class
}
});
and in remove method:
public void remove(long id){
String string = String.valueOf(id);
database.execSQL("DELETE FROM favorite WHERE _id = '" + string + "'");
}
Collected from
this stackoverflow question
Update:
don't set onclick lister on the button, in fact you probably want to remove an item from list view when it is clicked.
Assuming that your listView is the id for ListView of your Activity,
Here:
myDBHelper is an object of class that extends SQLiteOpenHelper like
public class MyDBHelper extends SQLiteOpenHelper{
//codes..
public void DeleteFromDB(String d) {
SQLiteDatabase db = getWritableDatabase();
String dm = "\"" + d + "\"";
try {
db.execSQL("delete from " + db_table + " where taskName=" + dm);
} catch (SQLException e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
Then use this in main activity :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
myDBHelper.DeleteFromDB(arrayList.get(position));
}
});

Categories