Two layouts, one disabled - android

I have an Activity with a RadioGroup which contains 2 RadioButtons (rdbtn4, rdbtn5).
Then I have a XML file which contains to LinearLayouts:
linlay4 just contains 4 Spinners,
linlay5 five additional Spinners.
Then the user can set the Spinners as he likes and after pressing a button 2 TextViews are set with specific text (depends on the chosen Spinner values).
This is working flawlessly with linlay4, with linlay5 chosen the TextViews aren't set.
This is my code:
package at.esdev.electro;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
public class Widerstandsfarbcode extends Activity
{
LinearLayout linlay4rings, linlay5rings;
TextView tvWidResultValue, tvWidToleranzValue;
Button btnCalcwid;
Spinner sp4Farbe1, sp4Farbe2, sp4Farbe3, sp4Farbe4, sp5Farbe1, sp5Farbe2, sp5Farbe3, sp5Farbe4, sp5Farbe5;
RadioGroup rdGrp1;
RadioButton rdbtn4rings, rdbtn5rings;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.widerstandsfarbcode);
linlay4rings = (LinearLayout) findViewById(R.id.linLay4rings);
linlay5rings = (LinearLayout) findViewById(R.id.linLay5rings);
tvWidResultValue = (TextView) findViewById(R.id.tvWidResultValue);
tvWidToleranzValue = (TextView) findViewById(R.id.tvWidToleranzValue);
btnCalcwid = (Button) findViewById(R.id.btnCalcwid);
sp4Farbe1 = (Spinner) findViewById(R.id.sp4Farbe1);
sp4Farbe2 = (Spinner) findViewById(R.id.sp4Farbe2);
sp4Farbe3 = (Spinner) findViewById(R.id.sp4Farbe3);
sp4Farbe4 = (Spinner) findViewById(R.id.sp4Farbe4);
sp5Farbe1 = (Spinner) findViewById(R.id.sp5Farbe1);
sp5Farbe2 = (Spinner) findViewById(R.id.sp5Farbe2);
sp5Farbe3 = (Spinner) findViewById(R.id.sp5Farbe3);
sp5Farbe4 = (Spinner) findViewById(R.id.sp5Farbe4);
sp5Farbe5 = (Spinner) findViewById(R.id.sp5Farbe5);
rdGrp1 = (RadioGroup) findViewById(R.id.rdGrp1);
rdbtn4rings = (RadioButton) findViewById(R.id.rdb4Rings);
rdbtn5rings = (RadioButton) findViewById(R.id.rdb5Rings);
//Default-Value when starting Activity:
linlay4rings.setVisibility(0); //0 = visible, 4 = invisible, 8 = gone
linlay5rings.setVisibility(8);
//Layout for 5 buttons disabled, if rdbtn4 is selected:
rdbtn4rings.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
linlay4rings.setVisibility(0); //0 = visible, 4 = invisible, 8 = gone
linlay5rings.setVisibility(8);
}
});
//Layout for 4 buttons disabled, if rdbtn5 is selected:
rdbtn5rings.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
linlay4rings.setVisibility(8); //0 = visible, 4 = invisible, 8 = gone
linlay5rings.setVisibility(0);
}
});
//Color-adjusting
ArrayAdapter <?> adapterFarben = ArrayAdapter.createFromResource(this, R.array.widerstandsfarbSpinnerItems, android.R.layout.simple_spinner_item);
adapterFarben.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp4Farbe1.setAdapter(adapterFarben);
sp4Farbe2.setAdapter(adapterFarben);
sp5Farbe1.setAdapter(adapterFarben);
sp5Farbe2.setAdapter(adapterFarben);
sp5Farbe3.setAdapter(adapterFarben);
//Multiplier-adjusting
ArrayAdapter <?> adapterMultiplikator = ArrayAdapter.createFromResource(this, R.array.widerstandsMultiplikatorSpinnerItems, android.R.layout.simple_spinner_item);
adapterMultiplikator.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp4Farbe3.setAdapter(adapterMultiplikator);
sp5Farbe4.setAdapter(adapterMultiplikator);
//Tolerance-adjusting:
ArrayAdapter <?> adapterToleranz = ArrayAdapter.createFromResource(this, R.array.widerstandsToleranzSpinnerItems, android.R.layout.simple_spinner_item);
adapterFarben.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp4Farbe4.setAdapter(adapterToleranz);
sp5Farbe5.setAdapter(adapterToleranz);
if (rdbtn4rings.isChecked())
{
btnCalcwid.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String s41 = String.valueOf(sp4Farbe1.getSelectedItemId()); //Farbe 1
String s42 = String.valueOf(sp4Farbe2.getSelectedItemId()); //Farbe 2
String s43 = String.valueOf(sp4Farbe3.getSelectedItemId()); //Multiplikator
String s44 = String.valueOf(sp4Farbe4.getSelectedItemId()); //Toleranz
int ds43 = Integer.parseInt(s43);
int ds44 = Integer.parseInt(s44);
rise1(ds43);
String snewTolerance = String.valueOf(getToleranceValue(ds44));
//Output:
tvWidResultValue.setText("" + s41 + s42 + "*10^" + ds43 + " Ohm");
tvWidToleranzValue.setText(""+ snewTolerance + " %");
}
});
}
if (rdbtn5rings.isChecked())
{
btnCalcwid.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String s51 = String.valueOf(sp5Farbe1.getSelectedItemId()); //Farbe 1
String s52 = String.valueOf(sp5Farbe2.getSelectedItemId()); //Farbe 2
String s53 = String.valueOf(sp5Farbe3.getSelectedItemId()); //Farbe 3
String s54 = String.valueOf(sp5Farbe4.getSelectedItemId()); //Multiplikator
String s55 = String.valueOf(sp5Farbe5.getSelectedItemId()); //Toleranz
int ds54 = Integer.parseInt(s54);
int ds55 = Integer.parseInt(s55);
rise1(ds54);
String snewTolerance = String.valueOf(getToleranceValue(ds55));
//Output:
tvWidResultValue.setText("" + s51 + s52 + s53 + "*10^" + ds54 + " Ohm");
tvWidToleranzValue.setText(""+ snewTolerance + " %");
}//onClick
});
}
}
public double rise1(double multiplikValue)
{
if (multiplikValue > -1)
{
if (multiplikValue < 7)
{
multiplikValue = multiplikValue++;
}
}
if (multiplikValue == 7)
{
multiplikValue = -1; //weil 10^-1 = 0.1
}
if (multiplikValue == 8)
{
multiplikValue = -2; //weil 10^-2 = 0.01
}
return multiplikValue;
}
public double getToleranceValue(double toleranz)
{
double newTolerance = 0;
if (toleranz == 0) //Spinnerposition
{
newTolerance = 1; //Toleranz-%-Wert
}
if (toleranz == 1 )
{
newTolerance = 2;
}
if (toleranz == 2 )
{
newTolerance = 0.5;
}
if (toleranz == 3 )
{
newTolerance = 0.25;
}
if (toleranz == 4 )
{
newTolerance = 0.1;
}
if (toleranz == 5 )
{
newTolerance = 5;
}
if (toleranz == 6 )
{
newTolerance = 10;
}
return newTolerance;
}
}
Thanks in advance! :)

Your variable names are very cryptic, but I think I see what is wrong. Try changing the checks in your btnCalcWid around, like this:
btnCalcwid.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (rdbtn4rings.isChecked())
{
String s41 = String.valueOf(sp4Farbe1.getSelectedItemId()); //Farbe 1
String s42 = String.valueOf(sp4Farbe2.getSelectedItemId()); //Farbe 2
String s43 = String.valueOf(sp4Farbe3.getSelectedItemId()); //Multiplikator
String s44 = String.valueOf(sp4Farbe4.getSelectedItemId()); //Toleranz
int ds43 = Integer.parseInt(s43);
int ds44 = Integer.parseInt(s44);
rise1(ds43);
String snewTolerance = String.valueOf(getToleranceValue(ds44));
//Output:
tvWidResultValue.setText("" + s41 + s42 + "*10^" + ds43 + " Ohm");
tvWidToleranzValue.setText(""+ snewTolerance + " %");
}
else if (rdbtn5rings.isChecked())
{
String s51 = String.valueOf(sp5Farbe1.getSelectedItemId()); //Farbe 1
String s52 = String.valueOf(sp5Farbe2.getSelectedItemId()); //Farbe 2
String s53 = String.valueOf(sp5Farbe3.getSelectedItemId()); //Farbe 3
String s54 = String.valueOf(sp5Farbe4.getSelectedItemId()); //Multiplikator
String s55 = String.valueOf(sp5Farbe5.getSelectedItemId()); //Toleranz
int ds54 = Integer.parseInt(s54);
int ds55 = Integer.parseInt(s55);
rise1(ds54);
String snewTolerance = String.valueOf(getToleranceValue(ds55));
//Output:
tvWidResultValue.setText("" + s51 + s52 + s53 + "*10^" + ds54 + " Ohm");
tvWidToleranzValue.setText(""+ snewTolerance + " %");
}//else if
}//onClick
});//setOnClickListener

Related

Quiz Application

I have a problem with my app and i can’t figure it out how to solve it :(
I made a quiz app. Radio Buttons works okey, open question works okey, I have a problem with Checkboxes. When I select all 3 checkboxes (where the correct answers are two), it still marks me as the correct answer… What am I doing wrong? Thanks! :(
package com.example.francesco.askzelda;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button submit;
int correctAnswers = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Make sure that user can only choose the two of the answers not all of them.
public void checkTwoBox(View view) {
CheckBox firstcheck = (CheckBox) findViewById(R.id.optionQ3_1);
CheckBox secondcheck = (CheckBox) findViewById(R.id.optionQ3_2);
CheckBox thirdcheck = (CheckBox) findViewById(R.id.optionQ3_3);
if (firstcheck.isChecked() && secondcheck.isChecked()) {
thirdcheck.setChecked(false);
}
if (thirdcheck.isChecked() && secondcheck.isChecked()) {
firstcheck.setChecked(false);
}
if (thirdcheck.isChecked() && firstcheck.isChecked()) {
secondcheck.setChecked(false);
}
}
//Show the result
public void submitResult(View view) {
//figure out if the user choose the right answer
RadioButton firstRightBox = (RadioButton) findViewById(R.id.option1_rb);
boolean hasClickedFirst1 = firstRightBox.isChecked();
RadioButton secondRightBox = (RadioButton) findViewById(R.id.optionQ2_2_rb);
boolean hasClickedSecond2 = secondRightBox.isChecked();
CheckBox thirdRightBox = (CheckBox) findViewById(R.id.optionQ3_1);
boolean hasClickedThird1 = thirdRightBox.isChecked();
CheckBox thirdSecondRightBox = (CheckBox) findViewById(R.id.optionQ3_3);
boolean hasClickedThird3 = thirdSecondRightBox.isChecked();
EditText answerText = (EditText) findViewById(R.id.question_4_editText);
String MasterSword = answerText.getText().toString();
//figure out if the user choose the wrong answer
RadioButton firstWrongBox = (RadioButton) findViewById(R.id.option2_rb);
boolean hasClickedFirst2 = firstWrongBox.isChecked();
RadioButton firstWrongBox2 = (RadioButton) findViewById(R.id.option3_rb);
boolean hasClickedFirst3 = firstWrongBox2.isChecked();
RadioButton secondWrongBox = (RadioButton) findViewById(R.id.optionQ2_1_rb);
boolean hasClickedSecond1 = secondWrongBox.isChecked();
RadioButton secondWrongBox2 = (RadioButton) findViewById(R.id.optionQ2_3_rb);
boolean hasClickedSecond3 = secondWrongBox2.isChecked();
CheckBox thirdWrongBox = (CheckBox) findViewById(R.id.optionQ3_2);
boolean hasClickedThird2 = thirdWrongBox.isChecked();
int correctAnswer = calculateCorrectAnswer(hasClickedFirst1, hasClickedSecond2, hasClickedThird1, hasClickedThird2, hasClickedThird3, MasterSword);
int wrongAnswer = calculateWrongAnswer(hasClickedFirst2, hasClickedFirst3, hasClickedSecond1, hasClickedSecond3, hasClickedThird2, hasClickedThird1, hasClickedThird3, MasterSword);
int emptyAnswer = calculateEmptyAnswer(hasClickedFirst1, hasClickedSecond2, hasClickedThird1, hasClickedThird2, hasClickedThird3, MasterSword, hasClickedFirst2, hasClickedFirst3, hasClickedSecond1, hasClickedSecond3);
String quizMessage = createOrderSummary(correctAnswer, wrongAnswer, emptyAnswer);
// Toast Message
String toast_1 = getString(R.string.toast_1);
String toast_2 = getString(R.string.toast_2);
String toast_3 = getString(R.string.toast_3);
Toast.makeText(MainActivity.this,toast_1 + " " + correctAnswer + " " + toast_2 + " \n" + toast_3, Toast.LENGTH_LONG).show();
displayMessage(quizMessage);
}
private String createOrderSummary(int correctAnswer, int wrongAnswer, int emptyAnswer) {
String msg1 = getString(R.string.thank1);
String msg2 = getString(R.string.thank2);
String msg3 = getString(R.string.total_correct);
String msg4 = getString(R.string.total_wrong);
String msg5 = getString(R.string.total_empty1);
String msg6 = getString(R.string.total_empty2);
String msg7 = getString(R.string.final_msg1);
String msg8 = getString(R.string.final_msg2);
String msg9 = getString(R.string.final_msg3);
String quizMessage = msg1 + " " + " " + msg2;
quizMessage += "\n" + msg3 + " " + correctAnswer;
quizMessage += "\n" + msg4 + " " + wrongAnswer;
quizMessage += "\n" + msg5 + " " + emptyAnswer + " " + msg6;
if (correctAnswer <= wrongAnswer) {
quizMessage += "\n" + msg7;
} else {
quizMessage += "\n" + msg8;
}
quizMessage += "\n" + msg9;
return quizMessage;
}
//Calculates correct
public int calculateCorrectAnswer(boolean first1, boolean second2, boolean third1, boolean third2, boolean third3, String LeoTolstoy) {
int correct = 0;
if (first1) {
correct = correct + 1;
}
if (second2) {
correct = correct + 1;
}
if (third1 & third3) {
correct = correct + 1;
}
if (LeoTolstoy.equals("Master Sword")) {
correct = correct + 1;
}
int correctAnswer = correct;
return correctAnswer;
}
//Calculates false
public int calculateWrongAnswer(boolean first2, boolean first3, boolean second1, boolean second3, boolean third2, boolean third1, boolean third3, String MasterSowrd) {
int wrong = 0;
if (first2) {
wrong = wrong + 1;
}
if (first3) {
wrong = wrong + 1;
}
if (second1) {
wrong = wrong + 1;
}
if (second3) {
wrong = wrong + 1;
}
if ((third1 & third2) || (third3 & third2) || (third3 & third2 & third1)) {
wrong = wrong + 1;
}
if (!MasterSowrd.equals("Master Sword") && !MasterSowrd.equals("")) {
wrong = wrong + 1;
}
int wrongAnswer = wrong;
return wrongAnswer;
}
//calculate empty questions
public int calculateEmptyAnswer(boolean first1, boolean second2, boolean third1, boolean third2, boolean third3, String MasterSowrd, boolean first2, boolean first3, boolean second1, boolean second3) {
int empty = 0;
if (!first1 && !first2 && !first3) {
empty = empty + 1;
}
if (!second1 && !second2 && !second3) {
empty = empty + 1;
}
if ((!third1 && !third3 && !third2) || (third1 && !third3 && !third2) || (third3 && !third1 && !third2) || (third2 && !third1 && !third3)) {
empty = empty + 1;
}
if (MasterSowrd.equals("")) {
empty = empty + 1;
}
int emptyAnswer = empty;
return emptyAnswer;
}
//This method displays the given text on the screen.
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.result_text_view);
orderSummaryTextView.setText(message);
}
}
You could do something like this:
public void runThisEveryTimeTheUserClicksAnyCheckBox(CheckBox mostRecentlySelectedCheckBox) {
CheckBox firstcheck = (CheckBox) findViewById(R.id.optionQ3_1);
CheckBox secondcheck = (CheckBox) findViewById(R.id.optionQ3_2);
CheckBox thirdcheck = (CheckBox) findViewById(R.id.optionQ3_3);
CheckBox[] allCheckBoxes = new CheckBox[]{firstcheck, secondcheck, thirdcheck};
int totalChecked = 0;
for (CheckBox checkBox : allCheckBoxes) {
if ( checkBox.isSelected() ) {
totalChecked++;
}
}
if (totalChecked == 3) {
mostRecentlySelectedCheckBox.setSelected(false);
}
}
Then you won't need the checkTwoBox method anymore.

While Scrolling RecyclerView, custom-view value keep changing

I have issue that when I click to increase quantity of position first item and when I scolling down and up then, position of that item is flickering...
Please help me out guys thanks in advance
This is my adapter class.
package growcia.malacus.com.growcia.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
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 android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import growcia.malacus.com.growcia.R;
import growcia.malacus.com.growcia.activity.ProductListActivity;
import growcia.malacus.com.growcia.database.SqliteDatabaseClass;
import growcia.malacus.com.growcia.model.SellerProductPOJO;
public class ProductListAdapter extends RecyclerView.Adapter<ProductListAdapter.ViewHolder> {
public Context context;
SqliteDatabaseClass DB;
String productCode;
boolean isPressed = false;
int count = 0;
int qty;
public String pname, price, img_path;
static int productItem = 0;
int totPrice;
ProductListActivity objProductList;
List<SellerProductPOJO> productListDetails;
public ProductListAdapter(List<SellerProductPOJO> productDetails, Context context) {
super();
DB = new SqliteDatabaseClass(context);
objProductList = new ProductListActivity();
this.productListDetails = productDetails;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_product, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final SellerProductPOJO objSellerProductPOJO = productListDetails.get(position);
try {
JSONArray jar = DB.getAllProductCodeAndQtyProductList();
Log.e("total pid and qty ad : ", "" + jar.toString());
for (int i = 0; i < jar.length(); i++) {
JSONObject job = jar.getJSONObject(i);
String cart_productId = job.getString("ProductCode");
String productQty = job.getString("QuantityOrdered");
Log.e("id and qty: ", cart_productId + " qty: " + productQty);
String plist_prod_id = productListDetails.get(position).getProductCode();
Log.e("product id in cart : ", "" + cart_productId.toString());
Log.e("product id service : ", "" + plist_prod_id.toString());
}
} catch (JSONException J) {
J.printStackTrace();
}
String url = objSellerProductPOJO.getImagePath();
Picasso.with(context)
.load(url)
.placeholder(R.drawable.placeholder) // optional
.error(R.drawable.error) // optional
.resize(100, 100) // optional
.into(holder.ivProduct);
holder.tvProductName.setText(objSellerProductPOJO.getProductName());
holder.tvUnit.setText(objSellerProductPOJO.getAvailableQuantity());
holder.tvPrice.setText(objSellerProductPOJO.getPrice());
Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/abc.ttf");
holder.tvProductName.setTypeface(font);
holder.tvUnit.setTypeface(font);
holder.tvPrice.setTypeface(font);
if (context instanceof ProductListActivity)
totPrice = DB.getSumPrice();
Log.e("all price insert : ", "" + totPrice);
count = DB.getProfilesCount();
Log.e("count from db", "" + count);
((ProductListActivity) context).showCartItem(count, totPrice);
holder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SellerProductPOJO objSellerProduct = productListDetails.get(position);
String stock = holder.tvUnit.getText().toString();
int qtyMiddle = Integer.parseInt(holder.tvQty.getText().toString());
int qtyStock = Integer.parseInt(objSellerProduct.getAvailableQuantity().toString());
if (!stock.equalsIgnoreCase("0")) {
if (qtyMiddle < qtyStock) {
pname = objSellerProduct.getProductName();
img_path = objSellerProduct.getImagePath();
price = objSellerProduct.getPrice();
productCode = objSellerProduct.getProductCode();
String str_qty = holder.tvQty.getText().toString();
int qty = Integer.parseInt(str_qty);
qty = qty + 1;
String final_str_qty = "" + qty;
objSellerProductPOJO.setQty(final_str_qty);
holder.tvQty.setText(objSellerProductPOJO.getQty() + "");
int reduceable_stock = qtyStock - qty;
holder.tvUnit.setText(reduceable_stock + "");
if (qty > 0) {
boolean entryStatus = DB.Exists(productCode);
if (entryStatus) {
productItem = productItem + 1;
String str_newQty = holder.tvQty.getText().toString();
int newqty = Integer.parseInt(str_newQty);
double intPrice = Double.parseDouble(price);
double totPrice = qty * intPrice;
DB.updateProductQty(productCode, newqty, totPrice);
totPrice = DB.getSumPrice();
Log.e("all price update: ", "" + totPrice);
} else {
productItem = 1;
DB.addProductItem(productCode, pname, img_path, productItem, price, price);
}
if (context instanceof ProductListActivity)
totPrice = DB.getSumPrice();
Log.e("all price insert : ", "" + totPrice);
count = DB.getProfilesCount();
Log.e("count from db", "" + count);
((ProductListActivity) context).showCartItem(count, totPrice);
}
} else {
Toast.makeText(context, "Product out of stock!!", Toast.LENGTH_SHORT).show();
}
}
}
});
holder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stock = holder.tvUnit.getText().toString();
if (!stock.equalsIgnoreCase("0")) {
SellerProductPOJO objSellerProductDeduct = productListDetails.get(position);
String str_qty = holder.tvQty.getText().toString();
int qty = Integer.parseInt(str_qty);
if (qty != 0) {
int qtyStockMinusClick = Integer.parseInt(holder.tvUnit.getText().toString());
holder.tvUnit.setText((qtyStockMinusClick + 1) + "");
Log.e("btnMinus", "" + qty);
if (qty == 1) {
Log.e("", "inside 0 qty");
DB.delete_byID(productCode);
qty = qty - 1;
String final_str_qty = "" + qty;
objSellerProductPOJO.setQty(final_str_qty);
holder.tvQty.setText(objSellerProductPOJO.getQty()+"");
} else {
qty = qty - 1;
String final_str_qty = "" + qty;
objSellerProductPOJO.setQty(final_str_qty);
holder.tvQty.setText(objSellerProductPOJO.getQty()+"");
double intPrice = Double.parseDouble(price);
double totPrice = qty * intPrice;
DB.updateProductQty(productCode, qty, totPrice);
}
if (context instanceof ProductListActivity)
totPrice = DB.getSumPrice();
Log.e("all price insert : ", "" + totPrice);
count = DB.getProfilesCount();
Log.e("count from db", "" + count);
((ProductListActivity) context).showCartItem(count, totPrice);
}
} else {
Toast.makeText(context, "Product out of stock!!", Toast.LENGTH_SHORT).show();
}
notifyDataSetChanged();
}
});
holder.imagefavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("position", "all position" + position);
if (isPressed)
holder.imagefavorite.setBackgroundResource(R.drawable.ic_not_favourite);
else
holder.imagefavorite.setBackgroundResource(R.drawable.favourite_icon);
isPressed = !isPressed;
}
});
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public int getItemCount() {
return productListDetails.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvProductName;
public TextView tvUnit;
public TextView tvPrice;
public TextView tvQty;
public ImageView ivProduct;
public ImageView imagefavorite;
// public EditText edqntiry;
public Button btnPlus;
public Button btnMinus;
public ViewHolder(View itemView) {
super(itemView);
ivProduct = (ImageView) itemView.findViewById(R.id.ivProduct);
tvProductName = (TextView) itemView.findViewById(R.id.tvProductName);
tvUnit = (TextView) itemView.findViewById(R.id.tvUnit);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
tvQty = (TextView) itemView.findViewById(R.id.tvQty);
btnPlus = (Button) itemView.findViewById(R.id.btnPlus);
btnMinus = (Button) itemView.findViewById(R.id.btnMinus);
imagefavorite = (ImageView) itemView.findViewById(R.id.imagefavorite);
}
}
}
When I am going to incerase qty then below screen shows
when I am scrolled down and up then below screen shows
You are not setting the initial value of holder.tvQty in your onBindViewHolder method.
When you update the value of holder.tvQty in holder.btnPlus or holder.btnMinus listeners, you should save that value somewhere in your objSellerProductPOJO:
objSellerProductPOJO.setQty(final_str_qty)
Then under:
holder.tvPrice.setText(objSellerProductPOJO.getPrice());
add:
holder.tvQty.setText(objSellerProductPOJO.getQty());
You need to update the productListDetails variable on add or subtract after
holder.tvQty.setText(final_str_qty);
And notify the adapter using notifydatasetchange()
In your onClick() methods, replace the the position parameter of the onBindViewHolder() method with the getAdapterPosition().
Replace from
SellerProductPOJO objSellerProduct = productListDetails.get(position);
SellerProductPOJO objSellerProductDeduct = productListDetails.get(position);
to
SellerProductPOJO objSellerProduct = productListDetails.get(getAdapterPosition());
SellerProductPOJO objSellerProductDeduct = productListDetails.get(getAdapterPosition());

Using AlertDialog.Builder to build custom AlertDialog class

I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.

validation for empty edit text field is not working

I have two TextView, two EditText and two Buttons. I want to set a DialogBox or Toast when the button is clicked without entering any values in the textview. I have two stings, s and s1. If s and s1 or either s or s1 is not entered in the edittext, I must get a toast. I wrote a code for toast but it's not working fine!
Can you help me with this?
This is my code:
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
AnimationDrawable frameanimation;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN , WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender=(Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview=(ImageView)findViewById(R.id.imageanim);
imgview.setBackgroundResource(R.drawable.myanim);
frameanimation=(AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
//code for toast//
//if s nd s1 is empty then execute this else executee the rest//
if((s==" ") && (s1==" "))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
else
{
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0,
n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
Change your validation to this :
if((s.equals("")) && (s1.equals("")))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}
Or you can check like this:
if((s.length() == 0) && (s1.length() == 0))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT). show();
}
Tried your code and validation is working :
import java.io.DataInputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
TextView name1;
TextView name2;
Button click;
Button samegender;
EditText boyname;
EditText girlname;
ImageView imgview;
Bitmap bmp;
String bread;
String cheese;
char sauce;
MediaPlayer song;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow(). setFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN
// ,WindowManager LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
name1 = (TextView) findViewById(R.id.tvname1);
name2 = (TextView) findViewById(R.id.tvname2);
click = (Button) findViewById(R.id.btclick);
samegender = (Button) findViewById(R.id.btsamegender);
samegender.setOnClickListener(this);
boyname = (EditText) findViewById(R.id.etboyname);
boyname.setInputType(InputType.TYPE_CLASS_TEXT);
girlname = (EditText) findViewById(R.id.etgirlname);
girlname.setInputType(InputType.TYPE_CLASS_TEXT);
imgview = (ImageView) findViewById(R.id.imageanim);
frameanimation = (AnimationDrawable) imgview.getBackground();
frameanimation.start();
click.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btclick:
DataInputStream dis = new DataInputStream(System.in);
int i,
j = 0;
int d = 0;
int totlen;
String flames;
int[] newarr = new int[20];
int[] newarr1 = new int[20];
System.out.println("enter name");
String s = boyname.getText().toString();
StringBuffer sb = new StringBuffer(s);
char namearr[] = s.toCharArray();
System.out.println("enter name");
String s1 = girlname.getText().toString();
// code for toast//
// if s nd s1 is empty then execute this else executee the rest//
if ((s.equals("")) || (s1.equals(""))) {
Toast.makeText(getBaseContext(), "cnt b empty",
Toast.LENGTH_SHORT).show();
} else {
StringBuffer sb1 = new StringBuffer(s1);
System.out.println("the string1=" + s);
System.out.println("the string2=" + s1);
char namearr1[] = s1.toCharArray();
try {
for (i = 0; i < sb.length(); i++) {
for (j = 0, d = 0; j < sb1.length(); j++) {
if (sb.charAt(i) == sb1.charAt(j)) {
sb.deleteCharAt(i);
System.out.println("the buff=" + sb);
sb1.deleteCharAt(j);
System.out.println("the buff=" + sb1);
i = 0;
break;
}
}
}
} catch (Exception e) {
System.out.println(e);
}
sb.length();
System.out.println("string length=" + sb.length());
sb1.length();
System.out.println("string length=" + sb1.length());
int len = sb.length() + sb1.length();
totlen = len - 1;
System.out.println("string length=" + totlen);
String str = "flames";
StringBuffer sb2 = new StringBuffer(str);
int index = 0;
str.length();
int length = str.length();
System.out.println("the length of flames is=" + str.length());
while (index < length) {
char letter = str.charAt(index);
System.out.println(letter);
index = index + 1;
}
System.out.println(sb2.length());
int m = 0, n = 0;
for (m = 0;;) {
if (n == totlen) {
sb2.deleteCharAt(m);
System.out.println(sb2 + " m:" + m + " n:" + n);
System.out.println(sb2);
n = 0;
m--;
} else {
n++;
}
if (m == sb2.length() - 1) {
m = 0;
} else {
m++;
}
if (sb2.length() == 1) {
break;
}
}
char res = sb2.charAt(0);
System.out.println("the final char is=" + res);
String bread = boyname.getText().toString();
String cheese = girlname.getText().toString();
char sauce = res;
Bundle basket = new Bundle();
basket.putString("name1", bread);
basket.putString("name2", cheese);
basket.putChar("ans", sauce);
Intent a = new Intent(MainActivity.this, ResultActivity.class);
a.putExtras(basket);
startActivity(a);
}
break;
}
}
}
Try if (s.isEmpty() || s1.isEmpty()) to check if your strings are empty. == and .equals will not work with string comparison because they are comparing the objects and not solely the contents. To check if two strings are equal, you can use firstString.compareTo(anotherString) == 0.
Trim your edittext value then compare
if((("").equals(s.trim())) && (("").equals(s1.trim())))
{
Toast.makeText(getBaseContext(),"cnt b empty" ,Toast.LENGTH_SHORT).show();
}

Android Spinner reselects itself to first value every half second

So, I have a spinner, populated with ~35 values. If I select, say, the fifth item, then when it is selected, it does what it is supposed to do (populate a second spinner). My problem is that shortly afterwards (<1/2 second) it reverts the values in the second spinner to what they would be if option 1 in the first spinner were selected. The fifth item in the first spinner is still selected but it acts as though the first item gets selected twice per second.
I've tried everything I could find on this (barely anything) and nothing has worked so far. This basically has me stuck on going further in my app.
Entire Code:
package com.nicotera.colton.londontransitguide;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.*;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class RoutesActivity extends Activity implements OnItemSelectedListener {
Spinner dirSpinner;
Spinner routeSpinner;
static String [] namedDirections = new String [2];
private static final String TAG = "RoutesActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_routes);
dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner = (Spinner) findViewById(R.id.route_name_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.routes_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner
routeSpinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "Item selected");
//DecimalFormat df = new DecimalFormat("00##");
int tempPos = pos;
Log.i(TAG, ("Position of selected item: " + tempPos));
int routeSelected;
if (tempPos < 17)
routeSelected = (tempPos + 1);
else if (tempPos >= 17 && tempPos < 29)
routeSelected = (tempPos + 2);
else
routeSelected = (tempPos + 3);
String temp;
if (routeSelected < 10)
temp = ("0") + routeSelected;
else
temp = ("") + routeSelected;
String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
new MyInnerClass().execute(url);
}
public void directionSpinner (String directions []) {
int temp;
for (int i = 1; i <=2; i++)
{
temp = Integer.parseInt(directions[i]);
if (temp == 1)
namedDirections[(i-1)] = "Eastbound";
else if (temp == 2)
namedDirections[(i-1)] = "Northbound";
else if (temp == 3)
namedDirections[(i-1)] = "Southbound";
else if (temp == 4)
namedDirections[(i-1)] = "Westbound";
}
//setContentView(R.layout.activity_routes);
dirSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add(namedDirections[0]);
adapter.add(namedDirections[1]);
dirSpinner.setAdapter(adapter);
Log.i(TAG, "spinner populated");
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
class MyInnerClass extends AsyncTask<String, Void, String> {
String [] directions = new String [3];
String [] directionNames = new String [3];
private static final String TAG = "RoutesActivity";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
RoutesActivity.this.directionSpinner(directions);
}
#Override
protected String doInBackground(String... params) {
try{
Pattern routeDirPattern = Pattern.compile("\\&d=(\\d{1,2})");
Connection conn = Jsoup.connect(params[0]);
Document doc = conn.get();
int i = 0;
Elements routeLinks = doc.select("a[href]");
for (Element routeLink : routeLinks) {
i = (i + 1);
String name = routeLink.text();
Attributes attrs = routeLink.attributes();
String href = attrs.get("href");
Matcher m = routeDirPattern.matcher(href);
if (m.find()) {
String number = m.group(1);
directions [i] = number;
directionNames [i] = name;
Log.i(TAG, directionNames [i]);
}
}
}catch(Exception e){Log.d("doinbackground exception", e.toString());}
return ("Done");
}
}
}
I was using the same onselected listener for both without an if statement to check which one was clicked so it just thought that the first one was clicked.
This is the corrected code:
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Spinner spnr = (Spinner) parent;
Log.i(TAG, "Item selected");
switch(parent.getId()) {
case R.id.route_name_spinner:
//DecimalFormat df = new DecimalFormat("00##");
int tempPos = pos;
Log.i(TAG, ("Position of selected item: " + tempPos));
int routeSelected;
if (tempPos < 17)
routeSelected = (tempPos + 1);
else if (tempPos >= 17 && tempPos < 29)
routeSelected = (tempPos + 2);
else
routeSelected = (tempPos + 3);
String temp;
if (routeSelected < 10)
temp = ("0") + routeSelected;
else
temp = ("") + routeSelected;
String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
new MyInnerClass().execute(url);
case R.id.route_direction_spinner:
}
}

Categories

Resources