Quiz Application - android

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.

Related

When using setOnGroupClickListener method report an error “cannot find symbol”

When using setOnGroupClickListener method report an error “cannot find symbol”,
I try to use setOnGroupClickListener to register sublist click event listener to list control,But an error is reported during compilation
error report:
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:142: error: cannot find symbol
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:143: error: method does not override or implement a method from a supertype
#Override
package com.mtb.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import com.xiaomi.mtb.*;
import com.xiaomi.mtb.activity.*;
import com.xiaomi.mtb.R;
import android.util.Log;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MtbNvAutoCheckList1Activity extends MtbBaseActivity {
private ArrayList<NvAutoCheckDataFather> groups = new ArrayList<>();
private ArrayList<ArrayList<NvAutoCheckDataSon>>children = new ArrayList<>();
private ArrayList<NvAutoCheckDataSon>data=new ArrayList<>();
private HashMap<Integer,Integer>hashMap=new HashMap<>();
private static int mNvEfsDataPrintMaxNum = 20;
private static final String LOG_TAG = "MtbNvAutoCheckMainActivity";
private static final int DATA_TYPE_DECIMALISM = 0;
private static int mHexOrDec = DATA_TYPE_DECIMALISM;
private static final int DATA_TYPE_HEX = 1;
private static final int SIGNED_DATA = 0;
private static final int UNSIGNED_DATA = 1;
private static boolean mTmpLogPrintFlag = false;
private ExpandableListView elvBook;
private NvAutoCheckBookAdapter adapter;
private static HashMap<Integer,byte[]>mNvData=new HashMap<Integer,byte[]>(){
{
put(550,new byte[]{8,(byte)138, 70, 115, 6, 98, 16, 5, 112});
put(74,new byte[]{6});
put(453,new byte[]{1});
}
};
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMtbHookAgent = MtbHookAgent.getHook();
int num=0;
Iterator<Map.Entry<Integer,byte[]>> iterator1=mNvData.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<Integer,byte[]>entry=iterator1.next();
int key=entry.getKey();
byte[] value=entry.getValue();
ByteBuffer byteBuf=mMtbHookAgent.onHookNvOptSync(0, key, mMtbHookAgent.EVENT_OEMHOOK_XIAOMI_NV_READ);
log("onNvEfsReadHookHdl, mNvId = "+key);
int ret = byteBuf.getInt();
int len = byteBuf.getInt();
log("onNvEfsReadHookHdl" + ", len = " + len);
byte[] bytes = null;
if(len<=0){
log("efs config empty");
}else{
bytes = new byte[len];
byteBuf.get(bytes);
}
String mNvFlagResult="false";
for(int i=0; i < value.length;i++){
if(entry.getValue()[i] != bytes[i]){
log("mNVDATA_"+key+"[" + i + "] not the same");
break;
}
log("mNVDATA_"+key+"[" + i + "] identical");
if(i == (value.length - 1)){
mNvFlagResult = "success";
}
}
groups.add(new NvAutoCheckDataFather(key,mNvFlagResult));
if(mNvFlagResult=="false"){
hashMap.put(num, hashMap.size());
NvAutoCheckDataSon mNvAutoCheckDataSon=new NvAutoCheckDataSon("正确的值是: "+onGetStringByByteGroup(value,value.length),"读出的值为: "+onGetStringByByteGroup(bytes,value.length));
children.add(new ArrayList<NvAutoCheckDataSon>(){
{
add(mNvAutoCheckDataSon);
}
});
}
num++;
}
// 利用布局资源文件设置用户界面
setContentView(R.layout.nv_auto_check_list1_config);
// 通过资源标识获得控件实例
elvBook = findViewById(R.id.elvBook);
// 创建适配器
adapter = new NvAutoCheckBookAdapter(this, groups, children, hashMap);
// 给列表控件设置适配器
elvBook.setAdapter(adapter);
// 给列表控件注册子列表单击事件监听器
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,long l){
if(!hashMap.containsKey(groupPosition)){
return true;
}else{
return false;
}
}
});
}
private static void log(String msg) {
Log.d(LOG_TAG, "MTB_ " + msg);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint) {
return onGetStringByDateType(val, uFlag, bPrint, mHexOrDec, true);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint, int hexOrDec, boolean fillHexZero) {
if (bPrint) {
tmpLog("onGetStringByDateType, byte, val = " + val + ", uFlag = " + uFlag + ", bPrint = " + bPrint + ", hexOrDec = " + hexOrDec + ", fillHexZero = " + fillHexZero);
}
String strVal = null;
BigDecimal bigVal;
byte lowVal = 0;
if (DATA_TYPE_HEX == hexOrDec) {
strVal = Integer.toHexString(val & 0xff);
if (1 == strVal.length() && fillHexZero) {
strVal = "0" + strVal;
}
if (bPrint) {
tmpLog("HEX, strVal = " + strVal);
}
} else {
strVal = "" + val;
if (UNSIGNED_DATA == uFlag && val < 0) {
lowVal = (byte)(val & 0x7f);
bigVal = BigDecimal.valueOf(lowVal).add(BigDecimal.valueOf(Byte.MAX_VALUE)).add(BigDecimal.valueOf(1));
strVal = bigVal.toString();
if (bPrint) {
tmpLog("val < 0, new strVal = " + strVal);
}
}
}
if (null != strVal) {
strVal = strVal.toUpperCase();
}
return strVal;
}
private String onGetStringByByteGroup(byte[] bytes, int len){
String ret="";
for(int i=0;i<len;i++){
String str1=onGetStringByDateType(bytes[i], UNSIGNED_DATA, false);
ret+=str1;
}
return ret;
}
private static void tmpLog(String msg) {
if (mTmpLogPrintFlag) {
log(msg);
}
}
}

IndexOutOfRangeException: Array index is out of range. DataCache.GetAchievementCacheData () (at Assets/Scripts/Mission/Plugin/DataCache.cs:329)

When I run the game using unity I get this error continuously in the console window and the loading screen is not going further next. Help me to fix this issue.
IndexOutOfRangeException: Array index is out of range.
DataCache.GetAchievementCacheData () (at
Assets/Scripts/Mission/Plugin/DataCache.cs:329)
Here is my code below
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;
//Class luu mission current
public class CurrentMission
{
public string FB_id { get; set; }
public string Name { get; set; }
public string Mission { get; set; }
public CurrentMission(string id, string name, string mission)
{
this.FB_id = id;
this.Name = name;
this.Mission = mission;
}
public CurrentMission()
{
this.FB_id = "";
this.Name = "";
this.Mission = "";
}
}
public class MissionDataSave
{
public int Mission;
public long Score;
public int Star;
public int Open;//0-false. 1-true
public MissionDataSave(int mission, long score, int star, int open)
{
Mission = mission;
Score = score;
Star = star;
Open = open;
}
public MissionDataSave()
{
Mission = 0;
Score = 0;
Star = 0;
Open = 0;
}
}
public class AchievementCache
{
//group nhiem vu
public int Group;
//Level hien tai cua group
public int Level;
//Gia tri hien tai
public int Value;
//Thong bao mission hoan thanh
public int Notify;//0 - False, 1 - true
//public AchievementCache()
//{
// this.Group = 1;
// this.Level = 1;
// this.Value = 0;
//}
public AchievementCache(int group, int level, int value, int notify)
{
this.Group = group;
this.Value = value;
this.Level = level;
this.Notify = notify;
}
public AchievementCache()
{
this.Group = 1;
this.Value = 0;
this.Level = 1;
this.Notify = 0;
}
}
public class DataCache
{
public static string FB_ID = "FB_ID";
public static string FB_USER = "FB_USER";
public static string Achievement_data_key = "Achievement_data_key";
public static string Mission_data_key = "Mission_data_key";
public static string Current_mission_data_key = "Current_mission_data_key";
public static AchievementCache[] dataAchievementCache;
public static MissionDataSave[] dataMissionCache;
public static CurrentMission[] dataCurrentMissionCache;
//public static string XML_Current_Mission_Path = "CurrentMissionSave.xml";
//public static string XML_Data_Mission_Path = "DataMissionSave.xml";
//public static string XML_Data_Achievement_Path = "AchievementCache.xml";
//serialize xml theo tung phan tu
//public static List<MissionDataSave> DeserializeMissionDataSaveListFromXML(string filePath)
//{
// if (!System.IO.File.Exists(filePath))
// {
// Debug.LogError("File " + filePath + " not exist!");
// return new List<MissionDataSave>();
// }
// XmlSerializer deserializer = new XmlSerializer(typeof(List<MissionDataSave>), new XmlRootAttribute("MissionDataSaveRoot"));
// TextReader textReader = new StreamReader(filePath);
// List<MissionDataSave> movies = (List<MissionDataSave>)deserializer.Deserialize(textReader);
// textReader.Close();
// return movies;
//}
//public static void readXMLTest()
//{
// string xmlDataCache1 = Application.persistentDataPath + "/" + XML_Current_Mission_Path;
// TextReader textReader = new StreamReader(xmlDataCache1);
// XmlDocument xmlDoc = new XmlDocument();
// xmlDoc.Load(textReader);
// XmlNodeList xmlNodeList = xmlDoc.DocumentElement.ChildNodes;
// Debug.Log("TRUOC");
// foreach (XmlNode node in xmlNodeList)
// {
// Debug.Log("aaaaaaaaaaaaaaaaaaaaa " + node.Attributes["Id"].Value);
// }
// Debug.Log("SAU");
// XmlNode root = xmlDoc.DocumentElement;
// XmlElement elem = xmlDoc.CreateElement("CurrentMissionCache");
// elem.SetAttribute("Id", "112312");
// elem.SetAttribute("Name", "NameDG");
// elem.SetAttribute("Mission", "MissionDG");
// root.AppendChild(elem);
// textReader.Close();
// xmlDoc.Save(xmlDataCache1);
//}
//Add mission xml node
public static void UpdateMissionScore(long score, int star, int mission, int open)
{
MissionDataSave data = dataMissionCache[mission - 1];
if (data.Star < star)
{
data.Star = star;
}
if (data.Score < score)
{
data.Score = score;
}
data.Open = open;
}
public static void SaveMissionDataCache(bool submitToServer = false)
{
string dataSave = "";
string dataSendServer = "";
for (int i = 0; i < dataMissionCache.Length; i++)
{
dataSave += dataMissionCache[i].Mission + "-" + dataMissionCache[i].Score + "-" + dataMissionCache[i].Star + "-" + dataMissionCache[i].Open + ",";
//Chi gui nhung mission da open len server
if (dataMissionCache[i].Open == 1)
{
if (dataSendServer.Length > 0)
dataSendServer += ",";
dataSendServer += dataMissionCache[i].Mission + "-" + dataMissionCache[i].Score + "-" + dataMissionCache[i].Star + "-" + dataMissionCache[i].Open;
}
}
Debug.Log("Data save " + dataSave);
PlayerPrefs.SetString(Mission_data_key, dataSave);
if (submitToServer)
{
Debug.Log("Data send server " + dataSendServer);
AudioControl.getMonoBehaviour().StartCoroutine(DHS.PostMeInfoMissionUpdate(FB.UserId, dataSendServer));
}
}
public static void GetMissionDataCache()
{
int max_mission = 100;
if (dataMissionCache != null)
{
dataMissionCache = null;
}
dataMissionCache = new MissionDataSave[max_mission];
//Tao moi neu chua co
if (!PlayerPrefs.HasKey(Mission_data_key))
{
string datas = "1-0-0-1,";
for (int i = 2; i <= max_mission; i++)
{
//Mission - Score - Star - Open
if (DataMissionControlNew.test)
{
datas += i + "-0-0-1,";
//if (i < 16)
// datas += i + "-0-0-1,";
//else datas += i + "-0-0-0,";
}
else
{
datas += i + "-0-0-0,";
}
}
PlayerPrefs.SetString(Mission_data_key, datas);
}
string missionData = PlayerPrefs.GetString(Mission_data_key);
string[] data = missionData.Split(',');
for (int i = 0; i < max_mission; i++)
{
string[] infoData = data[i].Split('-');
//Debug.Log("Info " + data[i]);
string mission = infoData[0];
string score = infoData[1];
string star = infoData[2];
string open = infoData[3];
dataMissionCache[i] = new MissionDataSave(Convert.ToUInt16(mission), Convert.ToUInt32(score), Convert.ToUInt16(star), Convert.ToUInt16(open));
}
}
//-------------------------CURRENT MISSION---------------------------
//Add current mission xml node
public static void SaveCurrentMission(string data = "")
{
if (String.IsNullOrEmpty(data))
{
string dataSave = "";
for (int i = 0; i < dataCurrentMissionCache.Length; i++)
{
if (dataSave.Length > 0)
dataSave += ",";
dataSave += dataCurrentMissionCache[i].FB_id + "-" + dataCurrentMissionCache[i].Name + "-" + dataCurrentMissionCache[i].Mission;
}
PlayerPrefs.SetString(Current_mission_data_key, dataSave);
}
else
{
PlayerPrefs.SetString(Current_mission_data_key, data);
GetCurrentMission();
}
}
public static void GetCurrentMission()
{
if (!PlayerPrefs.HasKey(Current_mission_data_key))
{
PlayerPrefs.SetString(Current_mission_data_key, "Me-User-1");
}
if (dataCurrentMissionCache != null)
{
dataCurrentMissionCache = null;
}
string current_data = PlayerPrefs.GetString(Current_mission_data_key);
string[] data = current_data.Split(',');
dataCurrentMissionCache = new CurrentMission[data.Length];
for (int i = 0; i < data.Length; i++)
{
string[] info = data[i].Split('-');
//fb - User name - missison
dataCurrentMissionCache[i] = new CurrentMission(info[0], info[1], info[2]);
}
}
public static void SetMeCurrentMission(int mission)
{
for (int i = 0; i < DataCache.dataCurrentMissionCache.Length; i++)
{
if ("Me".Equals(DataCache.dataCurrentMissionCache[i].FB_id))
{
int old = Convert.ToInt16(DataCache.dataCurrentMissionCache[i].Mission);
if (old < mission)
{
DataCache.dataCurrentMissionCache[i].Mission = "" + mission;
DataCache.UpdateMissionScore(0, 0, mission, 1);//Them mission moi vao xml
}
}
}
DataCache.SaveCurrentMission();
}
//-------------------------ACHIEVEMENT---------------------------
//Ghi de len du lieu cu
public static void ReplaceAchievementCache(int groupLevel, int value, int level = -1)
{
dataAchievementCache[groupLevel - 1].Value = value;
if (level != -1)
{
dataAchievementCache[groupLevel - 1].Level = level;
}
}
//Cap nhat them du lieu
public static void AddAchievementCache(int groupLevel, int addValue, int addLevel = 0)
{
dataAchievementCache[groupLevel - 1].Level += addLevel;
dataAchievementCache[groupLevel - 1].Value += addValue;
}
public static void GetAchievementCacheData()
{
Debug.Log("-------------GetAchievementCacheData--------------------");
if (dataAchievementCache != null)
{
dataAchievementCache = null;
}
dataAchievementCache = new AchievementCache[22];
//Tao achievement
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
string achi = "";
for (int i = 1; i <= 22; i++)
{
achi += i + "-1-0-0,";
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi);
}
string achievement = PlayerPrefs.GetString(Achievement_data_key);
//Debug.Log(achievement);
string[] achie = achievement.Split(',');
for (int i = 0; i< dataAchievementCache.Length; i++)
{
//Debug.Log(achie[i]);
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
string value = infoAchie[2];
string notify = infoAchie[3];
//Debug.Log(group +" " + dataAchievementCache[i].Group);
dataAchievementCache[i] = new AchievementCache();
dataAchievementCache[i].Group = Convert.ToInt16(group);
dataAchievementCache[i].Level = Convert.ToInt16(level);
dataAchievementCache[i].Value = Convert.ToInt32(value);
dataAchievementCache[i].Notify = Convert.ToInt16(notify);
}
}
public static void SaveAchievementCache(bool sendServer = false)
{
try
{
Debug.Log("-------------------SaveAchievementCache-----------------");
if (dataAchievementCache != null)
{
string achievement = "";
for (int i = 0; i < dataAchievementCache.Length; i++)
{
string s = "" + dataAchievementCache[i].Group + "-" + dataAchievementCache[i].Level + "-" + dataAchievementCache[i].Value + "-" + dataAchievementCache[i].Notify + ",";
achievement += s;
}
//Debug.Log("----------LUU ACHIEVEMENT------------ " + achievement);
PlayerPrefs.SetString(Achievement_data_key, achievement);
if (FB.IsLoggedIn && sendServer)
{
//Nếu chưa có playerprefs thì sẽ submit lên luôn
//Nếu có rồi thì phải check nó cập nhật hoàn thành từ server về thì mới cho up lên
bool check = !PlayerPrefs.HasKey(DataMissionControlNew.key_update_achievement_data_from_server) ||
(PlayerPrefs.HasKey(DataMissionControlNew.key_update_achievement_data_from_server) && PlayerPrefs.GetInt(DataMissionControlNew.key_update_achievement_data_from_server) == 1);
if (check)
{
AudioControl.getMonoBehaviour().StartCoroutine(DHS.PostMeInfoUpdate(DFB.UserId, "" + VariableSystem.diamond, "" + achievement, "", (www) =>
{
Debug.Log("----------Update achievement to server success!------------- " + achievement);
}));
}
else
{
Debug.Log("----------KHONG CHO UP ACHIEVEMENT VA DIAMOND LEN SERVER------------- " + PlayerPrefs.GetInt(DataMissionControlNew.key_update_mission_data_from_server, 0));
}
}
}
}
catch (Exception e)
{
Debug.Log("------------ERROR ---------------" + e.Message);
if (DataMissionControlNew.test)
{
MobilePlugin.getInstance().ShowToast("ERROR " + e.Message);
}
}
}
public static void DeleteUserData()
{
PlayerPrefs.DeleteKey(FB_ID);
PlayerPrefs.DeleteKey(Mission_data_key);
PlayerPrefs.DeleteKey(Current_mission_data_key);
PlayerPrefs.DeleteKey(Achievement_data_key);
PlayerPrefs.DeleteKey("diamond");
PlayerPrefs.DeleteKey(DataMissionControlNew.key_update_mission_data_from_server);
VariableSystem.diamond = 8;
VariableSystem.heart = 5;
}
public static void RestoreUserData(int diamond, string achievement)
{
Debug.Log("Restore user data");
VariableSystem.diamond = diamond;
VariableSystem.heart = PlayerPrefs.GetInt("heart", 5);
string[] achie = achievement.Split(',');
if (achie.Length > 5)
{
for (int i = 0; i < dataAchievementCache.Length; i++)
{
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
string value = infoAchie[2];
string notify = infoAchie[3];
dataAchievementCache[i].Group = Convert.ToInt16(group);
dataAchievementCache[i].Level = Convert.ToInt16(level);
dataAchievementCache[i].Value = Convert.ToInt32(value);
dataAchievementCache[i].Notify = Convert.ToInt16(notify);
}
//Debug.Log("---Luu achievement----");
SaveAchievementCache();
GetAchievementCacheData();
}
Debug.Log("----------------ACHIEVEMENT da dc cap nhat tu -----------------");
PlayerPrefs.SetInt(DataMissionControlNew.key_update_achievement_data_from_server, 1);
}
The line 329 is this
string level = infoAchie[1];
The problem is coming from the last comma you are adding in the string you are adding to your PlayerPrefs in this part:
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
string achi = "";
for (int i = 1; i <= 22; i++)
{
achi += i + "-1-0-0,";
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi);
}
This code generates this string:
1-1-0-0,2-1-0-0,3-1-0-0,4-1-0-0,5-1-0-0,6-1-0-0,7-1-0-0,8-1-0-0,9-1-0-0,10-1-0-0,11-1-0-0,12-1-0-0,13-1-0-0,14-1-0-0,15-1-0-0,16-1-0-0,17-1-0-0,18-1-0-0,19-1-0-0,20-1-0-0,21-1-0-0,22-1-0-0,
Keep in memory that last comma at the end of the string.
You are later doing a split on the ',' character, and iterating over them.
string[] achie = achievement.Split(',');
for (int i = 0; i< dataAchievementCache.Length; i++)
{
//Debug.Log(achie[i]);
string[] infoAchie = achie[i].Split('-');
string group = infoAchie[0];
string level = infoAchie[1];
...
}
The problem is that by doing so, your achie string array contains an empty last element. So when you are later splitting on the "-" character, your infoAchie string array only contains one element: the empty string. The first line:
string group = infoAchie[0];
Still works, but is filled with the empty string. Then:
string level = infoAchie[1];
Can't work, as you are indeed out of the bounds of the infoAchie array.
The solution would be to add the comma to your string only if it is not the last element.
Also, I strongly advise you to use a StringBuilder over a simple string for optimization purposes. Your code could then look like, for instance:
if (!PlayerPrefs.HasKey(Achievement_data_key))
{
StringBuilder achi = new StringBuilder();
for (int i = 1; i <= 22; i++)
{
achi.Append(i).Append("-1-0-0");
if(i != 22)
achi.Append(",");
}
//Debug.Log("Create new achievement " + achi);
PlayerPrefs.SetString(Achievement_data_key, achi.ToString());
}
Which generates this string:
1-1-0-0,2-1-0-0,3-1-0-0,4-1-0-0,5-1-0-0,6-1-0-0,7-1-0-0,8-1-0-0,9-1-0-0,10-1-0-0,11-1-0-0,12-1-0-0,13-1-0-0,14-1-0-0,15-1-0-0,16-1-0-0,17-1-0-0,18-1-0-0,19-1-0-0,20-1-0-0,21-1-0-0,22-1-0-0

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

R.string provides me numbers

I have this code which is not working:
public class MainActivity extends AppCompatActivity {
int quantity=2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i( "MainActivity", "modriodfw" + (R.string.Thankyou));
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
EditText nombre = (EditText) findViewById(R.id.nombre);
String nombre1 = nombre.getText().toString();
boolean cream = getstate();
boolean chocolate = getcState();
int price = calculatePrice(cream, chocolate);
String summary = createOrderSummary(price, cream,chocolate,nombre1);
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, (R.string.OrderMail) + nombre1);
intent.putExtra(Intent.EXTRA_TEXT, summary);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
displayMessage(summary);
}
public void clearText(View view)
{
EditText nombre = (EditText) findViewById(R.id.nombre);
nombre.setText("");
}
private boolean getcState()
{
CheckBox state = (CheckBox) findViewById(R.id.chocolate);
boolean chocolateState = state.isChecked();
return chocolateState;
}
private boolean getstate()
{
CheckBox state = (CheckBox) findViewById(R.id.cream);
boolean creamState = state.isChecked();
return (creamState);
}
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = (R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + (R.string.name);
}
if(chocolate && cream == false){
summary += "\n" + quantity + (R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + (R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + (R.string.Thankyou);
return summary;
}
private int calculatePrice(boolean cream, boolean chocolate) {
int price = 5;
if (cream) {
price = price + 1;
}
if (chocolate) {
price = price + 2;
}
price = price * quantity;
return price;
}
public void increase(View view) {
if (quantity == 99){
Toast.makeText(this, (R.string.high), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity + 1;
display(quantity);
}
public void decrease(View view){
if (quantity == 1){
Toast.makeText(this, (R.string.less), Toast.LENGTH_SHORT).show();
return;
}
quantity= quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int numb) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText("" + numb);
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String Summary) {
TextView summaryTextView = (TextView) findViewById(R.id.Summary_text_view);
summaryTextView.setText(Summary);
}
and all I get is this:
2131099680
Total: $10
2131099676
and it should be
Name:
summary
total $
Thank You!
im using java in android studio.
You need to do context.getString(R.string.your_string), as R.string.your_string on its own is just a reference.
You have forgotten to call getString method in four places. I update your code :
private String createOrderSummary(int price, boolean cream, boolean chocolate,String nombre1)
{
String summary = getString(R.string.name) + nombre1;
if(cream && chocolate == false){
summary += "\n" + quantity + getString(R.string.SummaryChocolate);
}
if(chocolate && cream == false){
summary += "\n" + quantity + getString(R.string.SummaryCream);
}
if(chocolate && cream){
summary += "\n" + quantity + getString(R.string.SummaryBoth);
}
summary += "\nTotal: $" +price;
summary += "\n" + getString(R.string.Thankyou);
return summary;
}`enter code here`

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