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);
Related
`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.
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;
}
}
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;
I am trying to implement image collage preview like Facebook while posting images,
so far i have created 5 layouts according to multiple image count and then i am inflating the layouts according to selected image list and setting image in forloop, i also need to show document icon if any selected.
Here is the code which i have implemented.
private void displayCollage() {
rlLayout.setVisibility(View.VISIBLE);
rlLayout.removeAllViews();
imagelayout5Binding.tvCount.setVisibility(View.GONE);
if (attachList.size() > 0) {
int count = attachList.size();
if (count > 5) {
count = 6;
}
switch (count) {
case 1:
DisplayCollageImage(imagelayout1Binding.ivImage, 0);
rlLayout.addView(imagelayout1Binding.getRoot());
break;
case 2:
for (int i = 0; i <= attachList.size(); i++) {
switch (i) {
case 0:
DisplayCollageImage(imagelayout2Binding.ivImage1, i);
break;
case 1:
DisplayCollageImage(imagelayout2Binding.ivImage2, i);
break;
}
}
rlLayout.addView(imagelayout2Binding.getRoot());
break;
case 3:
for (int i = 0; i <= attachList.size(); i++) {
switch (i) {
case 0:
DisplayCollageImage(imagelayout3Binding.ivImage1, i);
break;
case 1:
DisplayCollageImage(imagelayout3Binding.ivImage2, i);
break;
case 2:
DisplayCollageImage(imagelayout3Binding.ivImage3, i);
break;
}
}
rlLayout.addView(imagelayout3Binding.getRoot());
break;
case 4:
for (int i = 0; i <= attachList.size(); i++) {
switch (i) {
case 0:
DisplayCollageImage(imagelayout4Binding.ivImage1, i);
break;
case 1:
DisplayCollageImage(imagelayout4Binding.ivImage2, i);
break;
case 2:
DisplayCollageImage(imagelayout4Binding.ivImage3, i);
break;
case 3:
DisplayCollageImage(imagelayout4Binding.ivImage4, i);
break;
}
}
rlLayout.addView(imagelayout4Binding.getRoot());
break;
case 5:
for (int i = 0; i <= attachList.size(); i++) {
switch (i) {
case 0:
DisplayCollageImage(imagelayout5Binding.ivImage1, i);
break;
case 1:
DisplayCollageImage(imagelayout5Binding.ivImage2, i);
break;
case 2:
DisplayCollageImage(imagelayout5Binding.ivImage3, i);
break;
case 3:
DisplayCollageImage(imagelayout5Binding.ivImage4, i);
break;
case 4:
DisplayCollageImage(imagelayout5Binding.ivImage5, i);
break;
}
}
rlLayout.addView(imagelayout5Binding.getRoot());
break;
case 6:
for (int i = 0; i <= attachList.size(); i++) {
if (i >= attachList.size()) {
i = 5;
}
switch (i) {
case 0:
DisplayCollageImage(imagelayout5Binding.ivImage1, i);
break;
case 1:
DisplayCollageImage(imagelayout5Binding.ivImage2, i);
break;
case 2:
DisplayCollageImage(imagelayout5Binding.ivImage3, i);
break;
case 3:
DisplayCollageImage(imagelayout5Binding.ivImage4, i);
break;
case 4:
DisplayCollageImage(imagelayout5Binding.ivImage5, i);
break;
case 5:
DisplayCollageImage(imagelayout5Binding.tvCount);
break;
}
if (i == 5) {
break;
}
}
rlLayout.addView(imagelayout5Binding.getRoot());
break;
}
} else {
rlLayout.removeAllViews();
}
}
but doing this is taking too much processing time, please help me how can i reduce this processing time.
If you are trying to achieve the above output then i would suggest using a Recyclerview with StaggeredGrid Layout
I am working on a Android app that modifies the Bluetooth Chat example given with Eclipse to create an On-Board Diagnostic (OBD) reader. My code sends a message to my vehicle's ECU and retrieves data with the use of switches.
Now, my problem is, for some reason when I run my program I only receive data for 6 of my cases and I am not receiving data for the rest of them.
The code is kind of lengthy.
public void startTransmission() {
sendMessage("01 00" + '\r');
}
public void getData(int messagenumber) {
final TextView TX = (TextView) findViewById(R.id.TXView2);
switch (messagenumber) {
case 1:
sendMessage("01 0C" + '\r'); // get RPM
TX.setText("01 0C");
messagenumber++;
break;
case 2:
sendMessage("01 0D" + '\r'); // get MPH
TX.setText("01 0D");
messagenumber++;
break;
case 3:
sendMessage("01 04" + '\r'); // get Engine Load
TX.setText("01 04");
messagenumber++;
break;
case 4:
sendMessage("01 05" + '\r'); // get Coolant Temperature
TX.setText("01 05");
messagenumber++;
break;
case 5:
sendMessage("01 0F" + '\r'); // get Intake Temperature
TX.setText("01 0F");
messagenumber++;
break;
case 6:
sendMessage("AT RV" + '\r'); // get Voltage
TX.setText("AT RV");
messagenumber++;
break;
case 7:
sendMessage("01 06" + '\r'); // get Fuel Trim Bank 1 Sensor 1
TX.setText("01 06");
messagenumber++;
case 8:
sendMessage("01 07" + '\r'); // get Fuel Trim Bank 1 Sensor 2
TX.setText("01 07");
messagenumber++;
case 9:
sendMessage("01 0B" + '\r'); // get Intake Manifold Pressure
TX.setText("01 0B");
messagenumber++;
case 10:
sendMessage("01 0E" + '\r'); // get Timing Advance
TX.setText("01 0E");
messagenumber++;
case 11:
sendMessage("01 11" + '\r'); // get Throttle Position
TX.setText("01 11");
messagenumber++;
case 12:
sendMessage("01 14" + '\r'); // get Oxygen Bank 1 Sensor 1
TX.setText("01 14");
messagenumber++;
case 13:
sendMessage("01 15" + '\r'); // get Oxygen Bank 1 Sensor 2
TX.setText("01 15");
messagenumber++;
default:
;
}
}
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
.show();
return;
}// end if
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
// mOutEditText.setText(mOutStringBuffer);
}// end if
}// end sendMessage method
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// <--------- Initialize Data Display Fields ---------->//
/* PID = 0C */final TextView RPM = (TextView) findViewById(R.id.numRPM);
/* PID = 0D */final TextView MPH = (TextView) findViewById(R.id.numSpeed);
/* PID = 04 */final TextView engineLoad = (TextView) findViewById(R.id.numLoad);
/* PID = 05 */final TextView coolantTemperature = (TextView) findViewById(R.id.numCoolant);
/* PID = 0F */final TextView intakeTemperature = (TextView) findViewById(R.id.numIntakeAir);
/* PID = RV */final TextView voltage = (TextView) findViewById(R.id.numVoltage);
/* PID = 06 */final TextView fuelTrimB1S1 = (TextView) findViewById(R.id.numFTb1s1);
/* PID = 07 */final TextView fuelTrimB1S2 = (TextView) findViewById(R.id.numFTb1s2);
/* PID = 0A */final TextView intakeManifold = (TextView) findViewById(R.id.numManifold);
/* PID = 0E */final TextView timingAdvance = (TextView) findViewById(R.id.numTiming);
/* PID = 11 */final TextView throttlePos = (TextView) findViewById(R.id.numThrottle);
/* PID = 14 */final TextView oxygenB1s1 = (TextView) findViewById(R.id.numO2b1s1);
/* PID = 15 */final TextView oxygenB1s2 = (TextView) findViewById(R.id.numO2b1s2);
/* displays recieved string */final TextView RX = (TextView) findViewById(R.id.RXView2);
String dataRecieved;
int value = 0;
int value2 = 0;
int PID = 0;
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (D)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to,
mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
// byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
// String writeMessage = new String(writeBuf);
// mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
// ------- ADDED CODE FOR OBD -------- //
dataRecieved = readMessage;
RX.setText(dataRecieved);
if ((dataRecieved != null)
&& (dataRecieved
.matches("\\s*[0-9A-Fa-f]{2} [0-9A-Fa-f]{2}\\s*\r?\n?"))) {
dataRecieved = dataRecieved.trim();
String[] bytes = dataRecieved.split(" ");
if ((bytes[0] != null) && (bytes[1] != null)) {
PID = Integer.parseInt(bytes[0].trim(), 16);
value = Integer.parseInt(bytes[1].trim(), 16);
}
switch (PID) {
case 15:// PID(0F): Intake Temperature
value = value - 40; // Formula for Intake Temperature
value = ((value * 9) / 5) + 32; // Convert from Celsius
// to Farenheit
String displayIntakeTemp = String.valueOf(value);
intakeTemperature.setText(displayIntakeTemp + " F");
break;
// end Intake Temperature case
case 4:// PID(04): Engine Load
value = (value * 100) / 255;
String displayEngineLoad = String.valueOf(value);
engineLoad.setText(displayEngineLoad + " %");
break;
// end Engine Load case
case 5:// PID(05): Coolant Temperature
value = value - 40;
value = ((value * 9) / 5) + 32; // convert to deg F
String displayCoolantTemp = String.valueOf(value);
coolantTemperature.setText(displayCoolantTemp);
break;
// end Coolant Temperature case
case 12: // PID(0C): RPM
int RPM_value = (value * 256) / 4;
String displayRPM = String.valueOf(RPM_value);
RPM.setText(displayRPM);
break;
// end RPM case
case 13:// PID(0D): MPH
value = (value * 5) / 8; // convert KPH to MPH
String displayMPH = String.valueOf(value);
MPH.setText(displayMPH + " MPH");
break;
// end MPH case
case 6:// PID(06): Fuel Trim Bank 1 Sensor 1
value = (value - 128) * 100 / 128;
String displayFtB1s1 = String.valueOf(value);
fuelTrimB1S1.setText(displayFtB1s1);
break;
case 7:// PID(07): Fuel Trim Bank 1 Sensor 2
value = (value - 128) * 100 / 128;
String displayFtB1s2 = String.valueOf(value);
fuelTrimB1S2.setText(displayFtB1s2);
break;
case 11: // PID(0A): Intake Manifold Pressure
String displayIntakeManifold = String.valueOf(value);
intakeManifold.setText(displayIntakeManifold);
break;
case 14: // PID(0E): Timing Advance
value = value / 2 - 64;
String displayTimingAdvance = String.valueOf(value);
timingAdvance.setText(displayTimingAdvance);
break;
case 17: // PID(11): Throttle Position
value = value * 100 / 255;
String displayThrottlePos = String.valueOf(value);
throttlePos.setText(displayThrottlePos);
case 20: // PID(14): Oxygen Bank 1 Sensor 1
String displayO2B1s1 = String.valueOf(value);
oxygenB1s1.setText(displayO2B1s1);
break;
case 21: // PID(14): Oxygen Bank 1 Sensor 2
String displayO2B1s2 = String.valueOf(value);
oxygenB1s2.setText(displayO2B1s2);
break;
default:
;
}
} else if ((dataRecieved != null)
&& (dataRecieved
.matches("\\s*[0-9A-Fa-f]{1,2} [0-9A-Fa-f]{2} [0-9A-Fa-f]{2}\\s*\r?\n?"))) {
dataRecieved = dataRecieved.trim();
String[] bytes = dataRecieved.split(" ");
if ((bytes[0] != null) && (bytes[1] != null)
&& (bytes[2] != null)) {
PID = Integer.parseInt(bytes[0].trim(), 16);
value = Integer.parseInt(bytes[1].trim(), 16);
value2 = Integer.parseInt(bytes[2].trim(), 16);
}
// PID(0C): RPM
if (PID == 12) {
int RPM_value = ((value * 256) + value2) / 4;
String displayRPM = String.valueOf(RPM_value);
RPM.setText(displayRPM + " RPM");
} else if ((PID == 1) || (PID == 65)) {
switch (value) {
case 15:// PID(0F): Intake Temperature
value2 = value2 - 40; // formula for INTAKE AIR TEMP
value2 = ((value2 * 9) / 5) + 32; // convert to deg
// F
String displayIntakeTemp = String.valueOf(value2);
intakeTemperature
.setText(displayIntakeTemp + " °F");
break;
// end Intake Temperature case
case 4:// PID(04): Engine Load
value2 = (value2 * 100) / 255;
String displayEngineLoad = String.valueOf(value2);
engineLoad.setText(displayEngineLoad + " %");
break;
// end Engine Load case
case 5:// PID(05): Coolant Temperature
value2 = value2 - 40;
value2 = ((value2 * 9) / 5) + 32; // convert to deg
// F
String displayCoolantTemp = String.valueOf(value2);
coolantTemperature.setText(displayCoolantTemp
+ " °F");
break;
case 13:// PID(0D): MPH
value2 = (value2 * 5) / 8; // convert to MPH
String displayMPH = String.valueOf(value2);
MPH.setText(displayMPH + " MPH");
break;
// case 6:// PID(06): Fuel Trim Bank 1 Sensor 1
//
// value = (value - 128) * 100 / 128;
//
// String displayFtB1s1 = String.valueOf(value);
// fuelTrimB1S1.setText(displayFtB1s1 + " V");
// break;
//
// case 7:// PID(07): Fuel Trim Bank 1 Sensor 2
//
// value = (value - 128) * 100 / 128;
//
// String displayFtB1s2 = String.valueOf(value);
// fuelTrimB1S2.setText(displayFtB1s2 + " V");
// break;
//
// case 11: // PID(0A): Intake Manifold Pressure
//
// String displayIntakeManifold = String
// .valueOf(value);
// intakeManifold.setText(displayIntakeManifold
// + " psi");
// break;
//
// case 14: // PID(0E): Timing Advance
//
// value = value / 2 - 64;
//
// String displayTimingAdvance = String.valueOf(value);
// timingAdvance.setText(displayTimingAdvance + " °");
// break;
//
// case 17: // PID(11): Throttle Position
//
// value = value * 100 / 255;
//
// String displayThrottlePos = String.valueOf(value);
// throttlePos.setText(displayThrottlePos + " %");
//
// case 20: // PID(14): Oxygen Bank 1 Sensor 1
//
// String displayO2B1s1 = String.valueOf(value);
// oxygenB1s1.setText(displayO2B1s1 + " V");
// break;
//
// case 21: // PID(14): Oxygen Bank 1 Sensor 2
//
// String displayO2B1s2 = String.valueOf(value);
// oxygenB1s2.setText(displayO2B1s2 + " V");
// break;
default:
;
}
}
} else if ((dataRecieved != null)
&& (dataRecieved
.matches("\\s*[0-9]+(\\.[0-9]?)?V\\s*\r*\n*"))) {
dataRecieved = dataRecieved.trim();
voltage.setText(dataRecieved);
} else if ((dataRecieved != null)
&& (dataRecieved
.matches("\\s*[0-9]+(\\.[0-9]?)?V\\s*V\\s*>\\s*\r*\n*"))) {
dataRecieved = dataRecieved.trim();
// String volt_number = dataRecieved.substring(0,
// dataRecieved.length() - 1);
voltage.setText(dataRecieved);
} else if ((dataRecieved != null)
&& (dataRecieved
.matches("\\s*[ .A-Za-z0-9\\?*>\r\n]*\\s*>\\s*\r*\n*"))) {
if (message_number == 7)
message_number = 1;
getData(message_number++);
}
break;
}
}
Where I think I want to focus on is:
if ((dataRecieved != null)
&& (dataRecieved
.matches("\\s*[0-9A-Fa-f]{2} [0-9A-Fa-f]{2}\\s*\r?\n?"))) {
dataRecieved = dataRecieved.trim();
String[] bytes = dataRecieved.split(" ");
if ((bytes[0] != null) && (bytes[1] != null)) {
PID = Integer.parseInt(bytes[0].trim(), 16);
value = Integer.parseInt(bytes[1].trim(), 16);
}
This code is based off some research that I have done and I am not sure what the string behind the dataRecieved.matches is. It looks to be an array and I am thinking that the parameters received are causing my switch cases not to fire.
Thanks for any input.