Recursive(Tower Hanoi) UI for android - android

`[I want to change the UI through the recursive function.
I want to implement UI through recursive function. When you run it, you should see the process of changing the UI according to the value, but if you insert hanoi(), the process does not come out and the value is printed at once. I think I need to change the move, but it's the same if I put sleep() in the move, and I tried Thread, Handler, AsyncTask, but the results are the same. I'd appreciate your help.
public class Disk3 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
class BackgroundThread extends Thread {
boolean running = false;
#Override
public void run() {
running = true;
while (running) {
runOnUiThread(new Runnable() {
#Override
public void run() {
move(3, 1, 3);
}
});
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
btn_move.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundThread thread = new BackgroundThread();
thread.start();
}
});
public void move(int N, int start, int to) {
if (start == 1) {
for (int i = 0; i <= 2; i++) {
if (list_tv_diskA[i].getVisibility() == View.VISIBLE) {
startTv = list_tv_diskA[i];
startTv.setVisibility(View.INVISIBLE);
Log.d("TAG", "list_tv_disk A :: " + i);
break;
}
}
}
if (start == 2) {
for (int j = 0; j <= 2; j++) {
if (list_tv_diskB[j].getVisibility() == View.VISIBLE) {
startTv = list_tv_diskB[j];
startTv.setVisibility(View.INVISIBLE);
Log.d("TAG", "list_tv_disk B :: " + j);
break;
}
}
}
if (start == 3) {
for (int k = 0; k <= 2; k++) {
if (list_tv_diskC[k].getVisibility() == View.VISIBLE) {
startTv.setText(toTv.getText());
startTv = list_tv_diskC[k];
startTv.setVisibility(View.INVISIBLE);
Log.d("TAG", "list_tv_disk C :: " + k);
break;
}
}
}
if (to == 1) {
for (int i = 2; i >= 0; i--) {
if (list_tv_diskA[i].getVisibility() == View.INVISIBLE) {
toTv = list_tv_diskA[i];
toTv.setText(startTv.getText());
toTv.setVisibility(View.VISIBLE);
Log.d("TAG", "list_tv_disk B :: " + i);
break;
}
}
}
if (to == 2) {
for (int j = 2; j >= 0; j--) {
if (list_tv_diskB[j].getVisibility() == View.INVISIBLE) {
toTv = list_tv_diskB[j];
toTv.setText(startTv.getText());
toTv.setVisibility(View.VISIBLE);
Log.d("TAG", "list_tv_disk Bda :: " + j);
break;
}
}
}
if (to == 3) {
for (int k = 2; k >= 0; k--) {
if (list_tv_diskC[k].getVisibility() == View.INVISIBLE) {
toTv = list_tv_diskC[k];
toTv.setText(startTv.getText());
toTv.setVisibility(View.VISIBLE);
Log.d("TAG", "list_tv_disk C :: " + k);
break;
}
}
}
public void Hanoi(int N, int start, int to, int via) {
if (N == 1) {
move(1, start, to);
return;
} else {
Hanoi(N - 1, start, via, to);
move(N, start, to);
Hanoi(N - 1, via, to, start);
}
}

Related

How to fill a huge TableLayout without causing timeout ARNs?

I have a TableLayout with some hundreds of tablerows.
I'm filling it with a thread, which notifies to a handler when a row is created, and the handler adds the row in the UI thread. But the problem is that in some cases some users are reporting ARN due to:
Input dispatching timed out (Waiting to send key event because the
focused window has not finished processing all of the input events
that were previously delivered to it. Outbound queue length: 0. Wait
queue length: 1.)
The Android OS handles creating a ANR when it detects the UI/Main thread has been blocking for 5 seconds.
I thought using AsyncTask but is going to be deprecated in Android 11.
This is my thread:
private class PopulateTableThread extends Thread {
private Context context;
private ArrayList<Player> players;
public PopulateTableThread(Context context, ArrayList<Player> players) {
super();
this.context = context;
this.players = players;
}
public void run() {
for (int i=0; i<players.size(); i++) {
TableRow row = new TableRow(context);
row.setLayoutParams(rowParams);
row.setBackgroundResource(R.drawable.table_row_not_selected);
String strings[] = {players.get(i).getName(),
"" + players.get(i).getTeam().getName(),
"" + players.get(i).getPositionInString(context),
"" + players.get(i).getYearsOfContractFormatted(),
"" + players.get(i).getValue() + " M€",
"" + players.get(i).getSalary() + " M€",
"" + players.get(i).getAge(),
"" + players.get(i).getBaseLevel()};
for (int j = 0; j < strings.length; j++) {
TextView text = new TextView(context);
text.setBackgroundResource(R.drawable.table_cell_background);
if (j == 0) {
text.setLayoutParams(nameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
}else if (j == 1) {
text.setLayoutParams(teamNameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
} else if (j == 2 || j == 3) {
text.setLayoutParams(positionAndContractParams);
text.setGravity(Gravity.CENTER);
} else if (j == 4) {
text.setLayoutParams(valueParams);
text.setGravity(Gravity.CENTER);
} else if (j == 5) {
text.setLayoutParams(salaryParams);
text.setGravity(Gravity.CENTER);
} else if (j == 6 || j == 7) {
text.setLayoutParams(ageAndLevelParams);
text.setGravity(Gravity.CENTER);
}
if (j == 3 && strings[3].split("/")[0].equals("1")) {
text.setBackgroundResource(R.drawable.table_cell_background_danger);
}
text.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
text.setText(strings[j]);
row.addView(text);
}
ProgressBar levelProgress = new ProgressBar(new ContextThemeWrapper(context, R.style.ProgressBar), null, 0);
levelProgress.setBackgroundResource(R.drawable.table_cell_background);
levelProgress.setLayoutParams(levelBarParams);
levelProgress.setMinimumHeight((int) getResources().getDimension(R.dimen.cell_height));
levelProgress.setProgress(players.get(i).getBaseLevel());
levelProgress.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
row.addView(levelProgress);
final int finalIndex = i;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (searchProgressBar.getVisibility() == View.VISIBLE) {
return;
}
SoundEffectsManager.getInstance().play(context, SoundEffectsManager.button);
displaySignDialog(players.get(finalIndex));
}
});
Message message = new Message();
message.what = HANDLER_ROW_CREATED;
message.obj = row;
updateTableHandler.sendMessage(message);
}
Message message = new Message();
message.what = HANDLER_TABLE_FILLED;
updateTableHandler.sendMessage(message);
}
}
And this is the handler that it's updating the ui thread when the thread has created a new TableRow:
updateTableHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case HANDLER_ROW_CREATED:
TableRow row = (TableRow) msg.obj;
tableLayout.addView(row);
break;
case HANDLER_TABLE_FILLED:
tableLayout.setAlpha(1f);
searchProgressBar.setVisibility(View.GONE);
break;
}
}
};
How can i avoid these ARN reports?
Trying to do David Wasser solution, but with same problem:
private class PopulateTableThread extends Thread {
private Context context;
private ArrayList<Player> players;
public PopulateTableThread(Context context, ArrayList<Player> players) {
super();
this.context = context;
this.players = players;
}
public void run() {
Log.d("XXX_SeekerActivity","filling table with "+players.size()+" players");
for (int i=0; i<players.size(); i++) {
final String strings[] = {players.get(i).getName(),
"" + players.get(i).getTeam().getName(),
"" + players.get(i).getPositionInString(context),
"" + players.get(i).getYearsOfContractFormatted(),
"" + players.get(i).getValue() + " M€",
"" + players.get(i).getSalary() + " M€",
"" + players.get(i).getAge(),
"" + players.get(i).getBaseLevel()};
final int finalI = i;
runOnUiThread(new Runnable() {
#Override
public void run() {
TableRow row = new TableRow(context);
row.setLayoutParams(rowParams);
row.setBackgroundResource(R.drawable.table_row_not_selected);
for (int j = 0; j < strings.length; j++) {
TextView text = new TextView(context);
text.setBackgroundResource(R.drawable.table_cell_background);
if (j == 0) {
text.setLayoutParams(nameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
}else if (j == 1) {
text.setLayoutParams(teamNameParams);
text.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
text.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
text.setMaxLines(1);
text.setEllipsize(TextUtils.TruncateAt.END);
} else if (j == 2 || j == 3) {
text.setLayoutParams(positionAndContractParams);
text.setGravity(Gravity.CENTER);
} else if (j == 4) {
text.setLayoutParams(valueParams);
text.setGravity(Gravity.CENTER);
} else if (j == 5) {
text.setLayoutParams(salaryParams);
text.setGravity(Gravity.CENTER);
} else if (j == 6 || j == 7) {
text.setLayoutParams(ageAndLevelParams);
text.setGravity(Gravity.CENTER);
}
if (j == 2) {
switch (players.get(finalI).getPosition()) {
case Player.PLAYER_POSITION_GOALKEEPER:
text.setBackgroundResource(R.drawable.table_cell_background_position_gk);
break;
case Player.PLAYER_POSITION_DEFENDER:
text.setBackgroundResource(R.drawable.table_cell_background_position_def);
break;
case Player.PLAYER_POSITION_MIDFIELDER:
text.setBackgroundResource(R.drawable.table_cell_background_position_mid);
break;
case Player.PLAYER_POSITION_FORWARD:
text.setBackgroundResource(R.drawable.table_cell_background_position_fw);
break;
}
}
if (j == 3 && strings[3].split("/")[0].equals("1")) {
text.setBackgroundResource(R.drawable.table_cell_background_danger);
}
text.setMinHeight((int) getResources().getDimension(R.dimen.cell_height));
text.setText(strings[j]);
row.addView(text);
}
ProgressBar levelProgress = new ProgressBar(new ContextThemeWrapper(context, R.style.ProgressBar), null, 0);
levelProgress.setBackgroundResource(R.drawable.table_cell_background);
levelProgress.setLayoutParams(levelBarParams);
levelProgress.setMinimumHeight((int) getResources().getDimension(R.dimen.cell_height));
levelProgress.setProgress(players.get(finalI).getBaseLevel());
levelProgress.setPadding((int) getResources().getDimension(R.dimen.spacing_small), 0, (int) getResources().getDimension(R.dimen.spacing_small), 0);
row.addView(levelProgress);
final int finalIndex = finalI;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (searchProgressBar.getVisibility() == View.VISIBLE) {
return;
}
SoundEffectsManager.getInstance().play(context, SoundEffectsManager.button);
displaySignDialog(players.get(finalIndex));
}
});
row.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(final View view, MotionEvent motionEvent) {
if (searchProgressBar.getVisibility() == View.VISIBLE) {
return true;
}
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
delayColorizeHandler.postDelayed(new Runnable() {
#Override
public void run() {
Util.getInstance().colorizeBackgroundCheckingApiLevel(view);
}
}, Util.WAIT_TIME_BEFORE_TOUCH_COLORIZE);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
delayColorizeHandler.removeCallbacksAndMessages(null);
Util.getInstance().clearBackgroundColorFilter(view);
break;
}
return false;
}
});
tableLayout.addView(row);
}
});
}
runOnUiThread(new Runnable() {
#Override
public void run() {
tableLayout.setAlpha(1f);
searchProgressBar.setVisibility(View.GONE);
}
});
}
}
You can't create and manipulate UI elements (TableRow, TextView, etc.) on a background thread. All this stuff needs to be done on the main (UI) thread directly. You are probably creating object locks on parts of the UI framework that is blocking the main (UI) thread and causing your ANR.
Have your background thread loop over your players and get the data for each one. Then it can post a Runnable to the main (UI) thread (once for each player) with the player data and in the Runnable (which will run on the main (UI) thread) you can create the UI elements and add them to your layout.
By doing this in a loop in a background thread, you won't block the UI thread.

Android: Loading Fragment is Slow to Get String Values From SQLite

I try to use SQLite database to get String values and set these values into TextViews in Fragment.The String values are gotten when Boolean variables are returned true, and when loading the fragment, it takes little bit long time to load.
I have tried to use multiple threads to solve the problem but it does not work apparently. Do you have any idea to be faster load the fragment?
This is a class that be called in the fragment
public class Schedule_Config_Monday{
private Context mContext;
public Schedule_Config_Monday(Context context){
this.mContext = context;
}
public void Monday_Schedule_Settings_0(final TextView textView_1,final TextView textView_2,final TextView textView_3,final TextView textView_4,final TextView textView_5,
final TextView textView_6,final TextView textView_7,final TextView textView_8,final TextView textView_9,final TextView textView_10,
final TextView textView_11,final TextView textView_12,final TextView textView_13,final TextView textView_14,final TextView textView_15,
final TextView textView_16,final TextView textView_17,final TextView textView_18,final TextView textView_19,final TextView textView_20,
final TextView textView_21,final TextView textView_22,final TextView textView_23,final TextView textView_24){
final DatabaseTimetable databaseTimetable = new DatabaseTimetable(mContext);
final boolean[] monday_b = new boolean[]{
databaseTimetable.Monday_Start_End_Time(0,1),
databaseTimetable.Monday_Start_End_Time(0,2),
databaseTimetable.Monday_Start_End_Time(0,3),
databaseTimetable.Monday_Start_End_Time(0,4),
databaseTimetable.Monday_Start_End_Time(0,5),
databaseTimetable.Monday_Start_End_Time(0,6),
databaseTimetable.Monday_Start_End_Time(0,7),
databaseTimetable.Monday_Start_End_Time(0,8),
databaseTimetable.Monday_Start_End_Time(0,9),
databaseTimetable.Monday_Start_End_Time(0,10),
databaseTimetable.Monday_Start_End_Time(0,11),
databaseTimetable.Monday_Start_End_Time(0,12),
databaseTimetable.Monday_Start_End_Time(0,13),
databaseTimetable.Monday_Start_End_Time(0,14),
databaseTimetable.Monday_Start_End_Time(0,15),
databaseTimetable.Monday_Start_End_Time(0,16),
databaseTimetable.Monday_Start_End_Time(0,17),
databaseTimetable.Monday_Start_End_Time(0,18),
databaseTimetable.Monday_Start_End_Time(0,19),
databaseTimetable.Monday_Start_End_Time(0,20),
databaseTimetable.Monday_Start_End_Time(0,21),
databaseTimetable.Monday_Start_End_Time(0,22),
databaseTimetable.Monday_Start_End_Time(0,23),
databaseTimetable.Monday_Start_End_Time(0,0)
};
final TextView[] Mon_Text = new TextView[]{
textView_1,textView_2,textView_3,textView_4,textView_5,
textView_6,textView_7,textView_8,textView_9,textView_10,
textView_11,textView_12,textView_13,textView_14,textView_15,
textView_16,textView_17,textView_18,textView_19,textView_20,
textView_21,textView_22,textView_23,textView_24};
final int start = 0;
if (monday_b[0]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 1;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
Mon_Text[0].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
});
}
else if (monday_b[1]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 2;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[2]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 3;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[3]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 4;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[4]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 5;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[5]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 6;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[6]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 7;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[7]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 8;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[8]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 9;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[9]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 10;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[10]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 11;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[11]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 12;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[12]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 13;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[13]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 14;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[14]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 15;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[15]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 16;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[16]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 17;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[17]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 18;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[18]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 19;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[19]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 20;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[20]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 21;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[21]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 22;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[22]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 23;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < end; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
else if (monday_b[23]){
Mon_Text[0].post(new Runnable() {
#Override
public void run() {
int end = 0;
Mon_Text[0].setText(databaseTimetable.Monday_Title(start,end));
Mon_Text[0].setTextColor(Color.parseColor(databaseTimetable.Monday_Text_Color(start,end)));
for (int i = 0; i < 24; i++){
Mon_Text[i].setBackgroundColor(Color.parseColor(databaseTimetable.Monday_Text_BG_Color(start,end)));
}
}
});
}
}
}
These are methods inside of a class extends SQLiteOpenHelper to get Title, Text Color and Background Color
public String Monday_Title(int start, int end){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{COLUMN_TITLE,COLUMN_SUBTITLE,
COLUMN_MON,COLUMN_START_TIME,COLUMN_END_TIME};
#SuppressLint("Recycle")
Cursor cursor = sqLiteDatabase.query(TABLE_TIMETABLE,columns,COLUMN_MON + "=" + 1 + " AND " + COLUMN_START_TIME + " = " + start + " AND " + COLUMN_END_TIME + " = " + end,null,null,null,null);
int iTitle = cursor.getColumnIndex(COLUMN_TITLE);
int iSubtitle = cursor.getColumnIndex(COLUMN_SUBTITLE);
StringBuilder result = new StringBuilder();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.append(cursor.getString(iTitle)).append("\n").append("\n").append(cursor.getString(iSubtitle)).append("\n\n");
}
sqLiteDatabase.close();
return result.toString();
}
//Monday Get TextColor
public String Monday_Text_Color(int start, int end){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{COLUMN_TITLE,COLUMN_SUBTITLE, COLUMN_COLOR_TEXT,
COLUMN_MON,COLUMN_START_TIME,COLUMN_END_TIME};
#SuppressLint("Recycle")
Cursor cursor = sqLiteDatabase.query(TABLE_TIMETABLE,columns,COLUMN_MON + "=" + 1 + " AND " + COLUMN_START_TIME + " = " + start + " AND " + COLUMN_END_TIME + " = " + end,null,null,null,null);
int iTextColor = cursor.getColumnIndex(COLUMN_COLOR_TEXT);
StringBuilder result = new StringBuilder();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.append("#").append(cursor.getString(iTextColor));
}
sqLiteDatabase.close();
return result.toString();
}
//Monday Get Text Background Color
public String Monday_Text_BG_Color(int start, int end){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{COLUMN_TITLE,COLUMN_SUBTITLE, COLUMN_COLOR_TEXT_BG,
COLUMN_MON,COLUMN_START_TIME,COLUMN_END_TIME};
#SuppressLint("Recycle")
Cursor cursor = sqLiteDatabase.query(TABLE_TIMETABLE,columns,COLUMN_MON + "=" + 1 + " AND " + COLUMN_START_TIME + " = " + start + " AND " + COLUMN_END_TIME + " = " + end,null,null,null,null);
int iTextColor_BG = cursor.getColumnIndex(COLUMN_COLOR_TEXT_BG);
StringBuilder result = new StringBuilder();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.append("#").append(cursor.getString(iTextColor_BG));
}
sqLiteDatabase.close();
return result.toString();
}
This is a method that returns true if defined start and end are in the database
public Boolean Monday_Start_End_Time(int start, int end){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{COLUMN_MON,COLUMN_START_TIME,COLUMN_END_TIME};
#SuppressLint("Recycle")
Cursor cursor = sqLiteDatabase.query(TABLE_TIMETABLE,columns,COLUMN_MON + "=" + 1 + " AND " + COLUMN_START_TIME + " = " + start + " AND " + COLUMN_END_TIME + " = " + end,null,null,null,null);
boolean result = cursor.moveToFirst();
cursor.close();
sqLiteDatabase.close();
return result;
}
I am currently thinking what makes slow loading fragment is this Boolean check, so that I tried to create a function that returns integer value when the boolean variables are true, but it also slow to load the fragment.
And I am sure the problem is method of public void Monday_Schedule_Settings_0 because when I remove the code, the fragment loads definitely faster.
I would love to hear you advise.
I think your performance problem is that you're closing the database and reopening it with every DB query. You should be closing the cursors, but not closing the database itself. IE you should remove every instance of:
sqliteDatabase.close();

How to call text Watcher when user update any value from edit text

i have button,on button click it create editText with value, value of edit text is depending on count of total edit texts.for example edittext1 = 100, when user create two edit text then the value will be like this edittext1 = 50,edittext2 = 50 and so on.( value = 100/ total no of edittext) which i set equally to each edit text.now the problem is when user want to change/update any value from edittext, i want to update value of each edittext according to user's newly entered value.
i want to call textwatcher when value changed by only user,in my case when user click on button it will call.
thank you.
here is my code
public class StageForm extends BaseActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stage_form);
spinnerProjectStage = (Spinner) findViewById(R.id.spinnerAddProjectStage);
spinnerProjectList = (Spinner) findViewById(R.id.spinnerProjectList);
stageLinearLayout = (LinearLayout) findViewById(R.id.stageProjectList);
btnAddMoreStage = (Button) findViewById(R.id.btnAddMoreStage);
btnAddMoreStage.setOnClickListener(this);
getProjectStage();
}
public void onClick(View v) {
if (v.getId() == R.id.btnAddMoreStage) {
public void addMoreFields () {
try {
k++;
flag = k;
final LinearLayout.LayoutParams lparams;
lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout[flag] = new LinearLayout(StageForm.this);
layout[flag].setLayoutParams(lparams);
layout[flag].setId(flag);
txtStageName[flag] = new EditText(StageForm.this);
txtStageName[flag].setLayoutParams(lparams);
txtStageName[flag].setHint("stage " + k + "");
txtStageName[flag].setId(flag);
txtStagePercent[flag] = new EditText(StageForm.this);
txtStagePercent[flag].setLayoutParams(lparams);
txtStagePercent[flag].setHint("percent");
txtStagePercent[flag].setId(flag);
txtStagePercent[flag].addTextChangedListener(stagePercentChangeListener);
if (flag == 0) {
txtStagePercent[flag].setText(String.valueOf(totalPercent));
} else {
countEditText = flag + 1;
calculatePercentage(countEditText, flag);
}
} catch (Exception e) {
e.printStackTrace();
}
layout[flag].addView(txtStageName[flag]);
layout[flag].addView(txtStagePercent[flag]);
stageLinearLayout.addView(layout[flag]);
}
}
}
private void calculatePercentage(int countEditText, int flag) {
k = flag;
if (flag == 0) {
// countEditText = flag;
lastTextBox = countEditText;
} else {
// countEditText = flag;
lastTextBox = countEditText - 1;
}
result = totalPercent / countEditText;
convertFloatResult = Math.round(result);
remainingPercent = totalPercent - (convertFloatResult * countEditText);
lastTextValue = convertFloatResult + remainingPercent;
try {
if (remainingPercent == 0) {
for (int j = 0; j <= lastTextBox; j++) {
txtStagePercent[j].setText(String.valueOf(convertFloatResult));
}
txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue));
} else {
for (int j = 0; j < lastTextBox; j++) {
txtStagePercent[j].setText(String.valueOf(convertFloatResult));
}
txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private TextWatcher stagePercentChangeListener = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (flag == 0) {
} else {
String getbeforValue = String.valueOf(s);
beforeTextChanged = Integer.parseInt(getbeforValue);
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String getchangedValue = String.valueOf(s);
afterTextChanged = Integer.parseInt(getchangedValue);
}
#Override
public void afterTextChanged(Editable s) {
totalPercent = totalPercent - afterTextChanged;
countEditText = countEditText - 1;
calculatePercentage(countEditText, flag);
}
};
}

Check all the view's background in an if statement in Android?

I have many buttons(81) from the left and right part of my layout. All in all, I have 162 buttons. I put those buttons to Button[] and I handle it properly.
private int[] right_lung = { R.id.btn_right_106, R.id.btn_right_113,
R.id.btn_right_114, R.id.btn_right_115, R.id.btn_right_116, R.id.btn_right_121,
R.id.btn_right_122, R.id.btn_right_123, R.id.btn_right_124, R.id.btn_right_125,
R.id.btn_right_129, R.id.btn_right_130, R.id.btn_right_131, R.id.btn_right_132,
R.id.btn_right_133, R.id.btn_right_134, R.id.btn_right_137, R.id.btn_right_138,
R.id.btn_right_139, R.id.btn_right_140, R.id.btn_right_141, R.id.btn_right_142,
R.id.btn_right_143, R.id.btn_right_145, R.id.btn_right_146, R.id.btn_right_147,
R.id.btn_right_148, R.id.btn_right_149, R.id.btn_right_150, R.id.btn_right_151,
R.id.btn_right_152, R.id.btn_right_153, R.id.btn_right_154, R.id.btn_right_155,
R.id.btn_right_156, R.id.btn_right_157, R.id.btn_right_158, R.id.btn_right_159,
R.id.btn_right_160, R.id.btn_right_161, R.id.btn_right_162, R.id.btn_right_163,
R.id.btn_right_164, R.id.btn_right_165, R.id.btn_right_166, R.id.btn_right_167,
R.id.btn_right_168, R.id.btn_right_169, R.id.btn_right_170, R.id.btn_right_171,
R.id.btn_right_172, R.id.btn_right_173, R.id.btn_right_174, R.id.btn_right_175,
R.id.btn_right_176, R.id.btn_right_177, R.id.btn_right_178, R.id.btn_right_179,
R.id.btn_right_180, R.id.btn_right_181, R.id.btn_right_182, R.id.btn_right_183,
R.id.btn_right_184, R.id.btn_right_185, R.id.btn_right_186, R.id.btn_right_187,
R.id.btn_right_188, R.id.btn_right_189, R.id.btn_right_190, R.id.btn_right_191,
R.id.btn_right_192, R.id.btn_right_194, R.id.btn_right_195, R.id.btn_right_196,
R.id.btn_right_197, R.id.btn_right_198, R.id.btn_right_199, R.id.btn_right_200,
R.id.btn_right_205, R.id.btn_right_206, R.id.btn_right_207 };
private Button[] btn_right = new Button[right_lung.length];
private int[] left_lung = { R.id.btn_left_7, R.id.btn_left_13, R.id.btn_left_14,
R.id.btn_left_15, R.id.btn_left_16, R.id.btn_left_20, R.id.btn_left_21,
R.id.btn_left_22, R.id.btn_left_23, R.id.btn_left_24, R.id.btn_left_27,
R.id.btn_left_28, R.id.btn_left_29, R.id.btn_left_30, R.id.btn_left_31,
R.id.btn_left_32, R.id.btn_left_34, R.id.btn_left_35, R.id.btn_left_36,
R.id.btn_left_37, R.id.btn_left_38, R.id.btn_left_39, R.id.btn_left_40,
R.id.btn_left_41, R.id.btn_left_42, R.id.btn_left_43, R.id.btn_left_44,
R.id.btn_left_45, R.id.btn_left_46, R.id.btn_left_47, R.id.btn_left_48,
R.id.btn_left_49, R.id.btn_left_50, R.id.btn_left_51, R.id.btn_left_52,
R.id.btn_left_53, R.id.btn_left_54, R.id.btn_left_55, R.id.btn_left_56,
R.id.btn_left_57, R.id.btn_left_58, R.id.btn_left_59, R.id.btn_left_60,
R.id.btn_left_61, R.id.btn_left_62, R.id.btn_left_63, R.id.btn_left_64,
R.id.btn_left_65, R.id.btn_left_66, R.id.btn_left_67, R.id.btn_left_68,
R.id.btn_left_69, R.id.btn_left_70, R.id.btn_left_71, R.id.btn_left_72,
R.id.btn_left_73, R.id.btn_left_74, R.id.btn_left_75, R.id.btn_left_76,
R.id.btn_left_77, R.id.btn_left_78, R.id.btn_left_79, R.id.btn_left_80,
R.id.btn_left_81, R.id.btn_left_82, R.id.btn_left_83, R.id.btn_left_84,
R.id.btn_left_85, R.id.btn_left_86, R.id.btn_left_87, R.id.btn_left_88,
R.id.btn_left_89, R.id.btn_left_90, R.id.btn_left_91, R.id.btn_left_92,
R.id.btn_left_93, R.id.btn_left_94, R.id.btn_left_95, R.id.btn_left_98,
R.id.btn_left_99, R.id.btn_left_100, };
private Button[] btn_left = new Button[left_lung.length];
Whenever I click on the button, just like in mine sweeper game, many buttons are randomly opened. And when it is opened, I am changing its background into R.drawable.affected. The goal of the game is to open all the buttons in left and right. My question is this, how can I check if all of the buttons are set in R.drawable.affected? Because after that, I will execute a method that will congratulate the user. Thanks in advance.
EDIT:
for (int i = 0; i < btn_right.length; i++) {
final int a = i;
int counter_total_affected = 0;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 1) {
right_lung.add(a);
btn_right[a].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
} else if (counter == 2) {
for (int i = 0; i < 2; i++) {
int n = i;
right_lung.add(a + n);
}
try {
for (int i = 0; i < 2; i++) {
int n = i;
btn_right[a + n].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (counter == 3) {
right_lung.add(a);
btn_right[a].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
} else if (counter == 4) {
for (int i = 0; i < 25; i++) {
int n = i;
right_lung.add(a + n);
}
try {
for (int i = 0; i < 25; i++) {
int n = i;
btn_right[a + n].setBackgroundResource(R.drawable.affected);
counter_total_affected++;
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (counter == ...) {
//statements...
} else if (counter_total_affected == (btn_left.length + btn_right.length)) {
//CONGRATULATORY METHOD
}
counter++;
}
}
Increment the counter each time you change background of button and compare its value with length of button array. if both are same that means, all button backgrounds are set.
Try this :
for (int i = 0; i < btn_right.length; i++) {
final int b = i;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if btn_right[i].getDrawable().getConstantState().equals
(getResources().getDrawable(R.drawable.affected).getConstantState()))
{
if(counter == btn_right.length){
//Congratulate user...
}
}else{
btn_right[b].setBackgroundResource(R.drawable.affected);
counter++;
}
}
}
U can set Tag:
for (int i = 0; i < btn_right.length; i++) {
final int b = i;
btn_right[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 1) {
right_affected.add(b);
btn_right[b].setBackgroundResource(R.drawable.affected);
btn_right[b].setTag('1');
} else {
//some stuff here...
}
}
}
after congratulate the user set its Tag to 0.
EDIT:
ArrayList<Integer> arrayofId =new ArrayList<Integer>();
#Override
public void onClick(View v) {
if (counter == 1) {
right_affected.add(b);
btn_right[b].setBackgroundResource(R.drawable.affected);
arrayofId.add(b);//need to convert int to Integer.
} else {
//some stuff here...
}
}
To congratulate:
for(int i=0;i<arrayofId.size();i++)
{
// you can get here id of effected buttons
}

Application randomly stops responding.

I am new to programming and I'm making a very simple blackjack game with only basic functions. When I run the program on the emulator it runs maybe for one hand, two, sometimes 5 or more but it always stops responding at some stage when i click on one of the three butons. There is a splash screen that runs for three seconds and the there is a thread comming from that activity that starts this menu activity. Could anyone maybe tell why this is happening? It usually happens when I clcik on one of the buttons even though there is no much comput
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btDeal = (Button) findViewById(R.id.deal);
playerCards1 = (TextView) findViewById(R.id.playerCards);
playerPoints = (TextView) findViewById(R.id.playerPoints);
dealerCards1 = (TextView) findViewById(R.id.dealerCard);
mpBusted= MediaPlayer.create(this, R.raw.busted);
mpWin = MediaPlayer.create(this, R.raw.win);
mpShuffling = MediaPlayer.create(this, R.raw.shuffling);
mpEven = MediaPlayer.create(this, R.raw.even);
mpHit= MediaPlayer.create(this, R.raw.hit);
btDeal.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
deal ();
}
}); //getTotalDealerCards()
//getTotalPlayerCards()
btHit = (Button) findViewById(R.id.hit);
btHit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Boolean busted = isBusted();
if(!busted){
hitPlayer();
playerCards1.setText(getPlayerCardsToString());
if (isBusted()){
mpBusted.start();
}else{
playerCards1.setText(getPlayerCardsToString());
playerPoints.setText(Integer.toString(getTotalPlayerPoints()));
}
}
}
});
btStand = (Button) findViewById(R.id.stand);
btStand.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
checkWinner();
}// testValue(getTotalPlayerCards())
});
}
/*********** Function declarations starts here **********/
//Sum and return the total points for the dealer cards
public int getTotalDealerPoints(){
int points = 0;
int aceFlag = 0; //flag to deal with Aces
int counter;
for (counter = 0; counter <= getTotalDealerCards(); counter++){
if (dealerCards [counter].getCard() + 1 == 1){
points += 11;
aceFlag++;
}
else if (dealerCards [counter].getCard() + 1 > 10)
points += 10;
else
points += dealerCards [counter].getCard() + 1;
}
do {
if (points > 21 && aceFlag > 0){
points -= 10;
aceFlag--;
}
} while (aceFlag>0);
return points;
}
//Get the total player points deal
public int getTotalPlayerPoints(){
int points = 0;
int aceFlag = 0; //flag to deal with Aces
int counter;
for (counter = 0; counter <= getTotalPlayerCards(); counter++){
if (playerCards [counter].getCard() + 1 == 1){
points += 11;
aceFlag++;
}
else if (playerCards [counter].getCard() + 1 > 10)
points += 10;
else
points += playerCards [counter].getCard() + 1;
}
do {
if (points > 21 && aceFlag > 0){
points -= 10;
aceFlag--;
}
} while (aceFlag>0);
return points;
}
//Deal function to start hand
public void deal (){
// If deal is pressed reset all and start over.
mpShuffling.start();
totalDealerPoints = 0;
totalPlayerPoints = 0;
totalCreatedCards = 0;
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
// create dealer & player cards and save them to dealer, player and total arrays.
for (int dealcounter = 0; dealcounter <=1 ; dealcounter++){
dealerCards[dealcounter]= createCard();
addCardToCreatedCards(dealerCards[dealcounter]);
playerCards[dealcounter] = createCard();
addCardToCreatedCards(playerCards[dealcounter]);
}
String theCards = getPlayerCardsToString();
String dealerCard = dealerCards[0].toString();
String playerpoints= Integer.toString(getTotalPlayerPoints());
playerCards1.setText(theCards);
dealerCards1.setText(dealerCard);
playerPoints.setText(playerpoints);//getTotalPlayerPoints()
while (getTotalDealerPoints() < 16){
hitDealer();
}
}
// Create card and validate against existing before returning object.
public Card createCard(){
int counter2 = 0;
int flag = 0;
int value;
int suit;
do {
flag = 0;
suit = randomer.nextInt(4);
value = randomer.nextInt(13);
// validate against permitted values before creating cards
while (counter2 <= getTotalPlayerCards()) {
if (createdCards[counter2].getSuit() == suit && createdCards[counter2].getCard() == value || suit > 3 || suit < 0 || value > 12 || value < 0){
flag = -1;
}
counter2++;
}
} while (flag != 0);
Card theCard = new Card (suit, value);
return theCard;
}
// Add card to the records of created cards
public void addCardToCreatedCards(Card aCard){
createdCards [totalCreatedCards] = aCard;
totalCreatedCards++;
}
// Add a card to dealers cards
public void hitPlayer(){
//If the hand was started add card, else deal to start hand.
if (getTotalPlayerCards()+1 != 0){
mpHit.start();
playerCards [getTotalPlayerCards()+1] = createCard();
addCardToCreatedCards(playerCards [getTotalPlayerCards()]);
}
else
deal();
}
// Create a new card for the dealer
public void hitDealer(){
dealerCards [getTotalDealerCards()+1] = createCard();
addCardToCreatedCards(dealerCards [getTotalDealerCards()]);
}
public String getPlayerCardsToString(){
String cards = "";
int total = getTotalPlayerCards();
if (getTotalPlayerPoints() <=21){
int counter = 0;
while (counter <= total){
cards += playerCards[counter].toString() + " ";
counter++;
}
return cards;
}else {
int counter=0;
while (counter <= total){
cards += playerCards[counter].toString() + " ";
counter++;
}
return cards;
}
}
public int getTotalPlayerCards(){
int initialCount = 0;
while (playerCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public int getTotalDealerCards(){
int initialCount = 0;
while (dealerCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public int getTotalCreatedCards(){
int initialCount = 0;
while (createdCards[initialCount] != null){
initialCount++;
}
return initialCount-1;
}
public Boolean isBusted(){
Boolean busted = false;
if (getTotalPlayerPoints()>21){
busted=true;
totalDealerPoints = 0;
totalPlayerPoints = 0;
mpBusted.start();
playerPoints.setText("You were busted!!");
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
}
return busted;
}
//Check for winner
public void checkWinner(){
if (getTotalDealerPoints() <= 21 || getTotalPlayerPoints() <= 21 && !isBusted()){
if (getTotalDealerPoints() > 21 || getTotalDealerPoints() < getTotalPlayerPoints()){
playerPoints.setText("You won!!");
mpWin.start();
}
else if(getTotalDealerPoints() > getTotalPlayerPoints()){
mpBusted.start();
playerPoints.setText("You were busted!!");
for (int i = 0; i < TOTAL_CARDS; i++){
dealerCards [i] = null;
playerCards [i] = null;
createdCards [i] = null;
}
}
else{
mpEven.start();
playerCards1.setText("We have same points!");
}
}
else {
deal ();
}
}
}
Use the debugger in eclipse to find out where it gets frozen.
Also the android emulator is very slow even with a fast PC.
Try using the low resolution simulators.
open DDMS from the android-sdk\tools and check which method or thread is taking more time to execute.
Use AsyncTask or Handler when there is a functional(Computational) things running.

Categories

Resources