`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.
Related
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 new with android and java, so I apologize if what I say is not entirely correct.
In my application I'd like to convert an ArrayList to integer
to increase each value with a +1. Please note the commented out part to understand where is my problem. I can't find the right way..
This is what I do for now:
public String mRequest(String mUrl, String mAuth, String mParam, String customerId, ArrayList filter) {
InputStream mStreamResponse;
String mString = null;
try {
URL obj = new URL(mUrl);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", mAuth);
con.setRequestProperty("X-Limit", String.valueOf(xLimit));
con.setRequestProperty("X-Skip", String.valueOf(xSkip));
con.setRequestProperty("X-Sort", "{\"created\":-1}");
String parameters = null;
System.out.println("Value of mParam -> " + mParam);
if (mParam != null && customerId != null) {
Log.e("ERROR", "Ricerca per parametro e customerId");
} else if (mParam != null) {
parameters = "\"number\":{\"$regex\":" + mParam + "}";
} else if (customerId != null) {
parameters = "\"customer.id\":{\"$eq\":" + "\"" + customerId + "\"" + "}";
} else {
parameters = "\"number\":{\"$regex\":\"\"}";
}
System.out.println("parameters");
System.out.println(parameters);
if (filter != null) {
//convert ArrayList to Array
Object[] mArray = filter.toArray();
String filterGroup = mArray[0].toString() + ".id";
System.out.println("Group selected -> " + filterGroup);
for (int i = 1; i < mArray.length; i++) {
System.out.println("Value -> " + mArray[i]);
}
String pFilter = null;
for (int i = 1; i < mArray.length; i++) {
/*
*
* This is where I need to change value in
* pos i with i + 1
*
*/
switch (mArray[i].toString()) {
case "0":
mArray[i] = "1";
break;
case "1":
mArray[i] = "2";
break;
case "2":
mArray[i] = "3";
break;
case "3":
mArray[i] = "4";
break;
case "4":
mArray[i] = "5";
break;
case "5":
mArray[i] = "6";
break;
case "6":
mArray[i] = "7";
break;
case "7":
mArray[i] = "8";
break;
case "8":
mArray[i] = "9";
break;
case "9":
mArray[i] = "10";
break;
case "10":
mArray[i] = "11";
break;
case "11":
mArray[i] = "12";
break;
case "12":
mArray[i] = "13";
break;
}
if (mArray.length == 2){
pFilter = mArray[i].toString();
} else {
if (mArray[i] != mArray[mArray.length - 1]) {
if (pFilter != null) {
pFilter = pFilter + mArray[i].toString() + ",";
} else {
pFilter = mArray[i].toString() + ",";
}
} else {
pFilter = pFilter + mArray[i].toString();
}
}
}
String mFilter = "[" + pFilter + "]";
System.out.println("Insert value in a string -> " + mFilter);
String tempParam = null;
if (filterGroup.equals("assignee")) {
tempParam = "{\"$eq\":" + mFilter + "}";
} else {
tempParam = "{\"$in\":" + mFilter + "}";
}
//Override the value with the same filterGroup
if (filterMap.containsKey(filterGroup)) {
String toOverride = filterGroup;
filterMap.remove(filterGroup);
filterMap.put(toOverride, tempParam);
} else {
filterMap.put(filterGroup, tempParam);
}
//iterate
for (Map.Entry<String, String> entry : filterMap.entrySet()) {
switch (entry.getKey()) {
case "status.id":
status = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "queue.id":
queues = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "type.id":
types = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "severity.id":
severities = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
case "assignee.id":
mytickets = "\"" + entry.getKey() + "\":" + entry.getValue();
break;
}
}
filterMapValues = parameters ;
if (status != null) {
filterMapValues += ", " + status;
}
if (queues != null) {
filterMapValues += ", " + queues;
}
if (types != null) {
filterMapValues += ", " + types;
}
if (severities != null) {
filterMapValues += ", " + severities;
}
if (mytickets != null) {
filterMapValues += ", " + mytickets;
}
String myFilter = "{" + filterMapValues + "}";
System.out.println("myFilter -> " + myFilter);
//setup request header
con.setRequestProperty("X-Filter", myFilter);
} else {
String xFilter = "{\"status.id\":" + statusAll + ", \"queue.id\":" + queueAll + ", \"type.id\":" + typeAll + ", \"severity.id\":" + severityAll + "," + parameters + "}";
con.setRequestProperty("X-Filter", xFilter);
System.out.println("Reset all -> " + xFilter);
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + mUrl);
System.out.println("Response Code : " + responseCode);
mStreamResponse = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(mStreamResponse));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
mStreamResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
mString = sb.toString();
} catch (Exception e) {
}
return mString;
}
How can I do?
Thanks in advance.
Edit
I started the for loop in pos #1 because in pos #0 I save filterGroup value, and that's a String, I need to menage as int only values in pos > 0
First off:
I'd like to convert an ArrayList to integer [...]
ArrayList<E> is a collection object with type E that can be any object or primitive. What you are really asking for is how to convert an ArrayList<String> (see that it is an ArrayList of type String) into an integer array. I can see you have already converted the ArrayList<String> into an Object[] (Object array that can hold both integers and Strings) using the following line in the example code given above:
Object[] mArray = filter.toArray();
Getting back to the original answer, this would do it:
int[] mArray = new int[filter.size()];
for (int i = 0; i < filter.size(); i++) {
int value = Integer.parseInt(filter.get(i));
mArray[i] = value++;
}
Your code is correct just change the for loop initial value to start from 0 rather than 1 like this:
int tempValue = 0;
for (int i = 0; i < mArray.length; i++) {
{
// increasing your mArray value
tempValue = (Integer) mArray[i] + 1;
mArray[i] = tempValue;
//Rest of your code
}
Can you try this please.
Remove your switch case inside for and replace it with below. Hope you want something like this.
for(int i=0; i<mArray.length(); i++){
mArray[i] = i+1;
}
let me know..
Do follwoing
Step 1: Create a method
private List<Integer> stringToIncrementedString(ArrayList<String> stringArrayList){
List<Integer> arrayInt;
arrayInt = new ArrayList<Integer>();
for(int i=1 ;i<stringArrayList.size();i++)
arrayInt.add(Integer.parseInt(stringArrayList.get(i))+1);
return arrayInt;
}
Step 2 :Call this method from where you want.It will return the Arraylist with incremented value.
I have an issue.I have custom listView which has many child and also have another custom listview in it.All data which is display in both listView is coming from database.My Problem is that When I scroll My main ListView it stucks for a while and then scroll.I uploaded My all code here.
My Main Activity class:
public class TransactionListMonthWise<DisplayYear> extends TopParentActivity {
ListView statement;
ArrayList<DisplayMonth> status;
ArrayList<DisplayYear> yearstatus;
addBankTransactionList mAdapter;
TextView tvBankName, tvBalance, tvBankAccNoForHistory;
String monthname;
String monthName;
int yearName;
String bankname, amount, accno;
Date theDate;
String currencySymbl, cur_sym;
EPreferences epref;
String TotalBalance, BankBalance, finalTotalIncome;
Toolbar toolbarTransactionListMonthWise;
boolean loadingMore = false;
int itemsPerPage = 2;
DisplayMonth monthNameInAdapter;
int month;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction_monthwise);
bindview();
init();
addListener();
}
private void init() {
epref = EPreferences.getInstance(TransactionListMonthWise.this);
getPrefData();
Intent intent = getIntent();
bankname = intent.getStringExtra("NAME");
tvBankName.setText(bankname);
TotalBalance = String.valueOf(intent.getDoubleExtra("BALANCE", 0.0));
BankBalance = new BigDecimal(TotalBalance).toPlainString();
DecimalFormat decimalFormatIncome = new DecimalFormat("0.#");
finalTotalIncome = decimalFormatIncome.format(Double
.valueOf(TotalBalance));
tvBalance.setText(currencySymbl
+ " "
+ String.format("%,.00f",
(double) Double.parseDouble(finalTotalIncome)));
// tvBalance.setText(amount + " " + currencySymbl);
Log.i("symbol", currencySymbl);
accno = intent.getStringExtra("ACCNO");
status = new ArrayList<DisplayMonth>();
yearstatus = new ArrayList<DisplayYear>();
tvBankAccNoForHistory.setText("xxxxx"
+ intent.getStringExtra("ACC_NUMBER"));
Utils.BANK_ACC_NUM = intent.getStringExtra("ACC_NUMBER");
Utils.BANK_NAME_DISP = bankname;
setSupportActionBar(toolbarTransactionListMonthWise);
this.toolbarTransactionListMonthWise
.setNavigationIcon(R.drawable.ic_arrow_back_white100);
getSupportActionBar().setTitle(bankname + " History");
}
private void bindview() {
toolbarTransactionListMonthWise = (Toolbar) findViewById(R.id.toolbarTransactionListMonthWise);
statement = (ListView) findViewById(R.id.list_transaction_view);
tvBankName = (TextView) findViewById(R.id.tvBankNameForHistory);
tvBalance = (TextView) findViewById(R.id.tvNetBalanceForHistory);
tvBankAccNoForHistory = (TextView) findViewById(R.id.tvBankAccNoForHistory);
}
private void addListener() {
statement.setOnScrollListener(new AbsListView.OnScrollListener() {
int mLastFirstVisibleItem;
boolean mIsScrollingUp;
#Override
public void onScrollStateChanged(AbsListView view, int scrollstate) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount)) {
new MailSender().execute();
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(TransactionListMonthWise.this,
BankList.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private String getMonth(int month1) {
switch (month1) {
case 1:
monthname = "Jan";
break;
case 2:
monthname = "Feb";
break;
case 3:
monthname = "Mar";
break;
case 4:
monthname = "Apr";
break;
case 5:
monthname = "May";
break;
case 6:
monthname = "Jun";
break;
case 7:
monthname = "Jul";
break;
case 8:
monthname = "Aug";
break;
case 9:
monthname = "Sep";
break;
case 10:
monthname = "Oct";
break;
case 11:
monthname = "Nov";
break;
case 12:
monthname = "Dec";
break;
default:
break;
}
return monthname;
}
private int getYear(int years) {
switch (years) {
case 1:
years = 2011;
break;
case 2:
years = 2012;
break;
case 3:
years = 2013;
break;
case 4:
years = 2014;
break;
case 5:
years = 2015;
break;
case 6:
years = 2016;
break;
default:
break;
}
return years;
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = getResources().getString(R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = getResources().getString(R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = getResources().getString(R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = getResources().getString(R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = getResources().getString(R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = getResources().getString(R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = getResources().getString(R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = getResources().getString(R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = getResources().getString(R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = getResources().getString(R.string.Euro);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
public class MailSender extends AsyncTask<Void, Integer, Integer> {
Dialog progress;
#SuppressLint("ResourceAsColor")
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new Dialog(TransactionListMonthWise.this,
R.style.AppDialogExit);
progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
progress.show();
progress.setContentView(R.layout.custom_loading_dialog);
TextView tv = (TextView) progress.findViewById(R.id.tv);
tv.setText("Mail is sending...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
}
#Override
protected Integer doInBackground(Void... params) {
final RelativeLayout footerView = (RelativeLayout) findViewById(R.id.loadItemsLayout_recyclerView);
Calendar cal = Calendar.getInstance();
month = cal.get(Calendar.MONTH) + 1;
// int year = cal.get(Calendar.YEAR) - 10;
int currentYear = cal.get(Calendar.YEAR);
Log.d("viewMonths", "month is" + month + " " + currentYear);
for (int j = month; j > 0; j--) {
monthNameInAdapter = new DisplayMonth();
monthName = getMonth(j);
monthNameInAdapter.setMonth(monthName);
status.add(monthNameInAdapter);
}
mAdapter = new addBankTransactionList(getApplicationContext(),
month, status, bankname, accno, currentYear, amount);
return 0;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
// progress.dismiss();
if (progress != null) {
progress.dismiss();
progress = null;
}
try {
statement.setAdapter(mAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Main Xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:fitsSystemWindows="true"
android:gravity="center"
android:orientation="vertical" >
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarTransactionListMonthWise"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="?colorPrimary"
android:minHeight="?actionBarSize"
android:paddingRight="10dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true" >
<RelativeLayout
android:id="#+id/rlBankNameAndBalance"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#color/green_100"
android:clickable="true"
android:gravity="right"
android:orientation="vertical"
android:paddingLeft="#dimen/main_list_data_disp_padding_left"
android:paddingRight="#dimen/main_list_data_disp_padding_right"
android:paddingTop="#dimen/main_list_data_disp_padding_top" >
<TextView
android:id="#+id/tvBankNameForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/iconId"
android:text="#string/BankBalance"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
<TextView
android:id="#+id/tvBankAccNoForHistory"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvBankNameForHistory"
android:text="#string/BankBalance"
android:textColor="#color/gray_500"
android:textSize="14sp" />
<TextView
android:id="#+id/tvNetBalanceForHistory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#color/gray_900"
android:textSize="#dimen/main_list_data_disp_text_size" />
</RelativeLayout>
</android.support.v7.widget.CardView>
<ListView
android:id="#+id/list_transaction_view"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="2dp"
android:scrollbars="none" />
<include
android:id="#+id/loadItemsLayout_recyclerView"
android:layout_width="fill_parent"
android:layout_height="110dp"
android:layout_alignParentBottom="true"
layout="#layout/progress_layout"
android:visibility="gone" />
Main Adapter Class:
public class addBankTransactionList extends BaseAdapter {
// Activity activityCategory;
static ArrayList<DisplayMonth> monthName;
// ArrayList<DisplayYear> yearName;
ArrayList<Expense> expense;
ArrayList<Income> incomes, Arr;
#SuppressWarnings("rawtypes")
ArrayList<String> arrDateDebit, arrDateCredit;
ArrayList<Double> arrAmountDebit, arrAmountCredit;
Context contextAddBank;
int CurrentMonth;
String bankNameForMatch, months, allyear, SystemMonthInString, amount,
bankAccNoForMatch;
int monthname;
String currencySymbl, cur_sym;
String date = "", thirdYear;
String monthNameInString;
EPreferences epref;
ArrayList<Income> tempIncomeses = new ArrayList<Income>();
String dateIncome, dateExpense;
Double expenseAmount, incomeAmount;
DataBaseAdapter adapter;
// private String ;
int monthNameInStringExpense, monthNameInStringIncome;
int yr, year;
int monthsInIntIncome, dateInIntIncome, yearInIntIncome,
monthsInIntExpense;
String convertDate;
// private ArrayList<Income> tempincomes = new ArrayList<Income>();
List list;
Date date1;
String emptyExpenseAmount, emptyIncomeAmount;
FilterData data;
private String bankname, accno;
public static Boolean isScrolling = true;
public static class ViewHolder {
public TextView tvDate, tvIncomeMoney, tvExpenseMoney,
tvRecordnotFound, tvIncomeSymblIncomeDisp, tvTransactionType,
tvTransactionDate, tvTransactionAmount, tvMoneyCurrencyExpense,
tvMoneyCurrencyIncome;
ListView rvList;
}
public addBankTransactionList(Context mcontext, int month,
ArrayList<DisplayMonth> status, String bankname, String bankAccNo,
int year, String amt) {
super();
this.contextAddBank = mcontext;
monthName = status;
CurrentMonth = month;
bankNameForMatch = bankname;
bankAccNoForMatch = bankAccNo;
yr = year;
amount = amt;
}
public boolean setListViewHeightBasedOnItems(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
Log.i("TotalRecord", numberOfItems + "");
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
int totalDividersHeight = listView.getDividerHeight()
* (numberOfItems - 1);
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
listView.setClickable(false);
listView.setEnabled(false);
return true;
} else {
return false;
}
}
private void getPrefData() {
cur_sym = epref.getPreferencesStr(epref.KEY_CURRENCY, "India");
Log.d("vaaaaa", " == " + cur_sym);
if (cur_sym.equalsIgnoreCase("India")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.India);
} else if (cur_sym.equalsIgnoreCase("US")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United_States);
} else if (cur_sym.equalsIgnoreCase("Japan")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Japan);
} else if (cur_sym.equalsIgnoreCase("England")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.England_pound);
} else if (cur_sym.equalsIgnoreCase("Costa Rica")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Costa);
} else if (cur_sym.equalsIgnoreCase("UK")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.United);
} else if (cur_sym.equalsIgnoreCase("Phillipines")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Philippines);
} else if (cur_sym.equalsIgnoreCase("Mangolia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Macedonia);
} else if (cur_sym.equalsIgnoreCase("Australia")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Australia);
} else if (cur_sym.equalsIgnoreCase("Europ")) {
currencySymbl = contextAddBank.getResources().getString(
R.string.Euro);
}
}
private int getMonthName(String month1) {
switch (month1.toLowerCase().toString()) {
case "Jan":
monthname = 1;
break;
case "Feb":
monthname = 2;
break;
case "Mar":
monthname = 3;
break;
case "Apr":
monthname = 4;
break;
case "May":
monthname = 5;
break;
case "Jun":
monthname = 6;
break;
case "Jul":
monthname = 7;
break;
case "Aug":
monthname = 8;
break;
case "Sep":
monthname = 9;
break;
case "Oct":
monthname = 10;
break;
case "Nov":
monthname = 11;
break;
case "Dec":
monthname = 12;
break;
default:
break;
}
return monthname;
}
#Override
public int getCount() {
return monthName.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View conView, ViewGroup parent) {
ViewHolder vh;
if (conView == null) {
conView = LayoutInflater.from(contextAddBank).inflate(
R.layout.transaction_list, null, false);
vh = new ViewHolder();
vh.tvDate = (TextView) conView.findViewById(R.id.tvDate);
vh.rvList = (ListView) conView
.findViewById(R.id.lvDisplayExpenseList);
vh.tvIncomeMoney = (TextView) conView
.findViewById(R.id.tvIncomeMoney);
vh.tvExpenseMoney = (TextView) conView
.findViewById(R.id.tvExpenseMoney);
vh.tvRecordnotFound = (TextView) conView
.findViewById(R.id.tvrecordnotFound);
vh.tvIncomeSymblIncomeDisp = (TextView) conView
.findViewById(R.id.tvIncomeSymblIncomeDisp);
vh.tvMoneyCurrencyExpense = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyExpense);
vh.tvMoneyCurrencyIncome = (TextView) conView
.findViewById(R.id.tvMoneyCurrencyIncome);
adapter = new DataBaseAdapter(contextAddBank);
arrDateDebit = new ArrayList<String>();
arrAmountDebit = new ArrayList<Double>();
arrDateCredit = new ArrayList<String>();
arrAmountCredit = new ArrayList<Double>();
epref = EPreferences.getInstance(contextAddBank);
incomes = new ArrayList<Income>();
expense = new ArrayList<Expense>();
getPrefData();
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
adapter.open();
adapter.close();
conView.setTag(vh);
} else {
vh = (ViewHolder) conView.getTag();
}
expense.clear();
incomes.clear();
arrDateCredit.clear();
arrAmountCredit.clear();
arrDateDebit.clear();
arrAmountDebit.clear();
adapter.open();
// viewHolder.rvList.setAdapter(Adapter);
incomes = adapter.read_income();
expense = adapter.read_expense();
double totalExpense = 0.0;
double totalIncome = 0.0;
DisplayMonth month = monthName.get(position);
vh.tvDate.setText(month.getMonth() + " " + yr);
months = month.getMonth();
Log.d("tagNameAdapter",
"name is " + bankNameForMatch + ":::" + month.getMonth());
Log.d("expencesize", "size is " + expense.size());
// expense = adapter.read_expense_with_bankName(bankNameForMatch,
// bankAccNoForMatch);
if (expense.size() > 0) {
for (int l = 0; l < expense.size(); l++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ expense.get(l).getBankname() + " AND "
+ expense.get(l).getAccno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch.equals(expense.get(l).getBankname())
&& bankAccNoForMatch.substring(
bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
expense.get(l)
.getAccno()
.substring(
expense.get(l)
.getAccno()
.length() - 3))) {
dateExpense = expense.get(l).getDate();
expenseAmount = expense.get(l).getAmount();
Log.i("ExpenseAmount", expenseAmount + ":::::"
+ dateExpense);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateExpense, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntExpense = Integer.parseInt(secondMonth);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameExpense", totalYear + "");
Log.i("MonthSplitExpense", firstDate + " " + secondMonth
+ " " + thirdYear);
// for (int jmon = 0; jmon < expense.size(); jmon++) {
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateExpense);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
Log.i("allYear", year + " ");
monthNameInStringExpense = getMonthName(transactionMonth);
Log.i("finddate", convertDate + ":::" + transactionMonth
+ ":::" + monthNameInStringExpense + "::"
+ transactionYear);
Log.d("tagmonth", "" + month.getMonth() + " ::: "
+ transactionMonth + " ---- " + totalYear + "::::"
+ year);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyExpenseAmount = vh.tvExpenseMoney.getText()
.toString();
Log.i("dateAmount", " " + expense.get(l).getAmount()
+ " " + expense.get(l).getDate());
arrDateDebit.add(expense.get(l).getDate());
arrAmountDebit.add(expense.get(l).getAmount());
totalExpense += expense.get(l).getAmount();
DecimalFormat decimalFormatExpense = new DecimalFormat(
"0.#");
String finalTotalExpense = decimalFormatExpense
.format(Double.valueOf(totalExpense));
String valTvExpenseAmt = new BigDecimal(
finalTotalExpense).toPlainString();
vh.tvExpenseMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvExpenseAmt))
+ " " + currencySymbl);
if (totalExpense == 0.0) {
vh.tvExpenseMoney.setText("0.0");
vh.tvMoneyCurrencyExpense.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvMoneyCurrencyExpense
.setVisibility(View.INVISIBLE);
vh.tvExpenseMoney.setText(" " + totalExpense
+ " " + currencySymbl);
vh.tvMoneyCurrencyExpense
.setText(currencySymbl);
}
}
}
}
}
}
if (incomes.size() > 0) {
for (int j = 0; j < incomes.size(); j++) {
Log.d("tagbankfil",
"" + bankNameForMatch + "=="
+ incomes.get(j).getIncome_bankname() + " AND "
+ incomes.get(j).getIncome_accno() + "=="
+ bankAccNoForMatch);
if (bankNameForMatch
.equals(incomes.get(j).getIncome_bankname())
&& bankAccNoForMatch
.substring(bankAccNoForMatch.length() - 3)
.equalsIgnoreCase(
incomes.get(j)
.getIncome_accno()
.substring(
incomes.get(j)
.getIncome_accno()
.length() - 3))) {
dateIncome = incomes.get(j).getIncome_date();
incomeAmount = incomes.get(j).getIncome_amount();
Log.i("IncomeAmount", incomeAmount + ":::::" + dateIncome);
Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
StringTokenizer tokensIncome = new StringTokenizer(
dateIncome, "-");
String firstDate = tokensIncome.nextToken();
String secondMonth = tokensIncome.nextToken();
thirdYear = tokensIncome.nextToken();
monthsInIntIncome = Integer.parseInt(thirdYear);
int totalYear = Integer.parseInt(thirdYear);
Log.i("MonthNameIncome", monthsInIntIncome + " " + ""
+ monthNameInStringIncome + " " + dateIncome + " "
+ incomes.size() + "" + totalYear);
Log.i("MonthSplitIncome", firstDate + " " + secondMonth
+ " " + thirdYear);
Log.i("loopTimes", "Check");
SimpleDateFormat sdfSource = new SimpleDateFormat(
"dd-MM-yyyy");
Date dateVal = null;
Log.i("axisbankdateval", dateVal + "");
try {
dateVal = sdfSource.parse(dateIncome);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd-MMM-yyyy");
convertDate = sdfDestination.format(dateVal);
String[] parts = convertDate.split("-");
String transactionMonth = parts[1];
String transactionYear = parts[2];
monthNameInStringIncome = getMonthName(transactionMonth);
Log.i("finddate", convertDate + "::" + monthname + "::"
+ monthNameInStringIncome);
if (month.getMonth().contains(transactionMonth)
&& totalYear == year) {
emptyIncomeAmount = vh.tvIncomeMoney.getText()
.toString();
arrDateCredit.add(incomes.get(j).getIncome_date());
arrAmountCredit.add(incomes.get(j).getIncome_amount());
totalIncome += incomes.get(j).getIncome_amount();
DecimalFormat decimalFormatIncome = new DecimalFormat(
"0.#");
String finalTotalIncome = decimalFormatIncome
.format(Double.valueOf(totalIncome));
String valTvIncomeAmt = new BigDecimal(finalTotalIncome)
.toPlainString();
vh.tvIncomeMoney.setText(String.format("%,.00f",
(double) Double.parseDouble(valTvIncomeAmt))
+ " ");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
if (totalIncome == 0.0) {
vh.tvIncomeMoney.setText("0.0");
vh.tvMoneyCurrencyIncome.setText(currencySymbl);
} else {
if (vh.tvRecordnotFound.getVisibility() == View.VISIBLE) {
vh.tvRecordnotFound.setVisibility(View.GONE);
vh.tvIncomeMoney.setText(" " + totalIncome
+ " " + currencySymbl);
}
}
}
}
}
Log.i("currentYear", year + "" + thirdYear);
}
CategoryList categoryListAdapter = new CategoryList(contextAddBank,
arrDateDebit, arrAmountDebit, arrDateCredit, arrAmountCredit);
vh.rvList.setAdapter(categoryListAdapter);
setListViewHeightBasedOnItems(vh.rvList);
vh.rvList.setScrollContainer(true);
categoryListAdapter.notifyDataSetChanged();
return conView;
}
}
Your application is sticking when you're scrolling down because you're doing all of that processing upon every move when you scroll. Every row is running through the statements of your getView method every single time it's brought back to the screen, phones don't have enough processing power for all of that. You need to separate all of that into a different class, and then load it into the adapter in a smaller data set so that all it has to do is display it. Basically, you're doing processing in the UI(Main) thread, which is bad.
Given how you also have nested listViews, changing to an expandedListView would also be a lot easier for you in the grand scheme of things, may do the job better. Here's a tutorial for it: https://www.youtube.com/watch?v=BkazaAeeW1Q
I'm coding a method that solve various kind of equation. Now I want that the method receives a String equation that could be in the forms:
ax^2+bx+c=0
or
*ax^2+c=0*
or
bx+c=0
etc. and the order shouldn't matter.
My problem is: How could I parse the equation according the "x" grade?
The eq could contains more values of the same grade for example 2x^2+4x^2+3x+8=2 (max grade x^3).
My method should assign the a value to double a[] if on the left or on the right of a there is x^2, double b[], if on the left or on the right there is x, and double c[] if there isn't any x variable near the value (and should change the value sign if the therms is after the =).
Convert a String number in a double is simple but I don't know how I could disassemble the input String according the x grade as described.
Tested for -2x + 3x^2 - 2 + 3x = 3 - 2x^2
public Double[] parseEquation(String equation)
{
Log.d(TAG, "equation: " + equation);
// Remove all white spaces
equation = equation.replaceAll("[ ]", "");
// Get the left and right sides of =
String[] sides = equation.split("[=]"); // should be of size 2
boolean leftNegative = false;
boolean rightNegative = false;
if (sides.length != 2)
{
// There is no = or more than one = signs.
}
else
{
// if sides i starts with + remove the +
// if - we remove and put it back later
for (int i = 0; i < 2; i++)
{
if (sides[i].charAt(0) == '+')
{
sides[i] = sides[i].substring(1);
}
}
if (sides[0].charAt(0) == '-')
{
leftNegative = true;
sides[0] = sides[0].substring(1);
}
if (sides[1].charAt(0) == '-')
{
rightNegative = true;
sides[1] = sides[1].substring(1);
}
}
Log.d(TAG, "left side:" + sides[0] + " right side: " + sides[1]);
// Terms without signs need to find out later
String[] leftTerms = sides[0].split("[+-]");
String[] rightTerms = sides[1].split("[+-]");
int length = leftTerms[0].length();
if (leftNegative)
{
leftTerms[0] = "-" + leftTerms[0];
}
// put in the minus sign for the rest of the terms
for (int i = 1; i < leftTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[0].charAt(length));
if (sides[0].charAt(length) == '-')
{
leftTerms[i] = "-" + leftTerms[i];
length += leftTerms[i].length();
}
else
{
length += leftTerms[i].length() + 1;
}
}
length = rightTerms[0].length();
if (rightNegative)
{
rightTerms[0] = "-" + rightTerms[0];
}
for (int i = 1; i < rightTerms.length; i++)
{
Log.d(TAG, "length = " + length + " " + sides[1].charAt(length));
if (sides[1].charAt(length) == '-')
{
rightTerms[i] = "-" + rightTerms[i];
length += rightTerms[i].length();
}
else
{
length += rightTerms[i].length() + 1;
}
}
// Now we put all the factors and powers in a list
List<ContentValues> leftLists = new ArrayList<ContentValues>();
// left side
for (int i = 0; i < leftTerms.length; i++)
{
Log.d(TAG, "leftTerm: " + leftTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = leftTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no x mean a constant term
contentValues.put("factor", leftTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = leftTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = leftTerms[i].substring(indexOfX + 2).trim();
String factor = leftTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
leftLists.add(contentValues);
}
List<ContentValues> rightLists = new ArrayList<ContentValues>();
for (int i = 0; i < rightTerms.length; i++)
{
Log.d(TAG, "rightTerm: " + rightTerms[i]);
ContentValues contentValues = new ContentValues();
int indexOfX = rightTerms[i].indexOf('x');
if (indexOfX == -1)
{
// no hat mean a constant term
contentValues.put("factor", rightTerms[i]);
contentValues.put("power", "0");
}
else
{
int indexOfHat = rightTerms[i].indexOf('^');
if (indexOfHat == -1)
{
// no hat mean power = 1
contentValues.put("power", "1");
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
}
else
{
String power = rightTerms[i].substring(indexOfX + 2).trim();
String factor = rightTerms[i].substring(0, indexOfX).trim();
contentValues.put("factor", factor);
contentValues.put("power", power);
}
}
Log.d(TAG, contentValues.toString());
rightLists.add(contentValues);
}
// Now add the factors with same powers.
// Suppose we solve for cubic here the end result will be
// 4 terms constant, x, x^2 and x^3
// Declare a double array of dim 4 the first will hold constant
// the second the x factor etc...
// You can allow arbitrary power by looping through the lists and get the max power
Double[] result = new Double[]{0.0, 0.0, 0.0, 0.0};
for (ContentValues c : leftLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] += c.getAsDouble("factor");
break;
case 1:
result[1] += c.getAsDouble("factor");
break;
case 2:
result[2] += c.getAsDouble("factor");
break;
case 3:
result[3] += c.getAsDouble("factor");
break;
}
}
for (ContentValues c : rightLists)
{
switch (c.getAsInteger("power"))
{
case 0:
//Log.d(TAG, "power = 0, factor = " + c.toString());
result[0] -= c.getAsDouble("factor");
break;
case 1:
result[1] -= c.getAsDouble("factor");
break;
case 2:
result[2] -= c.getAsDouble("factor");
break;
case 3:
result[3] -= c.getAsDouble("factor");
break;
}
}
Log.d(TAG, "constant term = " + result[0] + ", x^1 = " + result[1]
+ ", x^2 = " + result[2] + ", x^3 = " + result[3]);
return result;
}
If you weren't limited by Android, I'd suggest using a lexer and parser. These are code generators, so they can work anywhere the base language works, but they tend to produce bloated code. Android might not appreciate that.
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);