Android currently index from the arrayList try to update - java

ArrayList < Titles > atitlename;
ArrayList < Items > aitems;
static int currentListIndex = 0, currentItemIndex = 0;
public void onClick(View button)
{
switch (button.getId())
case R.id.button_update: {
int id = aitems.get(currentListIndex).getItemId();
String newContent = etupdateName.getText().toString();
etupdateName.setText("");
ContentValues values = new ContentValues();
values.put(DBManager.C_ITEM_NAME, newContent);
try {
database = manager.getWritableDatabase();
database.update(DBManager.TABLE_ITEMS, values, DBManager.C_ID + "=" + id, null);
Toast.makeText(this, "you saved: " + newContent, Toast.LENGTH_LONG).show();
database.close();
refreshitem();
} catch (Exception e) {
Log.d(TAG, "Error" + e);
Toast.makeText(this, "error" + e, Toast.LENGTH_LONG).show();
}
break;
}
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
String name = (aitems.get(position).getItemName());
etupdateName.setText(name);
}
try to get the currentListindex from the ArrayList to the id, I set the currentListIndex = 0, cause I don't know how to get the current index, I got the int from the OnItemClick because it passes the int Position from the method, But i can't pass the int Position from the Onclick method.
I want the id = whatever I Click the item from the listview.
When I click the Item in the listview where id = 2, and I try to update it, it always updates the item where index = 0(becasue i set the currentItemIndex= 0).
what I want is to update the item's id = whatever I click the item from the listview which I have done it by using the int Position from the OnItemClick method.
Example:
I click the item from the listview where id = 3, it displays the item name in the EditText Box, then I want to update the item name, it will update the item name where id =3.

Related

indexOf() returns -1

I'm trying to replace an item in my recycler view and for that I need to get the index of an object(recipe) inside a list in SQLite database and it returns -1.Any idea??.
private void editRecipe(Intent data) {
if (data.hasExtra(Recipe.RECIPE_KEY) && data.hasExtra(Recipe.RECIPE_NAME)&& data.hasExtra(Recipe.RECIPE_DESCRIPTION)&& data.hasExtra(Recipe.RECIPE_DIFFICULTY))
{
Recipe recipe = (Recipe) data.getSerializableExtra(Recipe.RECIPE_KEY);
Long id = data.getExtras().getLong(Recipe.RECIPE_ID);
String name = (String) data.getExtras().get(Recipe.RECIPE_NAME);
String description = (String) data.getExtras().get(Recipe.RECIPE_DESCRIPTION);
int difficulty = (int) data.getExtras().get(Recipe.RECIPE_DIFFICULTY);
//find the recipe in the list
//Boolean result= recipeDataService.update(recipe);
int position = adapter.getRecipes().indexOf(recipe);
if(position >= 0){
//recipe was found
recipe = recipeDataService.getRecipe(id);
Boolean result= recipeDataService.update(recipe);
adapter.replaceItem(position, recipe);
}
}
} }
ยดยดยด

IndexOutOfBoundException when i pass arraylist to DBHelper to update database (Android SQlite)

I am new at android and trying to make managing members app with database. what i want to do here is that when user buys any drink it should change drinks name to "bought" in database, but when i pass Arraylist to db class it shows that my Arraylist is empty.
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.shashank.managemembers.DB_Controller.update_available(DB_Controller.java:88)
at com.shashank.managemembers.TempActivity$2.onClick(TempActivity.java:90)
userInputActivity
here user selects drink he/she wants and when he presses done button it should change database with drinks name.
And I'm checking it with Toast message that ArrayList is not empty. Toast message always appears with user's choice but db class throws error.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TempActivity.this, selectedInListView.get(0), Toast.LENGTH_SHORT).show();
dbController.update_available(code, selectedInListView);
onBackPressed();
}
});
here selectedInListView has many items when i am passing it to dbController.update_available.
dbController.java
here I have 9 columns in db starting from DRINK1 to DRINK9.
public void update_available(String memberCode, ArrayList<String> BoughtDrinks) {
Cursor cursor = this.getReadableDatabase().rawQuery("SELECT * FROM MEMBERS WHERE MEMBERCODE = '" + memberCode + "'", null);
int count = cursor.getColumnCount();
while (cursor.moveToNext()) {
for (int i = 5; i < count; i++) {
if (!cursor.getString(i).contains(BoughtDrinks.get(0))) {
this.getReadableDatabase().execSQL("UPDATE MEMBERS SET DRINK"+ i +"='Bought' WHERE DRINK" + i +"='" + BoughtDrinks.get(0) + "'" + "AND MEMBERCODE='" + memberCode + "'");
if(BoughtDrinks.size() > 0 ){
BoughtDrinks.remove(0);
}
}
}
}
cursor.close();
}
I am not understanding why it is throwing an error when I'm passing ArrayList with elements.
You got this error because ,if BoughtDrinks.size()>0 ,your code remove item at 0 then for loop get item at 0.So when you try to get item at 0 after you removed all the item ,you will get index IndexOutOfBoundsException.to avoid that just add if() condition.
public void update_available(String memberCode, ArrayList<String> BoughtDrinks) {
Cursor cursor = this.getReadableDatabase().rawQuery("SELECT * FROM MEMBERS WHERE MEMBERCODE = '" + memberCode + "'", null);
int count = cursor.getColumnCount();
while (cursor.moveToNext()) {
for (int i = 5; i < count; i++) {
if ( BoughtDrinks.size()>0 && !cursor.getString(i).contains(BoughtDrinks.get(0))) {
this.getReadableDatabase().execSQL("UPDATE MEMBERS SET DRINK"+ i +"='Bought' WHERE DRINK" + i +"='" + BoughtDrinks.get(0) + "'" + "AND MEMBERCODE='" + memberCode + "'");
if(BoughtDrinks.size() > 0 ){
BoughtDrinks.remove(0);
}
}
}
}
cursor.close();
}

Remove Item From Listview using SQLite

I have a strange problem in my ListView and I don't understand why it happens.
In my checklist when I select 3 or more items only last and first Item are deleted the second item is not deleted. It just remains selected and I need to click this post button again.
SendDataFragment Activity
btn_DataSend=(Button) getActivity().findViewById(R.id.trn_post_btn);
btn_DataSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
//get All info like custID, mStatus mTrnNo mCustID mCustName
List<customerInfo> stateList = adapter.mCategories;
for(int i=0;i<stateList.size();i++)
{
customerInfo state = stateList.get(i);
if(state.ismStatus())
{
//postData(state.getmTrnNo());
int c = i;
dbManager.delete_ShipmentDetails(state.getmCustID());
stateList.remove(i);
}
}
adapter.notifyDataSetChanged();
Toast.makeText(getActivity(), responseText, Toast.LENGTH_LONG).sho();
}
});
DBManager
public void delete_ShipmentDetails(String id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
db.execSQL("delete from "+ DatabaseHelper.TBL_OE_SHIPMENT_H +" WHERE " +DatabaseHelper.OE_SHIPMENT_H_CUSTID+"="+id);
}
My App screen-shots are:
Use loop in reverse order
for(int i = stateList.size()-1; i >= 0; i--){
customerInfo state = stateList.get(i);
if(state.ismStatus())
{
//postData(state.getmTrnNo());
int c = i;
dbManager.delete_ShipmentDetails(state.getmCustID());
stateList.remove(i);
notifyItemRemoved(i);
}
}
adapter.notifyDataSetChanged();
This is because you are looping through a list whilst changing the length of it.
There are several methods to solve this problem, either loop through the list backwards, use an iterator or save the deletions until the end. In order to change the loop to use an iterator the following should work as expected:
Iterator<Integer> it = stateList.iterator();
while (it.hasNext()) {
customerInfo state = it.next();
if(state.ismStatus()) {
dbManager.delete_ShipmentDetails(state.getmCustID());
it.remove();
}
}
adapter.notifyDataSetChanged();
Now I Get It Clearly I have also made another Way Just Change here like
for(int i=0;i<stateList.size();i++)
{
customerInfo state = stateList.get(i);
if(state.ismStatus())
{
postData(state.getmTrnNo());
dbManager.delete_ShipmentDetails(state.getmCustID());
stateList.remove(i);
i--;
}
}
adapter.notifyDataSetChanged();
});

Change the underline/style of EditText.....not the link, and scroll the text horizontally

I have created my own custom keyboard using buttons. I was tired of Android's keyboard popping up and taking up half the screen. My keyboard
is part of the Activity's layout. I have 2 EditTexts set to not-focusable to prevent the Android keyboard from popping up and make the EditTexts read-only. When I select buttons on my keyboard, the values of the buttons' text is displayed in the EditText field that I have assigned as focused (I do this using onTouch and setting a flag/boolean). If the flag mIsNameSelected = true, then the name EditText is considered focused, otherwise the email EditText is considered focused. Here's my dilemma;
First side-effect of this implementation is that when my text is longer than the space allotted to the EditText field, the text disappears to the right. I want to ellipsize the beginning as if the EditText was functioning normally but I think by setting it to isFocusable(false) I have eliminated it's ability to do this. Is there a work-around?
Second, to add a visual cue that the user has selected one of the EditTexts, I want to change the color of the underline on the EditText, not the text-link. The text link doesn't show up because the of the not-focusable attribute setting. I know there must be a way to change the EditText's style programmatically, which is what I'm looking for.
Here is a diagram:
The buttons call the type() method in XML
And here are the relevant methods (type() is called in XML):
public void setActivteListener(final EditText et) {
et.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int result = event.getAction();
if (result == MotionEvent.ACTION_DOWN) {
if (et.getId() == R.id.et_customer_name) {
Log.d(TAG, "here on customer name");
mIsNameSelected = true;
updateUI();
} else if (et.getId() == R.id.et_customer_email) {
Log.d(TAG, "here on customer email");
mIsNameSelected = false;
updateUI();
}
}
return true;
}
});
}
public void type(View view) {
Log.d(TAG, "type method called");
Button btn = (Button) view;
String txt = btn.getText().toString();
char value = txt.charAt(0);
if (mIsNameSelected) {
if (mCustomerName.getText().length() > 0) {
if (txt.equalsIgnoreCase("back")) {
char[] text = mCustomerName.getText().toString().toCharArray();
char[] temp = Arrays.copyOfRange(text, 0, text.length - 1);
mCustomerName.setText(String.valueOf(temp));
}
}
if (txt.equalsIgnoreCase("space")) {
char[] text = mCustomerName.getText().toString().toCharArray();
Log.d(TAG, "the value of text now : " + String.valueOf(text));
char[] temp = Arrays.copyOf(text, text.length + 1);
Log.d(TAG, "the value of temp now: " + String.valueOf(temp));
temp[temp.length - 1] = ' ';
Log.d(TAG, "temp to string: " + String.valueOf(temp));
mCustomerName.setText(String.valueOf(temp));
}
if (!(txt.equalsIgnoreCase("back") || txt.equalsIgnoreCase("space"))) {
char[] text = mCustomerName.getText().toString().toCharArray();
char[] temp = Arrays.copyOf(text, text.length + 1);
temp[temp.length - 1] = value;
mCustomerName.setText(String.valueOf(temp));
}
} else {
Log.d(TAG, "the length of the et field is : " + mCustomerName.getText().length());
if (mCustomerEmail.getText().length() > 0) {
Log.d(TAG, "the text is longer than 0");
if (txt.equalsIgnoreCase("back")) {
Log.d(TAG, "the text = back ");
char[] text = mCustomerEmail.getText().toString().toCharArray();
char[] temp = Arrays.copyOfRange(text, 0, text.length - 1);
mCustomerEmail.setText(String.valueOf(temp));
}
}
if (txt.equalsIgnoreCase("space")) {
char[] text = mCustomerEmail.getText().toString().toCharArray();
Log.d(TAG, "the value of text now : " + String.valueOf(text));
char[] temp = Arrays.copyOf(text, text.length + 1);
Log.d(TAG, "the value of temp now: " + String.valueOf(temp));
temp[temp.length - 1] = ' ';
Log.d(TAG, "temp to string: " + String.valueOf(temp));
mCustomerEmail.setText(String.valueOf(temp));
}
if (!(txt.equalsIgnoreCase("back") || txt.equalsIgnoreCase("space"))) {
char[] text = mCustomerEmail.getText().toString().toCharArray();
char[] temp = Arrays.copyOf(text, text.length + 1);
temp[temp.length - 1] = value;
mCustomerEmail.setText(String.valueOf(temp));
}
}
}
Set
android:windowSoftInputMode="stateAlwaysHidden"
in the activity xml of your manifest. You can have your views as focusable without the keyboard popping up then.
https://developer.android.com/guide/topics/manifest/activity-element.html

get unchecked and checked values from a checkbox

I'm trying to print the contents of my checkbox list. I'd like to display all the unchecked (false values) and checked (true values) in the order that it appears in the list view. So far I can only get the true values, how can I get the unchecked false values?
public void selection (){
final ListView lv = (ListView)findViewById(R.id.treeQuestionsList);
Intent intent = getIntent();
int id2 = intent.getIntExtra("id2", 0);
SparseBooleanArray checked = lv.getCheckedItemPositions();
int size = checked.size();
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
entries.add(new Observation(id2,lv.getCheckedItemPositions().get(key)));
Log.d(Constants.TAG,"--ID:="+id2+"--checkeddata----"+ entries.get(i).answers);
}
}
From the documentation available on Android Developers, you might need to use a combination of the value along with the key in order to get the desired result.
for (int i=0; i < checked.size(); i++) {
if (checked.valueAt(i)) {
int key = checked.keyAt(i);
Log.i(TAG, key + " is selected");
} else {
int key = checked.keyAt(i);
Log.i(TAG, key + " is not selected");
}
}
You can also take a look at what getCheckedItemPositions() does.

Categories

Resources