Android Spinner reselects itself to first value every half second - android

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:
}
}

Related

How can I control the Recycle View by clicking on the date of the calendar view?

I'm new in android and also new in English sorry my bad English...
I have learned android course at the academy.
My sentence may be wrong because it is written through a translator. I hope you understand with a generous heart.
Here's what I want:
If I click 15 days in Calendar View,
It is hoped that only the 15th day information will be shown in the Recyclerview. If I click on another date in calenderview, for example, 20 days, I hope that the 15th item will disappear and only the 20th item view will be displayed.
Here's what I'm trying to do.
When I click a date in a calendar view, I want to see the Item View corresponding to that date.
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.util.Calendar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Calender extends AppCompatActivity {
// CalendarView myCalenderView;
// TextView schedule1, schedule11;
String a, b, c;
static String data1;
long Now;
Date date;
java.text.SimpleDateFormat mFormat = new SimpleDateFormat("YYYY_MM_dd");
TextView datetext;
Context mcontext;
private String getTime() {
Now = System.currentTimeMillis();
date = new Date(Now);
return mFormat.format(date);
}
private ArrayList<calenderArrayList> mArrayList = new ArrayList<>();
private ArrayList<calenderArrayList> bArrayList = new ArrayList<>();
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static String TAG = "recyclerview_example";
//private ArrayList<calenderArrayList> mArrayList;
//ArrayList 선언
calendarAdapter mAdapter = new calendarAdapter(this, mArrayList);
//mAdapter 선언
// calendarAdapter bAdapter = new calendarAdapter(this, bArrayList);
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calender);
Log.d("스케쥴선택액티비티", "OnCreate()실행");
SharedPreferences calender_load = getSharedPreferences("calender", MODE_PRIVATE);
calender_load.getInt("save_size", 0);
int calender_size = calender_load.getInt("save_size", 0);
Log.d("시작시b사이즈1", "" + calender_size);
Log.d("시작시b사이즈1", "" + bArrayList.size());
Log.d("시작시m사이즈1", "" + mArrayList.size());
if (calender_size != 0) {
for (int i = 0; i < calender_size; i++) {
calenderArrayList calender = new calenderArrayList(calender_load.getString("save_date" + i, ""), calender_load.getString("save_work" + i, ""), calender_load.getString("save_place" + i, ""), calender_load.getBoolean("save_box" + i, false));
if (calender.number_exam.equals(data1)) {
Log.d("불러오기값", "" + calender_load.getString("save_date" + i, ""));
bArrayList.add(calender);
mArrayList.add(calender);
}
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
} else if (calender_size == 0) {
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
//recycler_view라는 id를 가진 recycler_view를 mRecyclerView로 지정해준다.
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), 1));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//RecyclerView 내에 Item view들의 크기를 측정하고 위치를 지정
//언제 item view를 재사용해야하는지에 대한 정책을 결정하고 결정.
//mArrayList = new ArrayList<>();
mAdapter = new calendarAdapter(this, mArrayList);
//RecyclerView 내에 보여지는 view 들에 date set을 binding 시켜주는 역할.
//binding? 데이터 끼리 묵어준다?
mRecyclerView.setAdapter(mAdapter);
//mRecyclerView의 Adapter를 mAdapter로 set한다.
//set? 지정한다. 놓다. 위치하다.
// myCalenderView = (CalendarView) findViewById(R.id.calendar);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// Toast.makeText(getApplicationContext(), "onStart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnStart()실행");
Log.d("스케쥴선택액티비티", "OnResume()실행");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// Toast.makeText(getApplicationContext(), "onResume()", Toast.LENGTH_SHORT).show();
final CalendarView calendar = (CalendarView) findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
data1 = year + "/" + (month + 1) + "/" + dayOfMonth;
String a = data1 + dayOfMonth;
Log.d("날짜", "" + a);
ArrayList<calenderArrayList> dayofMonth = new ArrayList<>();
Log.d("어떤 이름으로?", "" + dayofMonth);
if (dayofMonth.size() != 0) {
SharedPreferences load = getSharedPreferences("" + data1, MODE_PRIVATE);
}
/* if(mArrayList.size()!=0) {
for (int i=0; i<mArrayList.size() ; i++) {
SharedPreferences save11 = getSharedPreferences("save", MODE_PRIVATE );
SharedPreferences.Editor save_editor = save11.edit();
save_editor.putBoolean("save_box"+i+mArrayList.get(i).number_exam, mArrayList.get(i).selected );
save_editor.putString("save_date"+i+mArrayList.get(i).number_exam, mArrayList.get(i).number_exam);
save_editor.putString("save_work"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam);
save_editor.putString("save_place"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam2);
save_editor.putInt("save_size"+mArrayList.get(i).number_exam, mArrayList.size());
save_editor.commit();
}
}
mArrayList.clear();
if(mArrayList.size()!=0)
{
for (int i =0; i<mArrayList.size(); i++){
if(mArrayList.get(i).number_exam.equals(data1)){
}
}
}*/
//int a = dayOfMonth;
Toast.makeText(Calender.this, year + "/" + (month + 1) + "/" + dayOfMonth, Toast.LENGTH_SHORT).show();
Log.d("리사이클러뷰 실행 전", "실행 전");
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
Log.d("리사이클러뷰 실행 후", "실행 후");
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
//TextView ee = findViewById(R.id.number_exam);
Log.d("사이즈 측정 실행 전", "실행 전");
ArrayList<calenderArrayList> calenderArrayLists = new ArrayList<>();
Log.d("실행11111", mAdapter.getItemCount() + "");
Log.d("뭐가 들어있나?", "" + mArrayList);
Log.d("뭐가 들어있나?", "" + mArrayList.size());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(1).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(2).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(3).number_exam.toString());
if (mArrayList.size() != 0) {
Log.d("if구문 실행됨?", "" + mArrayList.size());
//1. 일단 뷰 자체를 초기화 해주어야함.
//2. 초기화 된 뷰에 다시 mArrayList에서 선정 된 정보를 다시 나타내주어야한다.
/* for(int i = 0; i<mArrayList.size(); i++){
Log.d("얼마?", ""+i);
Log.d("for 구문 작동?실행", "여기까진 접속?");
if(mArrayList.get(i).number_exam.toString().contains(a)){
Log.d("뭐가 들어있나? 실행여부", ""+mArrayList.get(i).number_exam.toString());
a = mArrayList.get(i).number_exam;
b = mArrayList.get(i).content_exam;
c = mArrayList.get(i).content_exam2;
//mArrayList.add(mArrayList.get(i));
}
}*/
}
}
});
Button buttonInsert_exam = (Button) findViewById(R.id.exam_button);
//button 클릭시 발생하는 이벤트를 나타낸다. 여기서는 입력하기 버튼 클릭시 발생하는 상황.
buttonInsert_exam.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Calender.this);
View view = LayoutInflater.from(Calender.this)
.inflate(R.layout.activity_calender_edit_box, null, false);
builder.setView(view);
final Button ButtonSubmit_exam = (Button) view.findViewById(R.id.button_dialog_submit_exam);
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
// final EditText editTextKorean = (EditText) view.findViewById(R.id.edittext_dialog_korean);
ButtonSubmit_exam.setText("입력하기");
number_exam.setText(data1);
final AlertDialog dialog = builder.create();
dialog.show();
//dialog에 나타나는 입력하기 버튼을 눌렀을 때 발생하는 상황
ButtonSubmit_exam.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strID = number_exam.getText().toString();
String strID2 = content_exam.getText().toString();
String strID3 = content_exam2.getText().toString();
//number와 content view에 입력한 문자열을 strID, strID2에 담는다.
//String strKorean = editTextKorean.getText().toString();
calenderArrayList dict = new calenderArrayList(strID, strID2, strID3);
bArrayList.add(0, dict);
mArrayList.add(0, dict); //첫 줄에 삽입
//mArrayList.add(dict); //마지막 줄에 삽입
mAdapter.notifyDataSetChanged(); //변경된 데이터를 화면에 반영
Log.d("b사이즈", "" + bArrayList.size());
Log.d("m사이즈", "" + mArrayList.size());
dialog.dismiss();
//dialog를 종료 시켜준다.
}
});
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Toast.makeText(getApplicationContext(), "onPause()", Toast.LENGTH_SHORT).show();
SharedPreferences calendersave = getSharedPreferences("calender", MODE_PRIVATE);
SharedPreferences.Editor calendersaveeditor = calendersave.edit();
//calenderArrayList calenderArrayList = new calenderArrayList();
if (bArrayList.size() != 0) {
for (int i = 0; i < bArrayList.size(); i++) {
calendersaveeditor.putBoolean("save_box" + i, bArrayList.get(i).selected);
calendersaveeditor.putString("save_date" + i, bArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work" + i, bArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place" + i, bArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", bArrayList.size());
calendersaveeditor.commit();
Log.d("종료시b사이즈", "" + bArrayList.size());
Log.d("종료시m사이즈", "" + mArrayList.size());
}
} else if (bArrayList.size() == 0) {
calendersaveeditor.clear();
calendersaveeditor.commit();
}
Log.d("스케쥴선택액티비티", "OnPause()실행");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
// Toast.makeText(getApplicationContext(), "onStop()", Toast.LENGTH_SHORT).show();
/*
* if(mArrayList.size()!=0){
for(int i = 0; i< mArrayList.size(); i++){
calendersaveeditor.putBoolean("save_box"+i, mArrayList.get(i).selected);
calendersaveeditor.putString("save_date"+i, mArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work"+i, mArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place"+i, mArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", mArrayList.size());
calendersaveeditor.commit();
}
}
else if(mArrayList.size()==0){
calendersaveeditor.clear();
calendersaveeditor.commit();
}
*/
Log.d("스케쥴선택액티비티", "OnStop()실행");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
// Toast.makeText(getApplicationContext(), "onRestart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnRestart()실행");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Toast.makeText(getApplicationContext(), "onDestroy()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnDestroy()실행");
}
}
First you need to add new entry in your existing mArrayList as i am can see from your code you are adding all existing entries again but not new entry.
After that you need to set adapter again with new mArrayList only then you will be able to see new data in your recycler view.

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());

How to get previous month's days on the gridview (Calendar)

I need help on how to go about and make prev month's days visible (grayed out) on this calendar.
I am getting a present months view here.. but as you can see the previous months days are not visible.I know why.. but how to go about it? also few bugs are there in this present one as well.please help.Posting the code for the custom adapter class:
CalendarAdapter.java
import java.util.ArrayList;
import java.util.Calendar;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CalendarAdapter extends BaseAdapter {
static final int FIRST_DAY_OF_WEEK =0; // Sunday = 0, Monday = 1
private Context mContext;
private java.util.Calendar month;
private Calendar selectedDate;
private ArrayList<String> items;
public CalendarAdapter(Context c, Calendar monthCalendar) {
month = monthCalendar;
selectedDate = (Calendar)monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
refreshDays();
}
public void setItems(ArrayList<String> items) {
for(int i = 0;i != items.size();i++){
if(items.get(i).length()==1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
public int getCount() {
return days.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView)v.findViewById(R.id.date);
// disable empty days from the beginning
if(days[position].equals("")) {
dayView.setClickable(false);
dayView.setFocusable(false);
//need to show previous months date
}
else {
// mark current day as focused
if(month.get(Calendar.YEAR)== selectedDate.get(Calendar.YEAR) && month.get(Calendar.MONTH)== selectedDate.get(Calendar.MONTH) && days[position].equals(""+selectedDate.get(Calendar.DAY_OF_MONTH))) {
v.setBackgroundResource(R.drawable.date_area);
dayView.setTextColor(Color.parseColor("#FFFFFF"));
}
else {
v.setBackgroundResource(R.drawable.current_date_area);
}
}
dayView.setText(days[position]);
// create date string for comparison
String date = days[position];
if(date.length()==1) {
date = "0"+date;
}
String monthStr = ""+(month.get(Calendar.MONTH)+1);
if(monthStr.length()==1) {
monthStr = "0"+monthStr;
}
// show icon if date is not empty and it exists in the items array
/* ImageView iw = (ImageView)v.findViewById(R.id.date_icon);
if(date.length()>0 && items!=null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
}
else {
iw.setVisibility(View.INVISIBLE);
}*/
return v;
}
public void refreshDays()
{
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
// figure size of the array
if(firstDay==1){
days = new String[lastDay+(FIRST_DAY_OF_WEEK*6)];
}
else {
days = new String[lastDay+firstDay-(FIRST_DAY_OF_WEEK+1)];
}
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay>1) {
for(j=0;j<firstDay-FIRST_DAY_OF_WEEK;j++) {
days[j] = "";
}
}
else {
for(j=0;j<FIRST_DAY_OF_WEEK*6;j++) {
days[j] = "";
}
j=FIRST_DAY_OF_WEEK*6+1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
for(int i=j-1;i<days.length;i++) {
days[i] = ""+dayNumber;
dayNumber++;
}
}
// references to our items
public String[] days;}
and this is the Activity code on how i am using this adapter:
CalendarView.java
/*some code above*/
/*this is in the OnCreate block*/
adapter = new CalendarAdapter(this, month);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);
/*some code below*/
and heres my calendar view screen (grid):
CalendarView Screenshot:
To be straight and to the point,All i want is that blank boxes before 1st of the month be filled in with the previous month's last week's days
Declare another calendar
private java.util.Calendar month, prevMonth;
Add a clone to calendar in the constructor
prevMonth = (Calendar) month.clone();
prevMonth.roll(Calendar.MONTH, false);
Then replace the refreshDays with this one.This fills up the blank spaces with the days from the last month and the next month for the first and last week of the current month respectively.
public void refreshDays() {
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int) month.get(Calendar.DAY_OF_WEEK);
int maxweek = month.getActualMaximum(Calendar.WEEK_OF_MONTH);
Log.d("CalendarAdapter", String.valueOf(maxweek));
// figure size of the array
/*
* if (firstDay == 1) { days = new String[lastDay + (FIRST_DAY_OF_WEEK *
* 6)]; }
*
* else { days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK +
* 1)]; }
*/
days = new String[maxweek * 7];
int j = FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if (firstDay > 1) {
// can be made a bit faster if implemented without this following
// for loop for roll
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
prevMonth.roll(Calendar.DAY_OF_MONTH, false);
Log.d("CalendarAdapter",
"roll block: " + prevMonth.get(Calendar.DAY_OF_MONTH));
}
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
// days[j] = "";
prevMonth.roll(Calendar.DAY_OF_MONTH, true);
int dayPrev = prevMonth.get(Calendar.DAY_OF_MONTH);
days[j] = " " + String.valueOf(dayPrev) + " ";
Log.d("CalendarAdapter", "calculation:J if firstDay>1 -- " + j
+ " roll gives:" + dayPrev);
}
} else {
for (j = 0; j < FIRST_DAY_OF_WEEK * 6; j++) {
days[j] = "";
Log.d("CalendarAdapter", "calculation:J if firstDay<1 -- " + j);
}
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
boolean flag = false;
for (int i = j - 1; i < days.length; i++) {
days[i] = String.valueOf(dayNumber).trim() + ".";
if (flag)
days[i] = String.valueOf(dayNumber).trim();
if (dayNumber == lastDay) {
dayNumber = 0;
flag=true;
}
dayNumber++;
}
}
// references to our items
public String[] days;
}

Java.lang.NullPointerException when trying to declare a Spinner

public void directionSpinner (String directions []) {
//Does some stuff to assign namedDirections [0] and namedDirections[1] a value.
dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); //THIS IS LINE 87
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");
}
LogCat:
12-09 20:50:13.497: E/AndroidRuntime(857): FATAL EXCEPTION: main
12-09 20:50:13.497: E/AndroidRuntime(857): java.lang.NullPointerException
12-09 20:50:13.497: E/AndroidRuntime(857): at android.app.Activity.findViewById(Activity.java:1839)
12-09 20:50:13.497: E/AndroidRuntime(857): at com.nicotera.colton.londontransitguide.RoutesActivity.directionSpinner(RoutesActivity.java:87)
12-09 20:50:13.497: E/AndroidRuntime(857): at com.nicotera.colton.londontransitguide.MyInnerClass.onPostExecute(RoutesActivity.java:142)
12-09 20:50:13.497: E/AndroidRuntime(857): at com.nicotera.colton.londontransitguide.MyInnerClass.onPostExecute(RoutesActivity.java:1)
Anyways, route_direction_spinner is defined correctly. directionSpinner() runs after an AsyncTask is completed.
Entire Code:
package com.nicotera.colton.londontransitguide;
import java.io.IOException;
import java.text.DecimalFormat;
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.os.Handler;
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;
import android.widget.TextView;
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);
Log.i(TAG, "second spinner populated");
}
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 tc = new RoutesActivity();
tc.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");
}
}
Basically, this grabs some values from a transit website. This section of code so far just gets the direction of the route based off the route selected.
(Your directionSpinner() method is different in the two snippets you've posted, and I'm working using the one added later, but this solution should work for both snippets, assuming the problem is the same)
Your problem is that you're not following the Activity lifecycle properly.
When you call:
RoutesActivity tc = new RoutesActivity();
tc.directionSpinner(directions);
You are actually creating a brand new instance of RoutesActivity. And since you're calling it as a standard Java class, it never follows the Activity lifecycle, which means that onCreate() is never called, which in turn means that your two spinner objects remain null (as you assign values to them in onCreate()).
Due to this, when you use:
dirSpinner.setOnItemSelectedListener(this);
dirSpinner is actually null resulting in a NullPointerException.
Instead, try using:
RoutesActivity.this.directionSpinner(directions);
Instead of:
RoutesActivity tc = new RoutesActivity();
tc.directionSpinner(directions);

Two layouts, one disabled

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

Categories

Resources