Dynamically change the status of a ProgressBar based on two TextFields - java

I'm trying to change the status of a ProgressBar while the user is typing a text on either text fields.
For example , the user starts typing on the first TextView, the ProgressBar should change it's value, if he deletes the text, it should reset to the previous value which is 30
package com.example.phill.jokes;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Entry extends AppCompatActivity {
private ProgressBar pr;
private Handler rHandler = new Handler();
private TextView tv ;
private TextView tv2 ;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
pr = (ProgressBar) findViewById(R.id.progressBar);
tv=(TextView) findViewById(R.id.textView9) ;
tv2=(TextView) findViewById(R.id.textView6) ;
new Thread(new Runnable() {
#Override
public void run() {
while (true)
{
android.os.SystemClock.sleep(300);
rHandler.post(new Runnable() {
#Override
public void run() {
pr.setProgress(30);
if(tv.getText().toString().matches(""))
{
titleboolean=true;
}
else
titleboolean=false;
if(tv2.getText().toString().matches(""))
{
jokeboolean=true;
}
else
jokeboolean=false;
if(titleboolean)
{
pr.setProgress(60);
}
if(jokeboolean)
{
pr.setProgress(100);
}
}
});
if(titleboolean && jokeboolean)
break;
}
rHandler.post(new Runnable() {
#Override
public void run() {
if(titleboolean && jokeboolean){
tv2.setVisibility(View.INVISIBLE);
tv.setVisibility(View.VISIBLE);
}
;
}
});
}
}).start();
}
}
The value of the ProgressBar never changes.
Any Ideas?

Let me explain you in detail
if(titleboolean && jokeboolean)
break;
when your both text fields clears it calls break statement after that your thread stops running you can achieve this in another way
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ProgressBar;
import android.widget.TextView;
public class TestActivity extends AppCompatActivity
{
private ProgressBar pr;
private EditText tv;
private EditText tv2;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
pr=(ProgressBar)findViewById(R.id.progressBar);
tv = (EditText) findViewById(R.id.tv);
tv2 = (EditText) findViewById(R.id.tv2);
TextView tV = new TextView(this);
tV.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
tv2.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
}
public void setProgress() {
pr.setProgress(30);
if (tv.getText().toString().matches("")) {
titleboolean = true;
} else
titleboolean = false;
if (tv2.getText().toString().matches("")) {
jokeboolean = true;
} else
jokeboolean = false;
if (titleboolean) {
pr.setProgress(60);
}
if (jokeboolean) {
pr.setProgress(100);
}
}
}

Use EditText instead TextView with TextChangedListener.
TextView does not allow to type text.
Also infinite cycle with pauses is bad approach, use EditText.addTextChangedListener to handle text after it have changed

Related

Button inside RecyclerView

I have a problem with my android app.
I have a RecyclerView and a click handler for it. When you click on a list item, one of the class fields is displayed on the screen. Also inside there is a button, by clicking on which another class field should be displayed. But the program throws a NullPointerException. I understand why this is happening, but I cannot understand how to modify my code, please help.
here is my Adapeter
package com.skorbr.stock_yandextest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class TickerAdapter extends RecyclerView.Adapter<TickerAdapter.TickerViewHolder> {
private List<Ticker> tickers;
private Context context;
// listener
private final Listener onTickerClickListener;
// constructor
public TickerAdapter(List<Ticker> tickers, Listener onTickerClickListener) {
this.tickers = tickers;
this.onTickerClickListener = onTickerClickListener;
}
#NonNull
#Override
public TickerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view = LayoutInflater.from(context).inflate(R.layout.recycler_stock_item, parent, false);
// click on RecyclerView
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onTickerClick((Ticker) v.getTag());
}
});
// click on button
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
}
});
return new TickerViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
}
#Override
public int getItemCount() {
return tickers.size();
}
class TickerViewHolder extends RecyclerView.ViewHolder {
private TextView ticker;
private TextView tickerFull;
private TextView price;
private TextView priceChange;
private ImageView tickerLogo;
private Button favouriteButton;
public TickerViewHolder(#NonNull final View itemView) {
super(itemView);
ticker = itemView.findViewById(R.id.ticker);
tickerFull = itemView.findViewById(R.id.ticker_full);
price = itemView.findViewById(R.id.price);
priceChange = itemView.findViewById(R.id.price_change);
tickerLogo = itemView.findViewById(R.id.ticker_image);
favouriteButton = itemView.findViewById(R.id.button_favourite);
}
// заполнение элемента RecyclerView данными
void bind(Ticker ticker) {
double priceNow = ticker.getPrice();
double priceDayAgo = ticker.getPriceDayAgo();
String sign = "";
this.ticker.setText(ticker.getTicker());
this.tickerFull.setText(ticker.getTickerFull());
this.price.setText("$" + priceNow);
// check price
if (priceNow < priceDayAgo) {
sign = "-";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorRedDm));
} else if (priceNow > priceDayAgo) {
sign = "+";
this.priceChange.setTextColor(context.getResources().getColor(R.color.colorGreenDm));
}
// check favourites
if (ticker.isFavourite()) {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_on));
} else {
this.favouriteButton.setBackground(context.getDrawable(R.drawable.ic_favourite_off));
}
this.priceChange.setText(String.format("%s$%.2f (%.2f%%)", sign, Math.abs(priceNow-priceDayAgo), Math.abs(priceNow/priceDayAgo*100-100)));
this.tickerLogo.setImageResource(ticker.getTickerLogo());
}
}
interface Listener {
void onTickerClick(Ticker ticker);
void onFavouriteClick(Ticker ticker);
}
}
Here is my Main Activity
package com.skorbr.stock_yandextest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ActivityMain extends Activity {
private RecyclerView tickerList;
private TickerAdapter tickerAdapter;
private List<Ticker> tickerListList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tickerListList = tickerList();
tickerList = findViewById(R.id.tickers_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
tickerList.setLayoutManager(layoutManager);
tickerAdapter = new TickerAdapter(tickerListList, new TickerAdapter.Listener() {
#Override
public void onTickerClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTickerFull(), Toast.LENGTH_SHORT);
}
#Override
public void onFavouriteClick(Ticker ticker) {
Toast.makeText(ActivityMain.this, ticker.getTicker(), Toast.LENGTH_SHORT);
}
});
tickerList.setAdapter(tickerAdapter);
}
private List<Ticker> tickerList() {
List<Ticker> tickers = new ArrayList<>();
tickers.add(new Ticker("APPL", "Apple Inc.", 138.54, 150.22, R.drawable.apple_logo, false));
tickers.add(new Ticker("TSLA", "Tesla Motors", 904.37, 753.92, R.drawable.tesla_logo, true));
tickers.add(new Ticker("GOOGL", "Alphabel Class A", 1845.90, 1845.90, R.drawable.google_logo, false));
return tickers;
}
}
Here is my class for data
package com.skorbr.stock_yandextest;
public class Ticker {
private String ticker;
private String tickerFull;
private double price;
private double priceDayAgo;
private int tickerLogo;
private boolean isFavourite;
public Ticker(String ticker, String tickerFull, double price, double priceDayAgo, int tickerLogo, boolean isFavourite) {
this.ticker = ticker;
this.tickerFull = tickerFull;
this.price = price;
this.priceDayAgo = priceDayAgo;
this.tickerLogo = tickerLogo;
this.isFavourite = isFavourite;
}
public String getTicker() {
return ticker;
}
public String getTickerFull() {
return tickerFull;
}
public double getPrice() {
return price;
}
public double getPriceDayAgo() {
return priceDayAgo;
}
public int getTickerLogo() {
return tickerLogo;
}
public boolean isFavourite() {
return isFavourite;
}
public void setFavourite(boolean favourite) {
isFavourite = favourite;
}
}
#Override
public void onBindViewHolder(#NonNull TickerViewHolder holder, int position) {
Ticker ticker = tickers.get(position);
holder.bind(ticker);
holder.itemView.setTag(ticker);
// add this line
holder.favouriteButton.setTag(ticker);
}
Or you can modify the onCreateViewHolder()
view.findViewById(R.id.button_favourite).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// instead of
onTickerClickListener.onFavouriteClick((Ticker) v.getTag());
// use
onTickerClickListener.onFavouriteClick((Ticker) view.getTag());
}
});

How to get value from MainActivity?

So I have this main activity:
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private volatile boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
public boolean getStopTask() {
return stopTask;
}
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
I was told that I could access getStopTask() from MyTask by getting an instance of MainActivity and accessing that function directly.
I tried that, but I get an error: "Can't create handler inside thread Thread[Thread-6,5,main] that has not called Looper.prepare()".
Here's MyTask:
import android.widget.TextView;
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = mainActivity.getStopTask();
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The error happens right after the app hits:
MainActivity mainActivity = new MainActivity();
How can I get the value of stopTask from MyTask?
I would turn boolean stopTask to static and use it instead of getStopTask() this way:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
public static boolean stopTask = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
}
/*
public boolean getStopTask() {
return stopTask;
}*/
public void startMyTask(View view) {
stopTask = false;
TextView textView = findViewById(R.id.text_view);
MyTask myTask = new MyTask(10, textView);
new Thread(myTask).start();
}
public void stopMyTask(View view) {
stopTask = true;
}
}
MyTask.java:
public class MyTask implements Runnable {
int seconds;
TextView textView;
MyTask(int seconds, TextView textView) {
this.seconds = seconds;
this.textView = textView;
}
#Override
public void run() {
//MainActivity mainActivity = new MainActivity();
for (int x = 0; x < seconds; x++) {
boolean stopTask = MainActivity.stopTask;
if (stopTask)
break;
textView.setText(String.format("x: %s", x));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

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.

Android studio error in java main activity?

I am dealing with a problem with compile errors in my java code which I cannot understand how to correct.
First error:
main cannot be resolved or is not a field ....
Second error:
The method OnKeyListener(new MainActivity.OnKeyListener(){}) is undefined for the type EditText
package com.uichat;
import android.app.Activity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends Activity{
private ChatArrayAdapter adp;
private ListView list;
private EditText ChatText;
private Button send;
Intent In;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent I = getIntent();
send = (Button) findViewById(R.id.btn);
list = (ListView) findViewById(R.id.list);
adp = new ChatArrayAdapter(getApplicationContext(), R.layout.chat);
ChatText = (EditText) findViewById(R.id.chat);
ChatText.setKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
return sendChatMessage(false);
}
return false;
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
sendChatMessage(false);
}
});
list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
list.setAdapter(adp);
adp.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
list.setSelection(adp.getCount() - 1);
}
});
}
private boolean sendChatMessage(boolean side) {
adp.add(new ChatMessage(side, ChatText.getText().toString()));
ChatText.setText("");
side = !side;
return true;
}
public ListView getList() {
return list;
}
public void setList(ListView list) {
this.list = list;
}
class EditView {
private String text;
public void setOnKeyListener(OnKeyListener onKeyListener) {
}
public boolean getText() {
return true;
}
public void setText(String text) {
this.text = text;
}
}
class OnKeyListener {
}
}
First Error:
main cannot be resolved or is not a field ....
setContentView(R.layout.main);
Attempts to reference a non-existent field of R.layout called "main"
It is missing either because you do not have a valid "main.xml" in your res/layout tree, or because you need to clean and rebuild your project to update changes there. (Accidentally importing Android's own R class could do it too, but you haven't done that in your provided code).
Second error:
The method OnKeyListener(new MainActivity.OnKeyListener(){}) is undefined for the type EditText
The method you should be calling for an EditText is setOnKeyListener()
the argument you pass will need to be a class which implements View.onKeyListener
Therefore your internal
class OnKeyListener {
}
Needs to have the required method
class OnKeyListener {
public boolean onKey(View v, int keyCode, KeyEvent event) {
//insert code here
return true;
}
}
see http://developer.android.com/reference/android/view/View.OnKeyListener.html

Categories