Saving EditTexts on App close - java

on the homepage of my app i have edittexts that represent counters for each row in my list. whenever i change activity and return back to my main screen all the numbers disappear, the same happens when I close the app and open it again. How do i make the numbers stay?
My main activity where I call the row layout with the edittexts
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MyActivity extends Activity implements MyAdapterInterface{
private CustomCursorAdapter customAdapter;
public ListView list1;
//instantiating the database class
com.example.rory.dripdrop.DBAdapter db = new com.example.rory.dripdrop.DBAdapter(this);
public MyActivity mMyActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
mMyActivity = this;
//button and listener for add activity
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Add.class);
startActivity(i);
}
});
//button and listener for delete activity
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
//button and listener for update activity
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
public void onResume()
{
super.onResume();
//update list
addData();
}
//refreshes data base when main page is resumed
public void addData()
{
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
//chaning the running total
public void updateLitres(int value)
{
EditText editLitres = (EditText)findViewById(R.id.edit1);
//EditText myEditText2 = (EditText)findViewById(R.id.edit2);
editLitres.setText(String.valueOf(value));
//myEditText2.setText(String.valueOf(value));
}
public void updateCost(double value)
{
EditText editCost = (EditText)findViewById(R.id.edit2);
String.format("%.2f", value);
editCost.setText("€" + String.valueOf(value));
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
My custom adapter for the rows
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomCursorAdapter extends CursorAdapter {
//public int counter = 0;
public ArrayList<Integer> counter;
public ArrayList<Integer> counter2;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor cursor, MyAdapterInterface myInterface) {
//instantiating the values
super(context, cursor);
this.context = context;
this.mMyInterface = myInterface;
//array to sort each value per row
counter = new ArrayList<Integer>();
counter2 = new ArrayList<Integer>();
//default all counters to 0
for(int i=0; i<cursor.getCount(); i++)
{
counter.add(0);
counter2.add(0);
}
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, final Cursor cursor) {
//getting the first value for the custom row (the item name)
TextView textViewItemName = (TextView) view.findViewById(R.id.item1);
textViewItemName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final int litres = Integer.parseInt(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
//editText for custom row
final EditText runningTotal = (EditText) view.findViewById(R.id.runningTotal);
//setting up the plus button
final Button plusButton = (Button)view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
//cursor.getPosition() returns the position in the list
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2++;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
//setting up the minus button
final Button minusButton = (Button)view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos = 0;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2--;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
}
}

You should have a look here You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html, I used this and helped me get through it, You need to save each edit text that you want to save. and as for each row I would suggest making an array or loop for saving the edit boxes in the rows

didn't read your code bro, but answering in concern to your question title :
override onStop and save the data to Shared Preferences, its very easy to use:
//To save your data
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
//to extract your data in onCreate or whenever you feel like:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);

You will want to look into SharedPreferences, once you do you will basically be saving your values in SharedPreferences in an onPause() / onDestroy() method, and then in your onResume() / onCreate() methods you will retrieve the previously stored data
Edit: You can retrieve a string from an EditText in the following way
String toStore = EditText.getText().toString();
and then store it
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
so...
public void onPause(){
super.onPause();
String toStore = EditText.getText().toString();
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
}
public void onResume(){
super.onResume();
String toStore = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY", "defaultStringIfNothingFound");
EditText.setText(toStore);
}

You may use onSavedInstanceState and onRestoreInstanceState methods of activity !
So in onSavedInstanceState (called before your activity pauses) you may save your `EditText' values to the bundle,
And restore them back in onRestoreInstance state.
You can use the link by #Kaique for more reference,
and also this answer https://stackoverflow.com/a/16769864/826657 and all related answers here.

You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html

Related

issue in change row in recyclerview

I am working on a shopping Android app, I have a CartActivity. In my CartActivity I put RecyclerView and each row in this RecyclerView have 2 buttons, one (+) button to increase the quantity for this item in the cart and other (-) button to delete 1 from the quantity of this item in the row.
Now when I have a single item in my cart, everything is ok. but when I have multi-item in cart (multi-row in RV) I have the issue which is: When I press (+) or (-) button on any item in RecyclerView the effect of quantity changing shown on the last item in this list (last row) and there is no changing on my selected row!
this is my adapter code:
package com.example.souqsenae.adapters;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.souqsenae.API_Utility.IApi;
import com.example.souqsenae.API_Utility.RetrofitBuilder;
import com.example.souqsenae.R;
import com.example.souqsenae.activities.cartActivity;
import com.example.souqsenae.models.AddToCart;
import com.example.souqsenae.models.CartInfo;
import com.example.souqsenae.models.Parts;
import com.example.souqsenae.models.RemoveProduct;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CartAdapter extends
RecyclerView.Adapter<CartAdapter.CartAdapterViewHolder> {
private Context context;
private ArrayList<CartInfo.Item> mItem;
private ItemOnClickHandler mItemOnClickHandler;
RetrofitBuilder rB = new RetrofitBuilder();
IApi service = rB.retrofit.create(IApi.class);
int totalQty =0; int subTotal = 0;
TextView tv1, tv4;
private static SharedPreferences pref;
String cookie;
public CartAdapter(ItemOnClickHandler cartAdapterOnClickHandler, Context _context) {
mItemOnClickHandler = cartAdapterOnClickHandler;
pref = _context.getSharedPreferences("log", Context.MODE_PRIVATE);
}
public void setProductsData(ArrayList<CartInfo.Item> item) {
mItem = item;
notifyDataSetChanged();
}
public void addAll(ArrayList<CartInfo.Item> newList) {
int lastIndex = getItemCount();
mItem.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
}
public void clear() {
int size = mItem.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
mItem.remove(0);
}
notifyItemRangeRemoved(0, size);
}
}
#Override
public CartAdapter.CartAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.row_cart, parent, false);
// Return a new holder instance
CartAdapterViewHolder viewHolder = new CartAdapterViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(CartAdapter.CartAdapterViewHolder viewHolder, int position) {
// viewHolder.iv.setAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_transition_animation));
viewHolder.container.setAnimation(AnimationUtils.loadAnimation(context,R.anim.fade_transition_animation));
final CartInfo.Item cartInfo = mItem.get(position);
tv1 = viewHolder.qty;
TextView tv2 = viewHolder.tvItemName;
TextView tv3 = viewHolder.tvItemDesc;
tv4 = viewHolder.tvSubTotal;
Button button = viewHolder.btnMin;
Button button1 = viewHolder.btnPlus;
totalQty = cartInfo.getQty();
tv1.setText(String.valueOf(totalQty));
tv2.setText(cartInfo.getName());
tv4.setText(String.valueOf(cartInfo.getSubtotal()));
cookie = pref.getString("cookie", "");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if((totalQty -1) >0){
totalQty = totalQty -1;
tv1.setText(String.valueOf(totalQty));
subTotal = totalQty * (cartInfo.getPrice());
tv4.setText(String.valueOf(subTotal));
}
if((totalQty - 1) == 0){
// remove from cart:
String row = cartInfo.getRowid();
String product_id = cartInfo.getId();
Call<RemoveProduct> call = service.updateCartQty( cookie,product_id,totalQty);
call.enqueue(new Callback<RemoveProduct>() {
#Override
public void onResponse(Call<RemoveProduct> call, Response<RemoveProduct> response) {
if(response.isSuccessful()){
notifyDataSetChanged();
Intent intent = new Intent(context, cartActivity.class);
context.startActivity(intent);
}
}
#Override
public void onFailure(Call<RemoveProduct> call, Throwable t) {
}
});
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int vendor = Integer.parseInt(cartInfo.getVendor());
int product_id = Integer.parseInt(cartInfo.getId());
Call<AddToCart> call = service.addToCart(cookie,product_id,vendor,1);
call.enqueue(new Callback<AddToCart>() {
#Override
public void onResponse(Call<AddToCart> call, Response<AddToCart> response) {
if(response.isSuccessful()){
totalQty = totalQty +1;
tv1.setText(String.valueOf(totalQty));
subTotal = totalQty * (cartInfo.getPrice());
tv4.setText(String.valueOf(subTotal));
}
}
#Override
public void onFailure(Call<AddToCart> call, Throwable t) {
}
});
}
});
}
// Returns the total count of items in the list
#Override
public int getItemCount() {
if(mItem == null) {
return 0;
}
return mItem.size();
}
public class CartAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final Button btnPlus;
public final Button btnMin;
public final TextView qty;
public final TextView tvItemName;
public final TextView tvItemDesc;
public final TextView tvSubTotal;
public final LinearLayout container;
public CartAdapterViewHolder(View view) {
super(view);
qty = (TextView) view.findViewById(R.id.partCount);
tvItemName = (TextView) view.findViewById(R.id.tv_item_name);
tvItemDesc = (TextView) view.findViewById(R.id.tv_item_description);
tvSubTotal = (TextView) view.findViewById(R.id.tvSubTotal);
btnMin = (Button) view.findViewById(R.id.btnMin);
btnPlus = (Button) view.findViewById(R.id.btnPlus);
container = (LinearLayout) view.findViewById(R.id.layout_part_item);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
CartInfo.Item selectedProduct = mItem.get(position);
mItemOnClickHandler.onClickItem(selectedProduct);
}
}
public interface ItemOnClickHandler {
void onClickItem(CartInfo.Item cartInfo);
}
}
I don't know what the wrong :(
Thanks
Better to use interface to perform click operations.
Whenever button clicked, update the quantity for a specific item and call adapter.notifyDataSetChanged();.
You have to made change for quantity in your model when click + or - button. So you have to add cartInfo.setQty(totalQty); inside your button clicks
Don't use global variables if you are using variable inside onBind()
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if((totalQty -1) >0){
cartInfo.setQty(cartInfo.getQty() -1);
tv1.setText(String.valueOf(cartInfo.getQty()));
tv4.setText(String.valueOf(cartInfo.getQty() * (cartInfo.getPrice())));
}
if((totalQty - 1) == 0){
// remove from cart:
String row = cartInfo.getRowid();
String product_id = cartInfo.getId();
mItem.remove(cartInfo);
Call<RemoveProduct> call = service.updateCartQty( cookie,product_id,totalQty);
call.enqueue(new Callback<RemoveProduct>() {
#Override
public void onResponse(Call<RemoveProduct> call, Response<RemoveProduct> response) {
if(response.isSuccessful()){
notifyDataSetChanged();
Intent intent = new Intent(context, cartActivity.class);
context.startActivity(intent);
}
}
#Override
public void onFailure(Call<RemoveProduct> call, Throwable t) {
}
});
notifyDataSetChanged();
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int vendor = Integer.parseInt(cartInfo.getVendor());
int product_id = Integer.parseInt(cartInfo.getId());
cartInfo.setQty(cartInfo.getQty()+1);
cartInfo.setQty(cartInfo.getQty()+1);
tv1.setText(String.valueOf(cartInfo.getQty()));
tv4.setText(String.valueOf(cartInfo.getQty() * (cartInfo.getPrice())));
Call<AddToCart> call = service.addToCart(cookie,product_id,vendor,1);
call.enqueue(new Callback<AddToCart>() {
#Override
public void onResponse(Call<AddToCart> call, Response<AddToCart> response) {
if(response.isSuccessful()){
}
}
#Override
public void onFailure(Call<AddToCart> call, Throwable t) {
}
});
}
});

Why is getAdapterPosition() being stuck on the first view clicked every (say) 5 seconds?

I have a RecyclerView class (QuestionCardAdapter) that presents all the items of a SpanishQuestionSet as CardViews.
Everything had been working fine (for instance i could make it so when a card was clicked, 'tick' and 'cross' buttons would come up and would remove the card when clicked)
However recently I wanted the clicking of the buttons (vCross or VTick) to modify an array which is a part of the SpanishQuestionSet (i.e. the item in the array would be +1 for wrong and -1 for right so that the descending quicksort i use will cause questions answered incorrectly to be at the top).
However, whenever I say click 4 consecutive cards as wrong, instead of each card's score being increased by 1, the first card of the 4's score is increased by 4. It seems like getAdapterPosition() is delayed. Could it be affected by a time limit variable I added so that the app wouldnt crash if someone double clicked a button before the card remove animation had completed?
Any help would be appreciated and I will present below the adapter and SpanishQuestionSet classes.
The adapter class is most likely the focus.
package com.alexgower.odin_spanishpack;
import android.content.Context;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.util.List;
public class QuestionCardAdapter extends RecyclerView.Adapter<QuestionCardAdapter.QuestionCardViewHolder> {
private final Context context;
protected List<QuestionCardInfo> questionCardList;
private long mLastClickTime = 0;
private SpanishQuestionSet questionSet;
private int positionClicked;
private void setPositionClicked(int i){
this.positionClicked =i;
}
private int getPositionClicked(){
return this.positionClicked;
}
public QuestionCardAdapter(Context contextIn, List<QuestionCardInfo> questionCardList, SpanishQuestionSet questionSetIn) {
this.questionCardList = questionCardList;
this.context = contextIn;
this.questionSet = questionSetIn;
}
#Override
public int getItemCount() {
return questionCardList.size();
}
#Override
public void onBindViewHolder(QuestionCardViewHolder questionCardViewHolder, int i) {
QuestionCardInfo ci = questionCardList.get(i);
questionCardViewHolder.vQuestionAnswer.setText(String.valueOf(ci.score) + ci.question);
questionCardViewHolder.answer = ci.answer;
questionCardViewHolder.vTick.setVisibility(View.INVISIBLE);
questionCardViewHolder.vCross.setVisibility(View.INVISIBLE);
questionCardViewHolder.vColorTV.setBackgroundColor(questionSet.getColourForScore(context,ci.score));
}
#Override
public QuestionCardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.question_card_layout, viewGroup, false);
return new QuestionCardViewHolder(itemView);
}
public class QuestionCardViewHolder extends RecyclerView.ViewHolder {
public View view;
protected TextView vQuestionAnswer;
protected TextView vColorTV;
protected ImageView vTick;
protected ImageView vCross;
protected String answer = "Error";
public QuestionCardViewHolder(View v) {
super(v);
vColorTV = (TextView) v.findViewById(R.id.forNowColourTextView);
vQuestionAnswer = (TextView) v.findViewById(R.id.questionAnswerTextView);
vTick = (ImageView) v.findViewById(R.id.tickImage);
vCross = (ImageView) v.findViewById(R.id.crossImage);
view = v;
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vQuestionAnswer.setText(answer);
vTick.setVisibility(View.VISIBLE);
vCross.setVisibility(View.VISIBLE);
setPositionClicked(getAdapterPosition());
}
});
view = vTick;
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SystemClock.elapsedRealtime() - mLastClickTime > 1000) {
questionSet.questionRight(getPositionClicked(),context);
//questionSet.saveScores(context);
Toast.makeText(context, String.valueOf(questionSet.getScore(getPositionClicked())), Toast.LENGTH_LONG).show();
removeAt(getPositionClicked());
mLastClickTime = SystemClock.elapsedRealtime();
}
}
});
view = vCross;
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SystemClock.elapsedRealtime() - mLastClickTime > 1000) {
questionSet.questionWrong(getPositionClicked(),context);
Toast.makeText(context, String.valueOf(questionSet.getScore(getPositionClicked())), Toast.LENGTH_LONG).show();
removeAt(getPositionClicked());
mLastClickTime = SystemClock.elapsedRealtime();
}
}
});
}
}
public void testContext(int position) {
questionSet.testFile(position, context);
//String name = questionSet.getQuestion(position);
//try {
// context.openFileOutput("a.txt", Context.MODE_PRIVATE);
// Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//}catch(FileNotFoundException e){
// Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
//}
}
public void removeAt(int position) {
questionCardList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, questionCardList.size());
}
SpanishQuestionSet class
package com.alexgower.odin_spanishpack;
import android.content.Context;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.util.List;
public class QuestionCardAdapter extends RecyclerView.Adapter<QuestionCardAdapter.QuestionCardViewHolder> {
private final Context context;
protected List<QuestionCardInfo> questionCardList;
private long mLastClickTime = 0;
private SpanishQuestionSet questionSet;
private int positionClicked;
private void setPositionClicked(int i){
this.positionClicked =i;
}
private int getPositionClicked(){
return this.positionClicked;
}
public QuestionCardAdapter(Context contextIn, List<QuestionCardInfo> questionCardList, SpanishQuestionSet questionSetIn) {
this.questionCardList = questionCardList;
this.context = contextIn;
this.questionSet = questionSetIn;
}
#Override
public int getItemCount() {
return questionCardList.size();
}
#Override
public void onBindViewHolder(QuestionCardViewHolder questionCardViewHolder, int i) {
QuestionCardInfo ci = questionCardList.get(i);
questionCardViewHolder.vQuestionAnswer.setText(String.valueOf(ci.score) + ci.question);
questionCardViewHolder.answer = ci.answer;
questionCardViewHolder.vTick.setVisibility(View.INVISIBLE);
questionCardViewHolder.vCross.setVisibility(View.INVISIBLE);
questionCardViewHolder.vColorTV.setBackgroundColor(questionSet.getColourForScore(context,ci.score));
}
#Override
public QuestionCardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.question_card_layout, viewGroup, false);
return new QuestionCardViewHolder(itemView);
}
public class QuestionCardViewHolder extends RecyclerView.ViewHolder {
public View view;
protected TextView vQuestionAnswer;
protected TextView vColorTV;
protected ImageView vTick;
protected ImageView vCross;
protected String answer = "Error";
public QuestionCardViewHolder(View v) {
super(v);
vColorTV = (TextView) v.findViewById(R.id.forNowColourTextView);
vQuestionAnswer = (TextView) v.findViewById(R.id.questionAnswerTextView);
vTick = (ImageView) v.findViewById(R.id.tickImage);
vCross = (ImageView) v.findViewById(R.id.crossImage);
view = v;
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vQuestionAnswer.setText(answer);
vTick.setVisibility(View.VISIBLE);
vCross.setVisibility(View.VISIBLE);
setPositionClicked(getAdapterPosition());
}
});
view = vTick;
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SystemClock.elapsedRealtime() - mLastClickTime > 1000) {
questionSet.questionRight(getPositionClicked(),context);
//questionSet.saveScores(context);
Toast.makeText(context, String.valueOf(questionSet.getScore(getPositionClicked())), Toast.LENGTH_LONG).show();
removeAt(getPositionClicked());
mLastClickTime = SystemClock.elapsedRealtime();
}
}
});
view = vCross;
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SystemClock.elapsedRealtime() - mLastClickTime > 1000) {
questionSet.questionWrong(getPositionClicked(),context);
Toast.makeText(context, String.valueOf(questionSet.getScore(getPositionClicked())), Toast.LENGTH_LONG).show();
removeAt(getPositionClicked());
mLastClickTime = SystemClock.elapsedRealtime();
}
}
});
}
}
public void testContext(int position) {
questionSet.testFile(position, context);
//String name = questionSet.getQuestion(position);
//try {
// context.openFileOutput("a.txt", Context.MODE_PRIVATE);
// Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
//}catch(FileNotFoundException e){
// Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
//}
}
public void removeAt(int position) {
questionCardList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, questionCardList.size());
}
}
Turns out it is quite easy. For anyone in the future with a similar problem, note that getAdapterView() simply returns the integer of a views position in the viewholder so when a view is removed, the next view takes its position.
i.e. if you have views 1,2,3,4,5. When you remove 2, 3 becomes 2 and 4 becomes 3 etc. Alternative explanation: whichever is the 5th view on the screen will have position 5, even if 10000 other items before it have been removed (it will not be position 10005).
So it was not a problem with getAdapterPostion(). To fix the problem I used a variable for an itemID for each view in the recyclerview and did not use getAdapterPosition() except for in the removeAt() method.

RecycleView Wont update

I'm still new with both Java and android
My problem is that the recycleview only gets updated and adds the new added tag if I closed the app and run it again. How can I get the app to update the recycle view instantly to display the new tags.
java code
package com.deitel.favoritesites;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String SITES="Sites";
private EditText urlEditText; //where user enters the URL
private EditText tagEditText;
private FloatingActionButton saveFloatingActionButton;
private SharedPreferences savedSites;
private List<String> tags;
private SitesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
urlEditText = ((TextInputLayout) findViewById(
R.id.URLTextInputLayout)).getEditText();
urlEditText.addTextChangedListener(textWatcher);
tagEditText=((TextInputLayout)findViewById(R.id.tagTextInputLayout)).getEditText();
tagEditText.addTextChangedListener(textWatcher);
//get the shared prefrences containing the user saved URLs
savedSites = getSharedPreferences(SITES, MODE_PRIVATE);
//get the shared tags in an ArrayList then sort them
tags = new ArrayList<>(savedSites.getAll().keySet());
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
//get reference to the recycle to configure it
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//use a linerlayout to display items in a vertical list
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//create recyclerView.Adopter to bind tags to the RecyclerView
adapter = new SitesAdapter(tags, itemClickListener, itemLongClickListener);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new ItemDivider(this));
//register listner to save a new or edit search
saveFloatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
saveFloatingActionButton.setOnClickListener(saveButtonListener);
updateSaveFAB();
}
private final TextWatcher textWatcher= new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateSaveFAB();
}
#Override
public void afterTextChanged(Editable s) {
}
};
//show or hide the saveFloatingActionButton
private void updateSaveFAB() {
//check if there is input in both EditButton
if (urlEditText.getText().toString().isEmpty() || tagEditText.getText().toString().isEmpty())
saveFloatingActionButton.hide();
else
saveFloatingActionButton.show();
}
//saveButtonListener save a tag query pair into sharedPrefrece
private final OnClickListener saveButtonListener=new OnClickListener() {
#Override
public void onClick(View view) {
String query = urlEditText.getText().toString();
String tag = tagEditText.getText().toString();
if (!query.isEmpty() && !tag.isEmpty()) {
//hide the virtual keyboard
((InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(),0);
addTaggedSites(tag, query);//add/update the search
urlEditText.setText("");//Clear queryEditText
tagEditText.setText("");//clear tagEditText
urlEditText.requestFocus();
}
}
};
//add new search to file then refresh all button
private void addTaggedSites(String tag, String query) {
//get a sharedprefrence editor to store new tag/query pair
SharedPreferences.Editor preferencesEditor = savedSites.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
//if tag is new> add and sort tags then display update
if (!tag.contains(tag)) {
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
//itemClickListener launches web broswer to display search results
private final OnClickListener itemClickListener=new OnClickListener() {
#Override
public void onClick(View view) {
//get query string and create a URL represeting the search
String tag= ((TextView) view).getText().toString();
String urlString=getString(R.string.search_URL)+Uri.encode(savedSites.getString(tag,""),"UTF-8");
//create an intent to lanuch a web broswer
Intent webIntent= new Intent(Intent.ACTION_VIEW,Uri.parse(urlString));
startActivity(webIntent);
}
};
//itemLongClickListener displays a dialog allowing the user to share edit or delete a saved search
private final OnLongClickListener itemLongClickListener= new OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
//get the tag that the user long touched
final String tag = ((TextView) view).getText().toString();
//creatw a new AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//set the alertDialog title
builder.setTitle(getString(R.string.share_edit_delete_title, tag));
//set list of items to display and create event handler
builder.setItems(R.array.dialog_items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0://share
shareSites(tag);
break;
case 1://edit
tagEditText.setText(tag);
urlEditText.setText(savedSites.getString(tag, ""));
break;
case 2: //delete
deleteSites(tag);
break;
}
}
}
);
//set the alertDialog negetive button
builder.setNegativeButton(getString(R.string.cancel), null);
builder.create().show();//display the alert dialog
return true;
}
};
//allow user to choose app for sharing URL of a saved search
private void shareSites(String tag){
//create the URL representing the search
String urlString= getString(R.string.search_URL)+Uri.encode(savedSites.getString(tag, ""), "UTF-8");
//create an intent to share urlString
Intent shareIntent= new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
shareIntent.putExtra(Intent.EXTRA_TEXT,getString(R.string.share_message,urlString));
shareIntent.setType("text/plain");
//display app that can share plain text
startActivity(Intent.createChooser(shareIntent,getString(R.string.share_search)));
}
//delete search after user confirms
private void deleteSites(final String tag){
//create a new AlertDialog and set its message
AlertDialog.Builder confirmBuilder= new AlertDialog.Builder(this);
confirmBuilder.setMessage(getString(R.string.confirm_message, tag));
//cancel button configration
confirmBuilder.setNegativeButton(getString(R.string.cancel), null);
//positive DELETE button
confirmBuilder.setPositiveButton(getString(R.string.delete),new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog , int id){
tags.remove(tag);
//remove sharedPerefrences.Editor from Sharedprefrences
SharedPreferences.Editor preferenceEditor= savedSites.edit();
preferenceEditor.remove(tag);
preferenceEditor.apply();
adapter.notifyDataSetChanged();
}
}
);
confirmBuilder.create().show();
}
}
This is my adopter code
package com.deitel.favoritesites;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class SitesAdapter extends RecyclerView.Adapter<SitesAdapter.ViewHolder> {
private final View.OnClickListener clickListener;
private final View.OnLongClickListener longClickListener;
private final List<String> tags;
public SitesAdapter(List<String> tags, View.OnClickListener clickListener, View.OnLongClickListener longClickListener) {
this.tags = tags;
this.clickListener = clickListener;
this.longClickListener = longClickListener;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView textView;
public ViewHolder(View itemView, View.OnClickListener clickListener, View.OnLongClickListener longClickListener) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(clickListener);
itemView.setOnLongClickListener(longClickListener);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return (new ViewHolder(view, clickListener, longClickListener));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(tags.get(position));
}
#Override
public int getItemCount() {
return tags.size();
}
}
Change your code into this
if (!tags.contains(tag)) {
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
Because, this below condition is always false
if(!tag.contains(tag))
Its because you are checking if a value contains in that value itself. SO it will be always true.
If you are checking the tag exist in the List<String> tags you should do like this below.
if(!tags.contains(tag))
change your code to....
//add new search to file then refresh all button
private void addTaggedSites(String tag, String query) {
//get a sharedprefrence editor to store new tag/query pair
SharedPreferences.Editor preferencesEditor = savedSites.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
//if tag is new> add and sort tags then display update
if (!this.tag.contains(tag)) {
this.tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
This may help:
create a setter method within your adapter allowing you to set/update the adapter ArrayList.
Whenever you make a change to your list i.e. remove Tag, pass this updated list to your adapter via your new setter method.
call notifyDataSetChanged().

Changing a EditText depending on listView Click

Hi guys I am looking for a bit of help and advise with my app, At the moment I have a custom adapter printing out each row, in each row it prints two buttons, one button to increment and one button to decrement. What I want to happen is for when a button is clicked a editText(totalCost) outside the listView changes. I have no idea how to go about doing this as I am pretty new to android and java, so any help will be great. Thanks
The custom adapter that I am using is
package com.example.rory.dbtest;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.pinchtapzoom.R;
public class CustomCursorAdapter extends CursorAdapter{
public int counter = 0;
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final EditText edit1 = (EditText) view.findViewById(R.id.runningTotal);
Button plusButton = (Button) view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
edit1.setText(Integer.toString(counter));
}
});
Button minusButton = (Button) view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter--;
edit1.setText(Integer.toString(counter));
}
});
}
}
This is the main activity where I want the editText(TotalCost) to change depending on the click
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.pinchtapzoom.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
public ListView list1;
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
public EditText TotalCost;
//public EditText TotalLitres;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Handler().post(new Runnable() {
#Override
public void run() {
//Log.d("test", "customadapter is " + customAdapter.toString());
//Log.d("test", "databaseHelper is " + databaseHelper.toString());
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords());
list1.setAdapter(customAdapter);
}
});
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
And the XML file for the adapter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="30sp"
android:paddingBottom="5dp"/>
<Button
android:id="#+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/plusButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/runningTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/minusButton"
android:layout_toStartOf="#+id/minusButton"
android:layout_marginRight="30dp" />
<Button
android:id="#+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/minusButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
You should use an Interface
1) create an interface class:
public interface MyAdapterInterface {
public void updateEditText(String value);
}
2) change your adapter to:
public class CustomCursorAdapter extends CursorAdapter{
public int counter = 0;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor c, MyAdapterInterface myInterface) {
super(context, c);
this.context = context;
this.mMyInterface = myInterface;
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final EditText edit1 = (EditText) view.findViewById(R.id.runningTotal);
Button plusButton = (Button) view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(/*YOUR VALUE*/);
}
});
Button minusButton = (Button) view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter--;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(/*YOUR VALUE*/);
}
});
}
}
3) implement the interface in your activity:
public class MyActivity extends Activity implements MyAdapterInterface {
private CustomCursorAdapter customAdapter;
public ListView list1;
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
public EditText TotalCost;
//public EditText TotalLitres;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Handler().post(new Runnable() {
#Override
public void run() {
//Log.d("test", "customadapter is " + customAdapter.toString());
//Log.d("test", "databaseHelper is " + databaseHelper.toString());
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), this);
list1.setAdapter(customAdapter);
}
});
#Override
public void updateEditText(String value) {
EditText myEditText = (EditText)findViewById(R.id./*YOUR EDITTEXT ID*/);
myEditText.setText(value);
}
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}

Start an activity from a listview with searchbox

Im having trouble with my listview and search box. Searching works fine, except for the fact that it is case sensitive. However, my problem is, starting an activity right after clicking.
The start activity is based on the position of the text. Therefore, if I dont conduct any research the links work fine. Yet, if i research for specifics the listview works but the links are wrong, because they are based on the initial position of the listview and not sorted by categories.
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import greendroid.widget.NormalActionBarItem;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class m_m_aeritalia extends GDActivity {
EditText edittext;
ListView listview;
Button search;
String[] text = { "(Lockheed) F-104S Starfighter",
"Aermecchi / EMBRAER AMX", "G-222" };
int[] image = { R.drawable.tf1, R.drawable.tf7, R.drawable.ts26 };
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setActionBarContentView(R.layout.m_listgeneral);
addActionBarItem(
getActionBar().newActionBarItem(NormalActionBarItem.class)
.setDrawable(R.drawable.ic_title_back),
R.id.action_bar_back);
edittext = (EditText) findViewById(R.id.EditText01);
listview = (ListView) findViewById(R.id.ListView01);
listview.setAdapter(new MyCustomAdapter(text, image));
listview.setClickable(true);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if ("(Lockheed) F-104S Starfighter".equals(text[position])) {
// code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(),
mcomingsoon.class);
startActivityForResult(myIntent, 0);
}
if ("Aermecchi / EMBRAER AMX".equals(text[position])) {
// code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(),
mcomingsoon.class);
startActivityForResult(myIntent, 0);
}
if ("G-222".equals(text[position])) {
// code specific to 2nd list item
Intent myIntent = new Intent(view.getContext(),
fa_f4.class);
startActivityForResult(myIntent, 0);
}
}
});
edittext.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
for (int i = 0; i < text.length; i++) {
if (textlength <= text[i].length()) {
if (text[i].indexOf(edittext.getText().toString()) != -1) {
text_sort.add(text[i]);
image_sort.add(image[i]);
}
}
}
listview.setAdapter(new MyCustomAdapter(text_sort, image_sort));
}
});
}
class MyCustomAdapter extends BaseAdapter {
String[] data_text;
int[] data_image;
MyCustomAdapter() {
}
MyCustomAdapter(String[] text, int[] image) {
data_text = text;
data_image = image;
}
MyCustomAdapter(ArrayList<String> text, ArrayList<Integer> image) {
data_text = new String[text.size()];
data_image = new int[image.size()];
for (int i = 0; i < text.size(); i++) {
data_text[i] = text.get(i);
data_image[i] = image.get(i);
}
}
public int getCount() {
return data_text.length;
}
public String getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.listview, parent, false);
TextView textview = (TextView) row.findViewById(R.id.TextView01);
ImageView imageview = (ImageView) row
.findViewById(R.id.ImageView01);
textview.setText(data_text[position]);
imageview.setImageResource(data_image[position]);
return (row);
}
}
#Override
public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
switch (item.getItemId()) {
case R.id.action_bar_back:
startActivity(new Intent(this, mbymanufacturers.class));
break;
}
return true;
}
Hope I made myself clear,
Any suggestions?
Thank You
Tiberio Bozotti
You shouldn't query the String array directy, but get the item from the Adapter.
Try this...
Create a custom private class to hold the String and integer value pair, such as:
private class DataPair { String text; int value; }
Then, instead of using your MyCustomAdapter, create an ArrayList of DataPair objects and assign it to an ArrayAdapter, such as:
new ArrayAdapter<DataPair>(this, R.layout.ListView01, new ArrayList<DataPair>);
Now, for getting your data, you only have to do:
getItem(position).text
or
getItem(position).value
In case of the setOnItemClickListener use:
((DataPair)listview.getAdapter().getItem(position)).text

Categories