Android Studio Java infix to postfix calculations decimal point gives crash - android

I was trying to make a calculator for my university homework. to calculate the results I use infix to postfix convention. but this code doesn't take only decimal point (.) as a result, it crashes whenever I put (.) as input like 1.1+ it crashes. In the operator section there is no part for decimal point this is happening for that. but I was confused about how to resolve this.
run log!
class Solution {
public double calculate(String s) {
if (s == null || s.length() < 1) return Integer.MIN_VALUE;
return evalSuffix(inToSuffix(s));
}
public int rank(Character op) {
switch (op) {
case '+': return 1;
case '-': return 1;
case '*': return 2;
case '/': return 2;
case '%': return 2;
case '^': return 3; //you can add more operators
default: return 0; //priority for '('
}
}
public List<Object> inToSuffix(String s) {
Stack<Character> opStack = new Stack<>();
List<Object> suffix = new LinkedList<>();
double num = 0;
boolean numCached = false;
char[] chars = s.toCharArray();
for (char c : chars) {
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
numCached = true;
}
else {
if (numCached) {
suffix.add(num);
num = 0;
numCached = false;
}
if (c == ' ' || c == '\t') continue;
if (c == '(') opStack.push('(');
else if (c == ')') {
while (opStack.peek() != '(') suffix.add(opStack.pop()); //op in () should be added first
opStack.pop();
}
else {
while (!opStack.isEmpty() && rank(c) <= rank(opStack.peek())) suffix.add(opStack.pop());
opStack.push(c);
}
}
}
if (numCached) suffix.add(num);
while (!opStack.isEmpty()) suffix.add(opStack.pop());
return suffix;
}
public double evalSuffix(List<Object> suffix) {
Stack<Double> numStack = new Stack<>();
double num1 = 0;
double num2 = 0;
for (Object o : suffix) {
if (o instanceof Character) {
char op = (Character)o;
num2 = numStack.pop();
num1 = numStack.pop();
switch (op) {
case '+': numStack.push(num1 + num2); break;
case '-': numStack.push(num1 - num2); break;
case '*': numStack.push(num1 * num2); break;
case '/': numStack.push(num1 / num2); break;
case '%': numStack.push(num1 % num2); break;
case '^': numStack.push((double)Math.pow((double)num1, (double)num2)); break;
}
}
else numStack.push((Double) o);
}
return numStack.pop();
}
}
Also, you can provide a better solution if you have any!!

This works fine for m!~
ExpCalculator{
public static double evalPostfix(String postfixExp){
int index = 0;
Stack<Double> arr = new Stack<Double>();
double result = 0;
for(int i = 0; i < postfixExp.length(); i++)
{
char c = postfixExp.charAt(i);
if(c == ' ')
continue;
else if(Character.isDigit(c))
{
double x = 0.0;
boolean check = true;
while(Character.isDigit(c) || c == '.')
{
if(c!= '.' && check == true){
x = x*10 + (double)(c-'0');
i++;
c = postfixExp.charAt(i);
}
else{
check = false;
x = x + 0.1 + (double)(c-'0')/10;
i++;
c = postfixExp.charAt(i);
}
}
i--;
arr.push(x);
}
else
{
double val1 = arr.pop();
double val2 = arr.pop();
switch(c)
{
case '+':
arr.push(val2+val1);
break;
case '-':
arr.push(val2- val1);
break;
case '/':
if (val1 == 0)throw new ArithmeticException();
arr.push(val2/val1);
break;
case '*':
arr.push(val2*val1);
break;
case '^':
for(int x = 1; x< val1; x++)val2*=val2;
arr.push(val2);
break;
default:
throw new ArithmeticException();
}
}
}
return arr.pop();
}
public static String infixToPostfix(String exp){
String result = "";
Stack<Character> arr = new Stack<>();
for (int i = 0; i <exp.length() ; i++) {
char c = exp.charAt(i);
if(precedence(c)>0){
while(arr.isEmpty()==false && precedence(arr.peek())>=precedence(c)){
result += arr.pop();
}
result += ' ';
arr.push(c);
}else if(c==')'){
char x = arr.pop();
while(x!='('){
result += x;
x = arr.pop();
}
}else if(c=='('){
arr.push(c);
}else{
result += c;
}
}
for (int i = 0; i <=arr.size() ; i++) {
result += arr.pop();
}
return result;
}
static int precedence(char c){
switch (c){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
}

Related

How to compare images in android?

`public class MainActivity extends AppCompatActivity {
Button btn_card;
ImageView iv_cpu_card0, iv_cpu_card1, iv_cpu_card2, iv_cpu_card3, iv_player_card0,
iv_player_card1, iv_player_card2, iv_player_card3, iv_center_triple, iv_card_center;
TextView tv_size;
TextView tv_player;
TextView tv_cpu;
ArrayList<Integer> deck = new ArrayList<>();
ArrayList<Integer> centerCards = new ArrayList<>();
ArrayList<Integer> cpuCards = new ArrayList<>();
ArrayList<Integer> playerCards = new ArrayList<>();
Random random = new Random();
int centerScore = 0, cpuScore = 0, playerScore = 0;
int cpu_card0 = 0, cpu_card1 = 0, cpu_card2 = 0, cpu_card3 = 0,
player_card0 = 0, player_card1 = 0, player_card2 = 0, player_card3 = 0,
card_center = 0, triple0 = 0, triple1 = 0, triple2 = 0, cValue = 0, playerCardSize = 0,
cpuCardSize = 0, centerCardSize = 0;
Handler handler = new Handler();
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
setContentView(R.layout.activity_main);
btn_card = findViewById(R.id.btn_card);
iv_cpu_card0 = findViewById(R.id.iv_cpu_card0);
iv_cpu_card1 = findViewById(R.id.iv_cpu_card1);
iv_cpu_card2 = findViewById(R.id.iv_cpu_card2);
iv_cpu_card3 = findViewById(R.id.iv_cpu_card3);
iv_player_card0 = findViewById(R.id.iv_player_card0);
iv_player_card1 = findViewById(R.id.iv_player_card1);
iv_player_card2 = findViewById(R.id.iv_player_card2);
iv_player_card3 = findViewById(R.id.iv_player_card3);
iv_card_center = findViewById(R.id.iv_card_center);
iv_center_triple = findViewById(R.id.iv_center_triple);
tv_size = findViewById(R.id.tv_size);
tv_player = findViewById(R.id.tv_player);
tv_cpu = findViewById(R.id.tv_cpu);
//btn_card.setVisibility(View.INVISIBLE);
deck.add(R.drawable.d_01); deck.add(R.drawable.d_02); deck.add(R.drawable.d_03);
deck.add(R.drawable.d_04); deck.add(R.drawable.d_05); deck.add(R.drawable.d_06);
deck.add(R.drawable.d_07); deck.add(R.drawable.d_08); deck.add(R.drawable.d_09);
deck.add(R.drawable.d_10); deck.add(R.drawable.d_11); deck.add(R.drawable.d_12);
deck.add(R.drawable.d_13); deck.add(R.drawable.s_01); deck.add(R.drawable.s_02);
deck.add(R.drawable.s_03); deck.add(R.drawable.s_04); deck.add(R.drawable.s_05);
deck.add(R.drawable.s_06); deck.add(R.drawable.s_07); deck.add(R.drawable.s_08);
deck.add(R.drawable.s_09); deck.add(R.drawable.s_10); deck.add(R.drawable.s_11);
deck.add(R.drawable.s_12); deck.add(R.drawable.s_13); deck.add(R.drawable.c_01);
deck.add(R.drawable.c_02); deck.add(R.drawable.c_03); deck.add(R.drawable.c_04);
deck.add(R.drawable.c_05); deck.add(R.drawable.c_06); deck.add(R.drawable.c_07);
deck.add(R.drawable.c_08); deck.add(R.drawable.c_09); deck.add(R.drawable.c_10);
deck.add(R.drawable.c_11); deck.add(R.drawable.c_12); deck.add(R.drawable.c_13);
deck.add(R.drawable.h_01); deck.add(R.drawable.h_02); deck.add(R.drawable.h_03);
deck.add(R.drawable.h_04); deck.add(R.drawable.h_05); deck.add(R.drawable.h_06);
deck.add(R.drawable.h_07); deck.add(R.drawable.h_08); deck.add(R.drawable.h_09);
deck.add(R.drawable.h_10); deck.add(R.drawable.h_11); deck.add(R.drawable.h_12);
deck.add(R.drawable.h_13);
Game();
//writeCardId(deck);
tv_size.setText("Array Size: " + deck.size());
/*iv_player_card0.setOnClickListener(v->{
iv_player_card0.setImageResource(random.nextInt());
});*/
}
private void writeCardId(ArrayList<Integer> deck){
String deckCode;
FileOutputStream fos = null;
try {
fos = openFileOutput("derzinek.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fos);
for (int i = 0; i < deck.size(); i++) {
deckCode = deck.get(i)+"\n";
outputWriter.write(deckCode);
}
outputWriter.close();
Toast.makeText(this, "Saved to " + getFilesDir() + "/" + "derzinek.txt",
Toast.LENGTH_LONG).show();
} catch(IOException e){
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#SuppressLint("SetTextI18n")
private void Game() {
card_center = random.nextInt(deck.size()-1);
iv_card_center.setImageResource(deck.get(card_center));
centerScore += cardValue(deck.get(card_center));
centerCardSize++;
deck.remove(card_center);
triple0 = random.nextInt(deck.size()-1);
centerScore += cardValue(deck.get(triple0));
centerCardSize++;
deck.remove(triple0);
triple1 = random.nextInt(deck.size()-1);
centerScore += cardValue(deck.get(triple1));
centerCardSize++;
deck.remove(triple1);
triple2 = random.nextInt(deck.size()-1);
centerScore += cardValue(deck.get(triple2));
centerCardSize++;
deck.remove(triple2);
centerCards.add(deck.get(triple0));
centerCards.add(deck.get(triple1));
centerCards.add(deck.get(triple2));
centerCards.add(deck.get(card_center));
cpu_card0 = random.nextInt(deck.size()-1);
cpuCards.add(deck.get(cpu_card0));
deck.remove(cpu_card0);
cpu_card1 = random.nextInt(deck.size()-1);
cpuCards.add(deck.get(cpu_card1));
deck.remove(cpu_card1);
cpu_card2 = random.nextInt(deck.size()-1);
cpuCards.add(deck.get(cpu_card2));
deck.remove(cpu_card2);
cpu_card3 = random.nextInt(deck.size()-1);
cpuCards.add(deck.get(cpu_card3));
deck.remove(cpu_card3);
player_card0 = random.nextInt(deck.size()-1);
iv_player_card0.setImageResource(deck.get(player_card0));
playerCards.add(deck.get(player_card0));
deck.remove(player_card0);
player_card1 = random.nextInt(deck.size()-1);
iv_player_card1.setImageResource(deck.get(player_card1));
playerCards.add(deck.get(player_card1));
deck.remove(player_card1);
player_card2 = random.nextInt(deck.size()-1);
iv_player_card2.setImageResource(deck.get(player_card2));
playerCards.add(deck.get(player_card2));
deck.remove(player_card2);
player_card3 = random.nextInt(deck.size()-1);
iv_player_card3.setImageResource(deck.get(player_card3));
playerCards.add(deck.get(player_card3));
deck.remove(player_card3);
tv_size.setText("Array Size: " + deck.size());
cValue = cardValue(centerCards.get(centerCards.size()-1));
tv_player.setText(centerCards.get(centerCards.size()-1)+"");
iv_player_card0.setOnClickListener(v -> {
if (isEqual(cValue) == isEqual(playerCards.get(0))) {
playerScore += centerScore + cardValue(playerCards.get(0));
tv_player.setText("PLAYER: " + playerScore);
playerCardSize += centerCardSize;
centerCardSize = 0;
centerScore = 0;
iv_player_card0.setVisibility(View.INVISIBLE);
iv_center_triple.setVisibility(View.INVISIBLE);
iv_card_center.setVisibility(View.INVISIBLE);
centerCards.clear();
} else {
centerScore += cardValue(playerCards.get(0));
iv_card_center.setImageResource(playerCards.get(0));
iv_card_center.setVisibility(View.VISIBLE);
iv_player_card0.setVisibility(View.INVISIBLE);
centerCardSize++;
tv_player.setText("PLAYER: " + playerScore);
}
cpuTurn();
});
iv_player_card1.setOnClickListener(v -> {
if (isEqual(cValue) == isEqual(playerCards.get(1))) {
playerScore += centerScore + cardValue(playerCards.get(1));
tv_player.setText("PLAYER: " + playerScore);
playerCardSize += centerCardSize;
centerCardSize = 0;
centerScore = 0;
iv_player_card1.setVisibility(View.INVISIBLE);
iv_center_triple.setVisibility(View.INVISIBLE);
iv_card_center.setVisibility(View.INVISIBLE);
centerCards.clear();
} else {
centerScore += cardValue(playerCards.get(1));
iv_card_center.setImageResource(playerCards.get(1));
iv_card_center.setVisibility(View.VISIBLE);
iv_player_card1.setVisibility(View.INVISIBLE);
centerCardSize++;
tv_player.setText("PLAYER: " + playerScore);
}
cpuTurn();
});
iv_player_card2.setOnClickListener(v -> {
if (isEqual(cValue) == isEqual(playerCards.get(2))) {
playerScore += centerScore + cardValue(playerCards.get(2));
tv_player.setText("PLAYER: " + playerScore);
playerCardSize += centerCardSize;
centerCardSize = 0;
centerScore = 0;
iv_player_card2.setVisibility(View.INVISIBLE);
iv_center_triple.setVisibility(View.INVISIBLE);
iv_card_center.setVisibility(View.INVISIBLE);
centerCards.clear();
} else {
centerScore += cardValue(playerCards.get(2));
iv_card_center.setImageResource(playerCards.get(2));
iv_card_center.setVisibility(View.VISIBLE);
iv_player_card2.setVisibility(View.INVISIBLE);
centerCardSize++;
tv_player.setText("PLAYER: " + playerScore);
}
cpuTurn();
});
iv_player_card3.setOnClickListener(v -> {
if (isEqual(cValue) == isEqual(playerCards.get(3))) {
playerScore += centerScore + cardValue(playerCards.get(3));
tv_player.setText("PLAYER: " + playerScore);
playerCardSize += centerCardSize;
centerCardSize = 0;
centerScore = 0;
iv_player_card3.setVisibility(View.INVISIBLE);
iv_center_triple.setVisibility(View.INVISIBLE);
iv_card_center.setVisibility(View.INVISIBLE);
centerCards.clear();
} else {
centerScore += cardValue(playerCards.get(3));
iv_card_center.setImageResource(playerCards.get(3));
iv_card_center.setVisibility(View.VISIBLE);
iv_player_card3.setVisibility(View.INVISIBLE);
centerCardSize++;
tv_player.setText("PLAYER: " + playerScore);
}
cpuTurn();
});
//Deal
if(cpuCards.size()==0 && playerCards.size()==0){
Game();
}
//Game Over
if(deck.size()==0){
btn_card.setVisibility(View.VISIBLE);
}
//New Game
btn_card.setOnClickListener(v ->{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
//Game();
});
}
private int cardValue(int deckValue){
int value;
switch (deckValue){
case 2131165280:
case 2131165365:
case 2131165290:
case 2131165381:
case 2131165391:
case 2131165355:
case 2131165378:
case 2131165368:
value = 1;
break;
case 2131165289:
value = 3;
break;
case 2131165356:
value = 2;
break;
default:
value = 0;
break;
}
return value;
}
private int isEqual(int deckValue){
//check equality of cpu/player cards with centerCard
switch (deckValue) {
case 2131165280:
case 2131165381:
case 2131165355:
case 2131165368:
deckValue = 1;
break;
case 2131165281:
case 2131165382:
case 2131165356:
case 2131165369:
deckValue = 2;
break;
case 2131165282:
case 2131165383:
case 2131165357:
case 2131165370:
deckValue = 3;
break;
case 2131165283:
case 2131165384:
case 2131165358:
case 2131165371:
deckValue = 4;
break;
case 2131165284:
case 2131165385:
case 2131165359:
case 2131165372:
deckValue = 5;
break;
case 2131165285:
case 2131165386:
case 2131165360:
case 2131165373:
deckValue = 6;
break;
case 2131165286:
case 2131165387:
case 2131165361:
case 2131165374:
deckValue = 7;
break;
case 2131165287:
case 2131165388:
case 2131165362:
case 2131165375:
deckValue = 8;
break;
case 2131165288:
case 2131165389:
case 2131165363:
case 2131165376:
deckValue = 9;
break;
case 2131165289:
case 2131165390:
case 2131165364:
case 2131165377:
deckValue = 10;
break;
case 2131165290:
case 2131165391:
case 2131165365:
case 2131165378:
deckValue = 11;
break;
case 2131165291:
case 2131165392:
case 2131165366:
case 2131165379:
deckValue = 12;
break;
case 2131165292:
case 2131165393:
case 2131165367:
case 2131165380:
deckValue = 13;
break;
default:
deckValue = 0;
break;
}
return deckValue;
}
#SuppressLint("SetTextI18n")
private void cpuTurn(){
iv_player_card0.setEnabled(false);
iv_player_card1.setEnabled(false);
iv_player_card2.setEnabled(false);
iv_player_card3.setEnabled(false);
for (int i = 0; i < cpuCards.size(); i++) {
if (isEqual(cValue) == isEqual(cpuCards.get(i))) {
iv_card_center.setImageResource(cpuCards.get(i));
cpuScore += centerScore + cardValue(cpuCards.get(i));
tv_cpu.setText("CPU: " + cpuScore);
cpuCardSize += centerCardSize;
centerCardSize = 0;
centerScore = 0;
handler.postDelayed(() -> {
}, 500);
centerCards.clear();
iv_player_card0.setEnabled(true);
iv_player_card1.setEnabled(true);
iv_player_card2.setEnabled(true);
iv_player_card3.setEnabled(true);
break;
} else if(cValue==2131165280||cValue==2131165290||cValue==2131165381||cValue==2131165391||
cValue==2131165355||cValue==2131165365||cValue==2131165368||cValue==2131165378){
cpuScore += centerScore + 1;
tv_cpu.setText("CPU: " + cpuScore);
cpuCardSize += centerCardSize;
centerCardSize = 0;
centerScore = 0;
iv_player_card0.setEnabled(true);
iv_player_card1.setEnabled(true);
iv_player_card2.setEnabled(true);
iv_player_card3.setEnabled(true);
break;
}else{
int cpuRandomCard = 0;
if(cpuCards.size()>0){
cpuRandomCard = random.nextInt(cpuCards.size()-1);
}
centerScore += cardValue(cValue);
tv_cpu.setText("CPU: "+cpuScore);
iv_card_center.setImageResource(cpuCards.get(cpuRandomCard));
centerCardSize++;
iv_player_card0.setEnabled(true);
iv_player_card1.setEnabled(true);
iv_player_card2.setEnabled(true);
iv_player_card3.setEnabled(true);
}
}
}
}`I'm new at android developing and need your help. I searched almost all questions similiar to mine I'm asking. Trying to develop a card game which has a deck of card. I put the images to drawable folder (R.drawable.h_01 --> Ace of Heart). Game is for two: Player and CPU. Both will start with 4 cards and another four cards will be on the table. One will be face up and other three are face down. If CPU or player has the same card (let's say face up card is 10 of Diamond and player/CPU has 10 of any suit) with face up card on the table, it will get the total points of the cards and those four cards will be moved to winner stack.
How can I compare face up card with player's/CPU's cards and every time player/CPU puts a card on the table?
I hope I made it clear.
PS: Whenever card(s) has/have been taken by player/CPU must be removed from deck.

Hevc video stream Media Codec Half of video is broken when receive 2 I frame consecutively

I'm trying to decode packages from Hevc Stream raw, then I receive 2 I Frames in a row because NaluType returns value 19 twice. Then half of the video is broken. I'm using Media Codec. How can I split the packages the hevc live video to render video without broken image? I've concatenated 2 I Frame but half of the video still broken.
private static final byte[] NALUStartCode = {0x00,0x00,0x00,0x01};
private boolean gotVPS = false;
private boolean gotPPS = false;
private boolean gotSPS = false;
private byte[] vspSet;
int temp;
private byte[] idrSet;
public DataStruct(byte[] data, long mTimeNum, boolean isParams) {
this.mVideoData = data;
this.mTimeNum = mTimeNum;
this.isParams = isParams;
}
private void splitRtpPackage(DataStruct hevcStruct) {
if (hevcStruct == null) {
return;
}
byte[] totalBytes = hevcStruct.getVideoData();
int payloadSize = totalBytes.length;
if (payloadSize > 8) {
byte[] hevcRaw = Arrays.copyOfRange(totalBytes, 12, totalBytes.length);
long timestamp = bytesToInt(Arrays.copyOfRange(totalBytes, 2, 10));
int check = totalBytes[1];
if (check != 2) {
stopSplitter();
return;
}
// extract the bit 2nd -> 6th from byte 1st
int nalType = (hevcRaw[0] >> 1) & 0x3f;
if ((9 < nalType && nalType < 16) || (21 < nalType && nalType < 32) || nalType > 40) {
return;
}
switch (nalType) {
case 32: //vps
this.vspSet = null;
this.vspSet = concatenateByteArrays(NALUStartCode, hevcRaw);
this.gotVPS = true;
this.gotSPS = false;
this.gotPPS = false;
break;
case 33: //sps
if (this.gotVPS) {
this.vspSet = concatenateByteArrays(this.vspSet, concatenateByteArrays(NALUStartCode, hevcRaw));
this.gotSPS = true;
}
break;
case 34: //pps
if (this.gotSPS) {
this.vspSet = concatenateByteArrays(this.vspSet, concatenateByteArrays(NALUStartCode, hevcRaw));
this.gotPPS = true;
this.gotVPS = false;
this.gotSPS = false;
onHevcPackageReceived(new DataStruct(this.vspSet, timestamp, true));
}
break;
case 19: //I Frame
case 20:
if (this.gotPPS) {
if (this.temp != 19 && this.temp != 20) {
this.idrSet = null;
this.idrSet = concatenateByteArrays(NALUStartCode, hevcRaw);
} else {
this.idrSet = concatenateByteArrays(this.idrSet, concatenateByteArrays(NALUStartCode, hevcRaw));
// concatened 2 I Frame
}
}
break;
case 0: // P Frame
case 1:
if (this.gotPPS) {
if (this.temp == 19 || this.temp == 20) {
onHevcPackageReceived(new DataStruct(this.idrSet, timestamp, false));
} else {
onHevcPackageReceived(new DataStruct(concatenateByteArrays(NALUStartCode, hevcRaw), timestamp, false));
}
}
break;
default:
if (this.gotPPS) {
onHevcPackageReceived(new DataStruct(concatenateByteArrays(NALUStartCode, hevcRaw), timestamp, false));
}
break;
}
this.temp = nalType;
}
}
private void onHevcPackageReceived(DataStruct dataStruct) {
this.Player.getDataQueue().enqueue(dataStruct); // enqueue to list to decode
}
private static byte[] concatenateByteArrays(byte[] a, byte[] b) {
byte[] result = new byte[(a.length + b.length)];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
private int bytesToInt(byte[] range) {
return ByteBuffer.wrap(range).getInt();
}
I've already solved problem by concatening P-frame equal to concatened I-Frame then sent it to decoder:
private int countIdr;
private int countPframe;
switch{....
case 19:
case 20:
if(this.gotPPS){
if(this.nalTemp != 19 && this.nalTemp !=20){
this.countIdr = 1;
this.idrSet = null;
this.idrSet = concatenateByteArrays(NALUStartCode, hevcRaw);
}else {
this.idrSet = concatenateByteArrays(this.idrSet, concatenateByteArrays(NALUStartCode, hevcRaw));
this.countIdr++;
}
}
break;
case 1:
case 0:
if (this.gotPPS) {
if (this.nalTemp == 19 || this.nalTemp == 20){
onHevcPackageReceived(new DataStruct(this.idrSet, timestamp, false));
this.countPframe = 1;
if(this.countIdr == 1){
onHevcPackageReceived(new DataStruct(concatenateByteArrays(NALUStartCode, hevcRaw), timestamp, false));
}else if(this.countIdr > 1){
this.pSet = null;
this.pSet = concatenateByteArrays(NALUStartCode, hevcRaw);
}
} else {
if(this.countIdr == 1){
onHevcPackageReceived(new DataStruct(concatenateByteArrays(NALUStartCode, hevcRaw), timestamp, false));
}else if(this.countIdr > 1){
if(this.countPframe > 0){
if(this.countPframe < this.countIdr && this.pSet != null){
this.pSet = concatenateByteArrays(this.pSet, concatenateByteArrays(NALUStartCode, hevcRaw));
this.countPframe++;
if(this.countPframe == this.countIdr){
onHevcPackageReceived(new DataStruct(this.pSet, timestamp, false));
this.countPframe -= this.countIdr;
}
}
}else if(this.countPframe == 0){
this.pSet = null;
this.pSet = concatenateByteArrays(NALUStartCode, hevcRaw);
this.countPframe++;
}
}
}
}
break;
this.nalTemp = nalType;

Comparison of app version

How to compare app version in android
I got latest version code and current version code , but the problem is
current version is 1.0
and latest version is 1.0.0
so how to compare that float value in android
I have written a small Android library for comparing version numbers: https://github.com/G00fY2/version-compare
What it basically does is this:
public int compareVersions(String versionA, String versionB) {
String[] versionTokensA = versionA.split("\\.");
String[] versionTokensB = versionB.split("\\.");
List<Integer> versionNumbersA = new ArrayList<>();
List<Integer> versionNumbersB = new ArrayList<>();
for (String versionToken : versionTokensA) {
versionNumbersA.add(Integer.parseInt(versionToken));
}
for (String versionToken : versionTokensB) {
versionNumbersB.add(Integer.parseInt(versionToken));
}
final int versionASize = versionNumbersA.size();
final int versionBSize = versionNumbersB.size();
int maxSize = Math.max(versionASize, versionBSize);
for (int i = 0; i < maxSize; i++) {
if ((i < versionASize ? versionNumbersA.get(i) : 0) > (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return 1;
} else if ((i < versionASize ? versionNumbersA.get(i) : 0) < (i < versionBSize ? versionNumbersB.get(i) : 0)) {
return -1;
}
}
return 0;
}
This snippet doesn't offer any error checks or handling. Beside that my library also supports suffixes like "1.2-rc" > "1.2-beta".
I am a bit late to the party but I have a great solution for all of you!
1. Use this class:
public class VersionComparator implements Comparator {
public boolean equals(Object o1, Object o2) {
return compare(o1, o2) == 0;
}
public int compare(Object o1, Object o2) {
String version1 = (String) o1;
String version2 = (String) o2;
VersionTokenizer tokenizer1 = new VersionTokenizer(version1);
VersionTokenizer tokenizer2 = new VersionTokenizer(version2);
int number1, number2;
String suffix1, suffix2;
while (tokenizer1.MoveNext()) {
if (!tokenizer2.MoveNext()) {
do {
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
if (number1 != 0 || suffix1.length() != 0) {
// Version one is longer than number two, and non-zero
return 1;
}
}
while (tokenizer1.MoveNext());
// Version one is longer than version two, but zero
return 0;
}
number1 = tokenizer1.getNumber();
suffix1 = tokenizer1.getSuffix();
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number1 < number2) {
// Number one is less than number two
return -1;
}
if (number1 > number2) {
// Number one is greater than number two
return 1;
}
boolean empty1 = suffix1.length() == 0;
boolean empty2 = suffix2.length() == 0;
if (empty1 && empty2) continue; // No suffixes
if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)
if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)
// Lexical comparison of suffixes
int result = suffix1.compareTo(suffix2);
if (result != 0) return result;
}
if (tokenizer2.MoveNext()) {
do {
number2 = tokenizer2.getNumber();
suffix2 = tokenizer2.getSuffix();
if (number2 != 0 || suffix2.length() != 0) {
// Version one is longer than version two, and non-zero
return -1;
}
}
while (tokenizer2.MoveNext());
// Version two is longer than version one, but zero
return 0;
}
return 0;
}
// VersionTokenizer.java
public static class VersionTokenizer {
private final String _versionString;
private final int _length;
private int _position;
private int _number;
private String _suffix;
private boolean _hasValue;
VersionTokenizer(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
_versionString = versionString;
_length = versionString.length();
}
public int getNumber() {
return _number;
}
String getSuffix() {
return _suffix;
}
public boolean hasValue() {
return _hasValue;
}
boolean MoveNext() {
_number = 0;
_suffix = "";
_hasValue = false;
// No more characters
if (_position >= _length)
return false;
_hasValue = true;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c < '0' || c > '9') break;
_number = _number * 10 + (c - '0');
_position++;
}
int suffixStart = _position;
while (_position < _length) {
char c = _versionString.charAt(_position);
if (c == '.') break;
_position++;
}
_suffix = _versionString.substring(suffixStart, _position);
if (_position < _length) _position++;
return true;
}
}
}
2. create this function
private fun isNewVersionAvailable(currentVersion: String, latestVersion: String): Boolean {
val versionComparator = VersionComparator()
val result: Int = versionComparator.compare(currentVersion, latestVersion)
var op = "=="
if (result < 0) op = "<"
if (result > 0) op = ">"
System.out.printf("%s %s %s\n", currentVersion, op, latestVersion)
return if (op == ">" || op == "==") {
false
} else op == "<"
}
3. and just call it by
e.g. isNewVersionAvailable("1.2.8","1.2.9") where 1.2.8 is your current version here and 1.2.9 is the latest version, which returns true!
Why overcomplicate this so much?
Just scale the major, minor, patch version and you have it covered:
fun getAppVersionFromString(version: String): Int { // "2.3.5"
val versions = version.split(".") // [2, 3, 5]
val major = versions[0].toIntOrDefault(0) * 10000 // 20000
val minor = versions[1].toIntOrDefault(0) * 1000 // 3000
val patch = versions[2].toIntOrDefault(0) * 100 // 500
return major + minor + patch // 2350
}
That way when you compare e.g 9.10.10 with 10.0.0 the second one is greater.
Use the following method to compare the versions number:
Convert float to String first.
public static int versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
String[] vals2 = str2.split("\\.");
int i = 0;
// set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++;
}
// compare first non-equal ordinal number
if (i < vals1.length && i < vals2.length) {
int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
return Integer.signum(diff);
}
// the strings are equal or one string is a substring of the other
// e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4"
return Integer.signum(vals1.length - vals2.length);
}
Refer the following SO question : Efficient way to compare version strings in Java

Reciprocal in Android code for calculator

This is the code for a calculator app for Android I'm making:
package com.example.calculator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Iterator;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.View;
import android.view.View.OnClickListener;
public class main extends Activity {
GridView mKeypadGrid;
TextView userInputText;
TextView memoryStatText;
Stack<String> mInputStack;
Stack<String> mOperationStack;
KeypadAdapter mKeypadAdapter;
TextView mStackText;
boolean resetInput = false;
boolean hasFinalResult = false;
String mDecimalSeperator;
double memoryValue = Double.NaN;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DecimalFormat currencyFormatter = (DecimalFormat) NumberFormat
.getInstance();
char decimalSeperator = currencyFormatter.getDecimalFormatSymbols()
.getDecimalSeparator();
mDecimalSeperator = Character.toString(decimalSeperator);
setContentView(R.layout.main);
// Create the stack
mInputStack = new Stack<String>();
mOperationStack = new Stack<String>();
// Get reference to the keypad button GridView
mKeypadGrid = (GridView) findViewById(R.id.grdButtons);
// Get reference to the user input TextView
userInputText = (TextView) findViewById(R.id.txtInput);
userInputText.setText("0");
memoryStatText = (TextView) findViewById(R.id.txtMemory);
memoryStatText.setText("");
mStackText = (TextView) findViewById(R.id.txtStack);
// Create Keypad Adapter
mKeypadAdapter = new KeypadAdapter(this);
// Set adapter of the keypad grid
mKeypadGrid.setAdapter(mKeypadAdapter);
// Set button click listener of the keypad adapter
mKeypadAdapter.setOnButtonClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button) v;
// Get the KeypadButton value which is used to identify the
// keypad button from the Button's tag
KeypadButton keypadButton = (KeypadButton) btn.getTag();
// Process keypad button
ProcessKeypadInput(keypadButton);
}
});
mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
private void ProcessKeypadInput(KeypadButton keypadButton) {
//Toast.makeText(this, keypadButton.getText(), Toast.LENGTH_SHORT).show();
String text = keypadButton.getText().toString();
String currentInput = userInputText.getText().toString();
int currentInputLen = currentInput.length();
String evalResult = null;
double userInputValue = Double.NaN;
switch (keypadButton) {
case BACKSPACE: // Handle backspace
// If has operand skip backspace
if (resetInput)
return;
int endIndex = currentInputLen - 1;
// There is one character at input so reset input to 0
if (endIndex < 1) {
userInputText.setText("0");
}
// Trim last character of the input text
else {
userInputText.setText(currentInput.subSequence(0, endIndex));
}
break;
case SIGN: // Handle -/+ sign
// input has text and is different than initial value 0
if (currentInputLen > 0 && currentInput != "0") {
// Already has (-) sign. Remove that sign
if (currentInput.charAt(0) == '-') {
userInputText.setText(currentInput.subSequence(1,
currentInputLen));
}
// Prepend (-) sign
else {
userInputText.setText("-" + currentInput.toString());
}
}
break;
case CE: // Handle clear input
userInputText.setText("0");
break;
case INVERT:
if (currentInput != "0") {
userInputText.setText("1/" + currentInput);
}
break;
case C: // Handle clear input and stack
userInputText.setText("0");
clearStacks();
break;
case DECIMAL_SEP: // Handle decimal separator
if (hasFinalResult || resetInput) {
userInputText.setText("0" + mDecimalSeperator);
hasFinalResult = false;
resetInput = false;
} else if (currentInput.contains("."))
return;
else
userInputText.append(mDecimalSeperator);
break;
case DIV:
case PLUS:
case MINUS:
case MULTIPLY:
if (resetInput) {
mInputStack.pop();
mOperationStack.pop();
} else {
if (currentInput.charAt(0) == '-') {
mInputStack.add("(" + currentInput + ")");
} else {
mInputStack.add(currentInput);
}
mOperationStack.add(currentInput);
}
mInputStack.add(text);
mOperationStack.add(text);
dumpInputStack();
evalResult = evaluateResult(false);
if (evalResult != null)
userInputText.setText(evalResult);
resetInput = true;
break;
case CALCULATE:
if (mOperationStack.size() == 0)
break;
mOperationStack.add(currentInput);
evalResult = evaluateResult(true);
if (evalResult != null) {
clearStacks();
userInputText.setText(evalResult);
resetInput = false;
hasFinalResult = true;
}
break;
case M_ADD: // Add user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue += userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case M_REMOVE: // Subtract user input value to memory buffer
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
if (Double.isNaN(memoryValue))
memoryValue = 0;
memoryValue -= userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
case MC: // Reset memory buffer to 0
memoryValue = Double.NaN;
displayMemoryStat();
break;
case MR: // Read memoryBuffer value
if (Double.isNaN(memoryValue))
return;
userInputText.setText(doubleToString(memoryValue));
displayMemoryStat();
break;
case MS: // Set memoryBuffer value to user input
userInputValue = tryParseUserInput();
if (Double.isNaN(userInputValue))
return;
memoryValue = userInputValue;
displayMemoryStat();
hasFinalResult = true;
break;
default:
if (Character.isDigit(text.charAt(0))) {
if (currentInput.equals("0") || resetInput || hasFinalResult) {
userInputText.setText(text);
resetInput = false;
hasFinalResult = false;
} else {
userInputText.append(text);
resetInput = false;
}
}
break;
}
}
private void clearStacks() {
mInputStack.clear();
mOperationStack.clear();
mStackText.setText("");
}
private void dumpInputStack() {
Iterator<String> it = mInputStack.iterator();
StringBuilder sb = new StringBuilder();
while (it.hasNext()) {
CharSequence iValue = it.next();
sb.append(iValue);
}
mStackText.setText(sb.toString());
}
private String evaluateResult(boolean requestedByUser) {
if ((!requestedByUser && mOperationStack.size() != 4)
|| (requestedByUser && mOperationStack.size() != 3))
return null;
String left = mOperationStack.get(0);
String operator = mOperationStack.get(1);
String right = mOperationStack.get(2);
String tmp = null;
if (!requestedByUser)
tmp = mOperationStack.get(3);
double leftVal = Double.parseDouble(left.toString());
double rightVal = Double.parseDouble(right.toString());
double result = Double.NaN;
if (operator.equals(KeypadButton.DIV.getText())) {
result = leftVal / rightVal;
} else if (operator.equals(KeypadButton.MULTIPLY.getText())) {
result = leftVal * rightVal;
} else if (operator.equals(KeypadButton.PLUS.getText())) {
result = leftVal + rightVal;
} else if (operator.equals(KeypadButton.MINUS.getText())) {
result = leftVal - rightVal;
}
String resultStr = doubleToString(result);
if (resultStr == null)
return null;
mOperationStack.clear();
if (!requestedByUser) {
mOperationStack.add(resultStr);
mOperationStack.add(tmp);
}
return resultStr;
}
private String doubleToString(double value) {
if (Double.isNaN(value))
return null;
long longVal = (long) value;
if (longVal == value)
return Long.toString(longVal);
else
return Double.toString(value);
}
private double tryParseUserInput() {
String inputStr = userInputText.getText().toString();
double result = Double.NaN;
try {
result = Double.parseDouble(inputStr);
} catch (NumberFormatException nfe) {
}
return result;
}
private void displayMemoryStat() {
if (Double.isNaN(memoryValue)) {
memoryStatText.setText("");
} else {
memoryStatText.setText("M = " + doubleToString(memoryValue));
}
}
}
To find the reciprocal of an inputted number, I use the following code:
case INVERT:
if (currentInput != "0") {
userInputText.setText("1/" + currentInput);
}
break;
But instead of displaying the output of the reciprocal, like I wanted, it simply displays "1/inputted number". Why is this, and can someone help me fix it? Thanks in advance.
You are returning it as text and so that is how it is displayed. You need to do the math then convert it to a string:
float input = Float.valueOf(currentInput);
if( input == 0) // Check if 0 to avoid divide by 0 error
userInputText.setText("NaN");
else
userInputText.setText(Float.toString(1/input));
double inputVal = Double.valueOf(currentInput);
userInputText.setText(inputVal != 0 ? String.valueOf(1/inputVal) : "NaN");

Simplyfing Code to Manage SharedPreferences

How can I make this code trimmed down?
prefsDisplay = getSharedPreferences("spinnerSelection",
Context.MODE_PRIVATE);
prefsPlan = getSharedPreferences("spinnerSelection1",
Context.MODE_PRIVATE);
if (prefsDisplay.getInt("spinnerSelection", 0) == 0) {
s1 = 0;
} else if (prefsDisplay.getInt("spinnerSelection", 0) == 1) {
s1 = 1;
} else if (prefsDisplay.getInt("spinnerSelection", 0) == 2) {
s1 = 2;
} else if (prefsDisplay.getInt("spinnerSelection", 0) == 3) {
s1 = 3;
} else {
s1 = 0;
DP.BreakdownMonths = 0;
}
if (prefsPlan.getInt("spinnerSelection1", 0) == 0) {
s2 = 0;
} else if (prefsPlan.getInt("spinnerSelection1", 0) == 1) {
s2 = 1;
} else if (prefsPlan.getInt("spinnerSelection1", 0) == 2) {
s2 = 2;
} else {
s2 = 0;
DP.PlanType = "highint";
}
Basically, what I am doing, when the app logs in, I want it to check SharedPreferences. If it finds a value, it assigns it, otherwise, it defaults to a value.
The following does exactly what your code does. Use the value assigned to shared prefs, and if empty, assign 0 AND also assign DP.
prefsDisplay = getSharedPreferences("spinnerSelection",
Context.MODE_PRIVATE);
prefsPlan = getSharedPreferences("spinnerSelection1",
Context.MODE_PRIVATE);
s1 = prefsDisplay.getInt("spinnerSelection", -1 );
if( s1 < 0 ) {
s1 = 0;
DP.BreakdownMonths = 0;
}
s2 = prefsPlan.getInt("spinnerSelection1", -1 );
if( s2 < 0 ) {
s2 = 0;
DP.PlanType = "highint";
}
Use switch and case to define for respective if statement and use default to assign if it doesn't match any of the if statement.
example:
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);

Categories

Resources