isAnswered=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG,"1isanswered : "+isAnswered);
Log.d(TAG, "matchinggame OnCreate");
super.onCreate(savedInstanceState);
dbHandler = new DatabaseHandler(this);
rLayout = new RelativeLayout(this);
object = new ObjectObject();
imageAnswer=new ImageView(this);
setContentView(rLayout);
trainingID = getIntent().getExtras().getInt("trainingid");
trainingObjectList = new ArrayList<TrainingObject>();
trainingObjectList = dbHandler.getAllTrainingObject(trainingID);
//// TODO: 02.05.2016 egitim kismi oalcak burda tek tek gosterilecek
rLayout.setBackgroundColor(Color.MAGENTA);
// Handler handler = new Handler(); Log.d(TAG,"2isanswered : "+isAnswered);
for(int i=0;i<2;i++){Log.d(TAG,"i:"+i); Log.d(TAG,"3tisanswered : "+isAnswered);
final int finalI = i;
// handler.postDelayed(new Runnable() {
// #Override
// public void run() {Log.d(TAG,"thread i: "+finalI);
Log.d(TAG,"4isanswered : "+isAnswered);
isAnswered = 0;
TrainingObject trainingObject = new TrainingObject();
trainingObject = trainingObjectList.get(finalI);
objectCount = 2;
//test icin
Log.d(TAG,"testicin trainingobjectid: "+trainingObject.getTrainingobjectID());
object = dbHandler.getObjectObject(trainingObject.getTrainingobjectAnswer());
if(trainingObject.getTrainingobjectThree()!=0) objectCount++;
if(trainingObject.getTrainingobjectFour()!=0) objectCount++;
if(trainingObject.getTrainingobjectFive()!=0) objectCount++;
Log.d(TAG,"matchinggame objcount: "+objectCount);
RelativeLayout.LayoutParams rLayParams = new RelativeLayout.LayoutParams(140,140);
rLayParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rLayParams.addRule(RelativeLayout.CENTER_IN_PARENT);
imgBytes = object.getObjectImageBlob();
bmp = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);
imageAnswer.setImageBitmap(bmp);
imageAnswer.setTag(trainingObject.getTrainingobjectAnswer());
imageAnswer.setId(R.id.imgAnswer);
rLayout.removeAllViews();
rLayout.addView(imageAnswer,rLayParams);
imageOne.setOnDragListener(MatchingGame.this);
imageAnswer.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) { Log.d(TAG,"6isanswered : "+isAnswered);
Log.d(TAG,"matchinggame setontouch");
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Log.d(TAG,"matchinggame setontouch if yes");
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
v.startDrag(data, shadowBuilder, v, 0);
v.setVisibility(View.INVISIBLE); Log.d(TAG,"7isanswered : "+isAnswered);
return true;
} else { Log.d(TAG,"8isanswered : "+isAnswered);
return false;
}
}
});
imageAnswer.setOnDragListener(MatchingGame.this);
Log.d(TAG,"*");
while(isAnswered==0){
//Log.d(TAG,"*");
}
// }
// }, 30000*finalI );Log.d(TAG,"thread sonrasi: "+finalI); Log.d(TAG,"5isanswered : "+isAnswered);
}Log.d(TAG,"ff");
}
because isanswered=0, it stays in infinite loop. But i cant see my layout, i only see magenta while this loop continues. After seconds black screen comes.
But when i disable while there, after printing ff to log, it finishes oncreate and then layout changes.
I searched but no answer for this.
Android layout only showing after oncreate method finishes
here it says try onstart. yes i tried but same.
i only have here asynctask call to get values from sqlite.
i have a for loop, in each iteration, i will show images and user will try to match them.
I did not use views or fragments.
Why doesnot it post to screen as soon as it takes view?
full activity is here:
https://gist.github.com/anonymous/87ccd4147ae0d202244bb78f51844f29
This happens because activity is not shown before onCreate method is finished. Try moving your code to onResume and see if it works. Also, in your current code, don't forget to call super.onCreate(savedInstanceState)
Related
I am making a puzzle game and every time the user completes the puzzle, a recreate button appears which is simply calling the recreate() method to restart the puzzle activity.
I override onSaveInstanceState because i want to save the image selected for the puzzle and the 4 pieces in case of screen orientation change.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("originalBM", originalBm);
outState.putParcelable("bm1", bm1);
outState.putParcelable("bm2", bm2);
outState.putParcelable("bm3", bm3);
outState.putParcelable("bm4", bm4);
}
So, when the user clicks the recreate button, the recreate() method is being called which also calls onSaveInstanceState by default because this is how android works and the user will have to play the puzzle with the same image again and again.
I don't want to implement the same code that i have on my onCreate method to select a new random image because this is causing memory leaks and my app crashes after 10-12 recreates.
I simply want it to restart the activity clean and fresh!
Instead of using recreate() inside my recreatePuzzle method, I also also tried this
Intent intent = getIntent();
finish();
startActivity(intent);
But this again is causing my app to crash after 10-12 recreates. It is also causing memory leaks.
So, i believe the best way to do this would be by skipping the Override of saveInstanceState when my recreatePuzzle is being called (if this is possible) or by passing a null Bundle when onSaveInstanceState is being called.
Is there any way to implement any of these solutions above?
Any help would be highly appreciated.
Thank you all in advance.
EDIT:
Full code of my class
package kidsbook.jok.kidsbook;
public class Puzzle extends AppCompatActivity {
private String[] puzzleIMGS;
private String randomPuzzleIMG;
private int corrects = 0, tries = 0;
private ImageView part1, part2, part3, part4;
private TextView piece1, piece2, piece3, piece4;
private Button againButton;
private Bitmap bm1, bm2, bm3, bm4, originalBm;
private Intent i;
private MediaPlayer mp = new MediaPlayer();
private List<Bitmap> parts = new ArrayList<>();
private boolean recreatePuzzle = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_puzzle);
mp = MediaPlayer.create(getApplicationContext(), R.raw.pop);
//Select random image
puzzleIMGS = getResources().getStringArray(R.array.all_animal_imgs);
randomPuzzleIMG = puzzleIMGS[new Random().nextInt(puzzleIMGS.length)];
//Get all elements
againButton = (Button) findViewById(R.id.againPuzzleButton);
part1 = (ImageView) findViewById(R.id.part1);
part2 = (ImageView) findViewById(R.id.part2);
part3 = (ImageView) findViewById(R.id.part3);
part4 = (ImageView) findViewById(R.id.part4);
piece1 = (TextView) findViewById(R.id.piece1);
piece2 = (TextView) findViewById(R.id.piece2);
piece3 = (TextView) findViewById(R.id.piece3);
piece4 = (TextView) findViewById(R.id.piece4);
part1.setOnTouchListener(new MyTouchListener());
part2.setOnTouchListener(new MyTouchListener());
part3.setOnTouchListener(new MyTouchListener());
part4.setOnTouchListener(new MyTouchListener());
piece1.setOnDragListener(new MyDragListener());
piece2.setOnDragListener(new MyDragListener());
piece3.setOnDragListener(new MyDragListener());
piece4.setOnDragListener(new MyDragListener());
if(savedInstanceState!=null) {
Log.i("debug","inside saved instance");
//Convert randomly selected resource image to bitmap
originalBm = savedInstanceState.getParcelable("originalBM");
bm1 = savedInstanceState.getParcelable("bm1");
bm2 = savedInstanceState.getParcelable("bm2");
bm3 = savedInstanceState.getParcelable("bm3");
bm4 = savedInstanceState.getParcelable("bm4");
} else {
Log.i("debug","inside null instance");
//Convert randomly selected resource image to bitmap
originalBm = BitmapFactory.decodeResource(getResources(), getImageId(this, randomPuzzleIMG));
//Split bitmap to 4 parts
bm1 = Bitmap.createBitmap(originalBm, 0, 0, (originalBm.getWidth() / 2), (originalBm.getHeight() / 2));
bm2 = Bitmap.createBitmap(originalBm, (originalBm.getWidth() / 2), 0, (originalBm.getWidth() / 2), (originalBm.getHeight() / 2));
bm3 = Bitmap.createBitmap(originalBm, 0, (originalBm.getHeight() / 2), (originalBm.getWidth() / 2), (originalBm.getHeight() / 2));
bm4 = Bitmap.createBitmap(originalBm, (originalBm.getWidth() / 2), (originalBm.getHeight() / 2), (originalBm.getWidth() / 2), (originalBm.getHeight() / 2));
}
//Make the background transparent
piece1.setBackgroundDrawable(new BitmapDrawable(getResources(), bm1));
piece1.setAlpha(0.2f);
piece2.setBackgroundDrawable(new BitmapDrawable(getResources(), bm2));
piece2.setAlpha(0.2f);
piece3.setBackgroundDrawable(new BitmapDrawable(getResources(), bm3));
piece3.setAlpha(0.2f);
piece4.setBackgroundDrawable(new BitmapDrawable(getResources(), bm4));
piece4.setAlpha(0.2f);
//Place parts in an array
parts.add(bm1);
parts.add(bm2);
parts.add(bm3);
parts.add(bm4);
//Shuffle the array
Collections.shuffle(parts);
//Assign the correct piece tag to each part
for(int i=0;i<4;i++){
if(i==1) {
part1.setImageBitmap(parts.get(i));
if (parts.get(i).equals(bm1)){
part1.setTag("piece1");
} else if (parts.get(i).equals(bm2)){
part1.setTag("piece2");
} else if (parts.get(i).equals(bm3)){
part1.setTag("piece3");
} else {
part1.setTag("piece4");
}
} else if(i==2){
part2.setImageBitmap(parts.get(i));
if (parts.get(i).equals(bm1)){
part2.setTag("piece1");
} else if (parts.get(i).equals(bm2)){
part2.setTag("piece2");
} else if (parts.get(i).equals(bm3)){
part2.setTag("piece3");
} else {
part2.setTag("piece4");
}
} else if(i==3){
part3.setImageBitmap(parts.get(i));
if (parts.get(i).equals(bm1)){
part3.setTag("piece1");
} else if (parts.get(i).equals(bm2)){
part3.setTag("piece2");
} else if (parts.get(i).equals(bm3)){
part3.setTag("piece3");
} else {
part3.setTag("piece4");
}
} else {
part4.setImageBitmap(parts.get(i));
if (parts.get(i).equals(bm1)){
part4.setTag("piece1");
} else if (parts.get(i).equals(bm2)){
part4.setTag("piece2");
} else if (parts.get(i).equals(bm3)){
part4.setTag("piece3");
} else {
part4.setTag("piece4");
}
}
}
}
private static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
private final class MyTouchListener implements View.OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, view, 0);
return true;
} else {
return false;
}
}
}
class MyDragListener implements View.OnDragListener {
#Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED:
// do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
break;
case DragEvent.ACTION_DRAG_EXITED:
break;
case DragEvent.ACTION_DROP:
// Dropped, reassign View to ViewGroup
View view = (View) event.getLocalState();
ViewGroup owner = (ViewGroup) view.getParent();
if(view.getTag().equals(v.getTag())){
if(view.getTag().equals("piece1")){
owner.removeView(view);
useMediaPlayer();
piece1.setBackgroundDrawable(new BitmapDrawable(getResources(), bm1));
piece1.setAlpha(0.9f);
corrects++;
} else if (view.getTag().equals("piece2")){
owner.removeView(view);
useMediaPlayer();
piece2.setBackgroundDrawable(new BitmapDrawable(getResources(), bm2));
piece2.setAlpha(0.9f);
corrects++;
} else if (view.getTag().equals("piece3")){
owner.removeView(view);
useMediaPlayer();
piece3.setBackgroundDrawable(new BitmapDrawable(getResources(), bm3));
piece3.setAlpha(0.9f);
corrects++;
} else if (view.getTag().equals("piece4")) {
owner.removeView(view);
useMediaPlayer();
piece4.setBackgroundDrawable(new BitmapDrawable(getResources(), bm4));
piece4.setAlpha(0.9f);
corrects++;
}
}
tries++;
if(corrects==4){
finish();
}
break;
case DragEvent.ACTION_DRAG_ENDED:
break;
default:
break;
}
return true;
}
}
public void useMediaPlayer(){
mp.start();
}
public void againPuzzle(View v){
recreatePuzzle = true;
recreate();
}
public void finish(){
againButton.setVisibility(View.VISIBLE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("originalBM", originalBm);
outState.putParcelable("bm1", bm1);
outState.putParcelable("bm2", bm2);
outState.putParcelable("bm3", bm3);
outState.putParcelable("bm4", bm4);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_games, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
return true;
case R.id.menu_about:
i = new Intent(this, About.class);
startActivity(i);
return true;
case R.id.menu_help:
i = new Intent(this, Help.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
What about starting the same activity then finishing the previous one ? like :
Intent intent=new Intent(this, MainActivity.class)
startActivity(intent);
finish();
Using finish will help you not having any memoryleak as oncreate() do.
Second option : move the code selecting a puzzle in a new method (like selectNewPuzzle()), then call that method in onCreated and when you need select a new puzzle.
Third option : use a global boolean named like "canSaveInstance" wich is true when onCreate end. Encapsulate the lines saving the instancestate in an if statement checking this boolean, and when you need recreating, put this variable false, recreate as you usually do (so no data is saved, new puzzle is started) then reput it true (to handle config changes). You will need to be carefull when recreating activity : if(savedinstancestate!=null) must become "if(savedinstancestate!=null && canSaveInstance) (because if not you may try to load data which were not saved previously).
last option : (but i'm not really aware on how to do exactly) prevent user from launching multiple time the puzzle activity, then "launch" a new one (the older one will be overrided i think). You may need do some more research to do this one. As other options are easier I won't search for documentation helping doing that.
So i finally came up with a solution. What i was missing was to release the bitmap memory of my activity and that was what was causing memory leak. So, finally, me recreate() method looks like
public void againPuzzle(View v){
originalBm.recycle();
bm1.recycle();
bm2.recycle();
bm3.recycle();
bm4.recycle();
originalBm = null;
bm1 = null;
bm2 = null;
bm3 = null;
bm4 = null;
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}
friends I am building an App for android and facing some problem in showing dynamically added TextViewer my scenario is like this.
I am using ResulReceiver to receive notification and adding this result Dynamically in TextView to display.When my activity is active I.e The application is keep open till then it is working properly.
When my Activity is not in the Active mode then I'm storing it to DB (SQLLITE), but when I come back to my Activity again then I can fetch data from DB and do the same thing like before,till now there is no problem.
But it starts as i receive new notification at that time is not able to append the new TextView with the existing one dynamically,But when fro debugging purpose i use Toast it is showing properly.
Could you please help me out.
Thanks in Advance.
This is my code
#Override
public void onReceiveResult(int resultCode, Bundle resultData) {
// TODO Auto-generated method stub
String result = resultData.getString("notifyService");
CustomActionBar.controlNotifyImage(this,mActionBar);
ActivityManager activityManager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if(!".activity.CatagoryChooserActivity".equals(componentInfo.getShortClassName()) ){
notifyInfo = new NotifyInfo();
notifyInfo.setNotifyPk(100000+new Long(CreateOrderService.notifyCount.get()));
notifyInfo.setNotifyTxt(result);
notifyInfo.setNotifyDate(new Date().toString());
notifyInfo.setNotifyTime(new Date().toGMTString());
SellerNotifyDB sellerNotifydb = SellerNotifyDB.getInstance(context);
sellerNotifydb.addNotification(notifyInfo);
Toast.makeText(this,"Notify :: "+CreateOrderService.notifyCount.get(),Toast.LENGTH_LONG).show();
}
else {
runOnUiThread(new UpdateUI(result));
}
}
class UpdateUI implements Runnable
{
String updateString;
public UpdateUI(String updateString) {
this.updateString = updateString;
}
public void run() {
// txtview.setText(updateString);
createNotifyLatout(updateString);
}
private void createNotifyLatout(String result) {
//final ArrayList<TextView> addrTextList = new ArrayList<TextView>();
addrLinearLayout = (LinearLayout) findViewById(R.id.dashboardLayout);
TextView addrTextView = new TextView(context);
LinearLayout addrLayout = new LinearLayout(context);
addrLayout.setPadding(2, 0, 2, 0);
addrLayout.setOrientation(LinearLayout.HORIZONTAL);
ImageView editImgBtn = new ImageView(context);
editImgBtn.setId(700 + CreateOrderService.notifyCount.get());
editImgBtn.setImageDrawable(getResources().getDrawable(R.drawable.takeorder));
editImgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
editImgBtn.setLayoutParams((new LinearLayout.LayoutParams(100,
40, 1.0f)));
ImageView deltImgBtn = new ImageView(context);
deltImgBtn.setId(8000 + CreateOrderService.notifyCount.get());
deltImgBtn.setLayoutParams((new LinearLayout.LayoutParams(100,
50, 1.0f)));
deltImgBtn.setPadding(0, 0, 0, 10);
deltImgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
deltImgBtn.setImageDrawable(getResources().getDrawable(R.drawable.cancelorder));
addrTextView.setPadding(2, 5, 0, 0);
addrTextView.setText(Html.fromHtml("<br><br>" + result + "<br><br>"));
addrTextView.setLayoutParams((new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)));
addrTextView.setMaxEms(10);
// registerForContextMenu(addrTextView);
addrLayout.setBackgroundColor(getResources().getColor(R.color.banarColor));
addrLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
addrLayout.setDividerDrawable(getResources().getDrawable(R.drawable.divider));
addrTextView.setTextColor(getResources().getColor(R.color.backgroundColor));
addrTextView.setBackgroundDrawable(getResources().getDrawable(R.drawable.backg_txt));
addrLayout.addView(editImgBtn);
addrLayout.addView(deltImgBtn);
// addrTextList.add(addrTextView);
addrLinearLayout.addView(addrTextView);
addrLinearLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_img));
addrLinearLayout.addView(addrLayout);
Toast.makeText(context,"Notify Open :: "+CreateOrderService.notifyCount.get()+"=##=="+result,Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
CustomActionBar.controlNotifyImage(this,mActionBar);
//Toast.makeText(context,"#####",Toast.LENGTH_LONG).show();
SellerNotifyDB sellerNotifydb = SellerNotifyDB.getInstance(context);
sellerNotifydb.deleteNotification();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
CustomActionBar.controlNotifyImage(this,mActionBar);
SellerNotifyDB sellerNotifydb = SellerNotifyDB.getInstance(context);
ArrayList notifyInfoList = sellerNotifydb.getNotification();
if(notifyInfoList instanceof ArrayList && notifyInfoList.size() > 0)
for (int i=0;i<notifyInfoList.size();i++){
//createNotifyLatout(((NotifyInfo)notifyInfoList.get(i)).getNotifyTxt());
test = ((NotifyInfo)notifyInfoList.get(i)).getNotifyTxt();
runOnUiThread(new UpdateUI(test));
}
}
I think you need to stop your existing running service.
Keep your Existing TextView in a LinearLayout and then generate a TextView And add to LinearLayout. See this
I wish to add the following functionality to my game:
-When the game is complete (no more cards are visible on screen) then move to a new activity
I am aware how to move to another activty using intents but I am not sure how to implement the functionality in this case.
I.e. what variable/info can I use to ensure the game is complete when I move before moving to the next activity?
For reference, The game is based off this open source game Images of the game are shown here to give an idea.
Current code:
public class Manager extends Activity {
private static int ROW_COUNT = -1;
private static int COL_COUNT = -1;
private Context context;
private Drawable backImage;
private int [] [] cards;
private List<Drawable> images;
private Card firstCard;
private Card seconedCard;
private ButtonListener buttonListener;
private static Object lock = new Object();
int turns;
private TableLayout mainTable;
private UpdateCardsHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new UpdateCardsHandler();
loadImages();
setContentView(R.layout.main);
TextView url = ((TextView)findViewById(R.id.myWebSite));
Linkify.addLinks(url, Linkify.WEB_URLS);
backImage = getResources().getDrawable(R.drawable.icon);
/*
((Button)findViewById(R.id.ButtonNew)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newGame();
}
});*/
buttonListener = new ButtonListener();
mainTable = (TableLayout)findViewById(R.id.TableLayout03);
context = mainTable.getContext();
Spinner s = (Spinner) findViewById(R.id.Spinner01);
ArrayAdapter adapter = ArrayAdapter.createFromResource(
this, R.array.type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(
android.widget.AdapterView<?> arg0,
View arg1, int pos, long arg3){
((Spinner) findViewById(R.id.Spinner01)).setSelection(0);
int x,y;
switch (pos) {
case 1:
x=4;y=4;
break;
case 2:
x=4;y=5;
break;
case 3:
x=4;y=6;
break;
case 4:
x=5;y=6;
break;
case 5:
x=6;y=6;
break;
default:
return;
}
newGame(x,y);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void newGame(int c, int r) {
ROW_COUNT = r;
COL_COUNT = c;
cards = new int [COL_COUNT] [ROW_COUNT];
mainTable.removeView(findViewById(R.id.TableRow01));
mainTable.removeView(findViewById(R.id.TableRow02));
TableRow tr = ((TableRow)findViewById(R.id.TableRow03));
tr.removeAllViews();
mainTable = new TableLayout(context);
tr.addView(mainTable);
for (int y = 0; y < ROW_COUNT; y++) {
mainTable.addView(createRow(y));
}
firstCard=null;
loadCards();
turns=0;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
}
private void loadImages() {
images = new ArrayList<Drawable>();
images.add(getResources().getDrawable(R.drawable.card1));
images.add(getResources().getDrawable(R.drawable.card2));
images.add(getResources().getDrawable(R.drawable.card3));
images.add(getResources().getDrawable(R.drawable.card4));
images.add(getResources().getDrawable(R.drawable.card5));
images.add(getResources().getDrawable(R.drawable.card6));
images.add(getResources().getDrawable(R.drawable.card7));
images.add(getResources().getDrawable(R.drawable.card8));
images.add(getResources().getDrawable(R.drawable.card9));
images.add(getResources().getDrawable(R.drawable.card10));
images.add(getResources().getDrawable(R.drawable.card11));
images.add(getResources().getDrawable(R.drawable.card12));
images.add(getResources().getDrawable(R.drawable.card13));
images.add(getResources().getDrawable(R.drawable.card14));
images.add(getResources().getDrawable(R.drawable.card15));
images.add(getResources().getDrawable(R.drawable.card16));
images.add(getResources().getDrawable(R.drawable.card17));
images.add(getResources().getDrawable(R.drawable.card18));
images.add(getResources().getDrawable(R.drawable.card19));
images.add(getResources().getDrawable(R.drawable.card20));
images.add(getResources().getDrawable(R.drawable.card21));
}
private void loadCards(){
try{
int size = ROW_COUNT*COL_COUNT;
Log.i("loadCards()","size=" + size);
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<size;i++){
list.add(new Integer(i));
}
Random r = new Random();
for(int i=size-1;i>=0;i--){
int t=0;
if(i>0){
t = r.nextInt(i);
}
t=list.remove(t).intValue();
cards[i%COL_COUNT][i/COL_COUNT]=t%(size/2);
Log.i("loadCards()", "card["+(i%COL_COUNT)+
"]["+(i/COL_COUNT)+"]=" + cards[i%COL_COUNT][i/COL_COUNT]);
}
}
catch (Exception e) {
Log.e("loadCards()", e+"");
}
}
private TableRow createRow(int y){
TableRow row = new TableRow(context);
row.setHorizontalGravity(Gravity.CENTER);
for (int x = 0; x < COL_COUNT; x++) {
row.addView(createImageButton(x,y));
}
return row;
}
private View createImageButton(int x, int y){
Button button = new Button(context);
button.setBackgroundDrawable(backImage);
button.setId(100*x+y);
button.setOnClickListener(buttonListener);
return button;
}
class ButtonListener implements OnClickListener {
#Override
public void onClick(View v) {
synchronized (lock) {
if(firstCard!=null && seconedCard != null){
return;
}
int id = v.getId();
int x = id/100;
int y = id%100;
turnCard((Button)v,x,y);
}
}
private void turnCard(Button button,int x, int y) {
button.setBackgroundDrawable(images.get(cards[x][y]));
if(firstCard==null){
firstCard = new Card(button,x,y);
}
else{
if(firstCard.x == x && firstCard.y == y){
return; //the user pressed the same card
}
seconedCard = new Card(button,x,y);
turns++;
((TextView)findViewById(R.id.tv1)).setText("Tries: "+turns);
TimerTask tt = new TimerTask() {
#Override
public void run() {
try{
synchronized (lock) {
handler.sendEmptyMessage(0);
}
}
catch (Exception e) {
Log.e("E1", e.getMessage());
}
}
};
Timer t = new Timer(false);
t.schedule(tt, 1300);
}
}
}
class UpdateCardsHandler extends Handler{
#Override
public void handleMessage(Message msg) {
synchronized (lock) {
checkCards();
}
}
public void checkCards(){
if(cards[seconedCard.x][seconedCard.y] == cards[firstCard.x][firstCard.y]){
firstCard.button.setVisibility(View.INVISIBLE);
seconedCard.button.setVisibility(View.INVISIBLE);
}
else {
seconedCard.button.setBackgroundDrawable(backImage);
firstCard.button.setBackgroundDrawable(backImage);
}
firstCard=null;
seconedCard=null;
}
}
}
The easiest way to do this would be to check win conditions with an if statement. This should be done in the method when a turn is actually taken which I assume happens in the turnCard() method.
if (winConditionMet) {
displayWinningScreen();
} else if (lossConditionMet) {
displayLosingScreen();
}
If conditions have been met, then call a method which handles wrapping up that screen, and then launching a new activity. For instance you could add a button to the screen with whatever text you wanted, that when pushed, would take the user to the next screen, be it your score screen, replay screen, main menu, or what have you.
Edit: Okay, since this is a game of memory, you could iterate through the cards at the end of every turn taken and check if any card still has its image set to backImage. If there are none left that are set to backImage, you can then end the game with your code inside of the if statement.
Or, instead of using an ArrayList, you could use some form of Map to keep track of if each card has been permanently turned up or not with the boolean value.
I have listactivity app forming many rows , one row is images Slideshow , when you click
the row open activity showing ImageView , also there is optionmenu of one item which is( slideshow animation setting ), when you click it , it open checkbox preference
animations screen with multiple checkboxes each one apply different animation to images
slideshow ,where user determine either to slide images with many animations available by
check its checkbox animation name or when uncheck all the checkboxs so the slideshow activity
must show images in viewpager pattern .
android:defaultValue="true" for first animation which is fade_in animation.
BUT: when you open slideshow activity its open the images in imagepager pattern ,and ignoring android:defaultValue="true" for fade_in checkbox,
then after go to preference screen to choose another animation then back to slideshow
activity , it doesn't apply the new animation , i have to press back button many times
till finish all images scrolled in pager then it apply the next animation ,
and sometimes it stuck on image pager and freeze's ,the normal behavior is applying
the next animation once press back button which return to slideshow .
another thing when i was in image viewpager pattern and scroll it ,
it scroll a few number of images then back to first image then i scroll images again
and suddenly it back to first image one and so on .
whole project can be downloaded from here
any help will be appreciated.
SlideShow.java
public class SlideShow extends Activity {
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingimage;
private int[] IMAGE_IDS = {
R.drawable.day_one_1, R.drawable.day_one_2, R.drawable.day_one_3,
R.drawable.day_one_4, R.drawable.day_one_5, R.drawable.day_one_6,
R.drawable.day_one_7, R.drawable.day_one_8, R.drawable.day_one_9,
R.drawable.day_one_10, R.drawable.day_one_11, R.drawable.day_one_12,
R.drawable.day_one_13, R.drawable.day_one_14, R.drawable.day_one_15,
R.drawable.day_one_16,R.drawable.day_one_17,R.drawable.day_one_18,
R.drawable.day_one_19,R.drawable.day_one_20
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide);
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; // delay for 1 sec.
int period = 8000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
private void AnimateandSlideShow() {
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean animation = getPrefs.getBoolean("animation", true);
boolean animation_one = getPrefs.getBoolean("animation_one", false);
boolean animation_two = getPrefs.getBoolean("animation_two", false);
boolean animation_three = getPrefs.getBoolean("animation_three", false);
boolean animation_four = getPrefs.getBoolean("animation_four", false);
boolean animation_five = getPrefs.getBoolean("animation_five", false);
if (animation == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
slidingimage.startAnimation(rotateimage);
}else if(animation_one == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in);
slidingimage.startAnimation(rotateimage);
}else if (animation_two == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_out);
slidingimage.startAnimation(rotateimage);
}else if (animation_three == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.bounce);
slidingimage.startAnimation(rotateimage);
}else if(animation_four == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in_2);
slidingimage.startAnimation(rotateimage);
}else if (animation_five == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.flip);
slidingimage.startAnimation(rotateimage);
}else if(animation == false && animation_one == false && animation_two == false){
Intent intent = new Intent(SlideShow.this, ImagePager.class);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings:
Intent p = new Intent("com.test.test.SETTING");
startActivity(p);
break;
}
return false;
}
}
ImagePager.java
public class ImagePager extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myimagepager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
private int imageArra[] = { R.drawable.day_one_1, R.drawable.day_one_2, R.drawable.day_one_3,
R.drawable.day_one_4, R.drawable.day_one_5, R.drawable.day_one_6,
R.drawable.day_one_7, R.drawable.day_one_8, R.drawable.day_one_9,
R.drawable.day_one_10, R.drawable.day_one_11, R.drawable.day_one_12,
R.drawable.day_one_13, R.drawable.day_one_14, R.drawable.day_one_15,
R.drawable.day_one_16,R.drawable.day_one_17,R.drawable.day_one_18,
R.drawable.day_one_19,R.drawable.day_one_20
};
public class ImagePagerAdapter extends PagerAdapter {
Activity activity;
int[] imageArray;
public ImagePagerAdapter(Activity act, int[] imgArra) {
imageArray = imgArra;
activity = act;
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_pager, null);
ImageView im=(ImageView) layout.findViewById(R.id.pager_imageView);
im.setImageResource(imageArray[position]);
((ViewPager) collection).addView(layout, 0);
return layout;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings:
Intent p = new Intent("com.test.test.SETTING");
startActivity(p);
break;
}
return false;
}
}
Please post the project to be work out a proper solution mean while try using this
First of all as you have declared the ImageView slidingimage; as an instance variable, declare the Animation rotateimage as an instance variables and use it as
rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
Now once you add the animation to imageview call the invalidate() method inside the if loops
slidingimage.startAnimation(rotateimage)
slidingimage.invalidate();
And in your imagePager class make ViewPager myPager as static instance variable private static ViewPager myPager and add this code to the class
public static void refreshPager(){
if(myPager != null)
myPager.invalidate();
}
And in your settings class call this method on the onBackPressed() event
#Override
public void onBackPressed() {
ImagePager.refreshPager();
super.onBackPressed();
}
EDIT
All you just need to do is this, add this code in your Slide.java file after the setContentView(R.layout.main); and before final Handler mHandler = new Handler();
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
if(getPrefs.getBoolean("Initialization", false) == false){
SharedPreferences.Editor edit = getPrefs.edit();
edit.putBoolean("animation_one", true);
edit.putBoolean("Initialization", true);
edit.commit();
}
Like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
if(getPrefs.getBoolean("Initialization", false) == false){
SharedPreferences.Editor edit = getPrefs.edit();
edit.putBoolean("animation_one", true);
edit.putBoolean("Initialization", true);
edit.commit();
}
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; // delay for 1 sec.
int period = 8000; // repeat every 4 sec.
Timer timer = new Timer
// Some more code............
The preference file was not created only ;)
EDIT 2
In you Slide.java file declare a boolean like this
public boolean loaded ;
and code your else if like this
else if(animation_one == false && animation_two == false && animation_three == false
&& animation_four == false && animation_five == false){
Intent intent = new Intent(Slide.this, ImagePager.class);
if(loaded)
startActivity(intent);
loaded = true;
}
Create a static variable in Slide.java public static TimerTask task; and in your ImagePager.java add this code if(imageArra.length-1 == position)Slide.task.cancel(); in instantiateItem() method like this
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_pager, null);
ImageView im=(ImageView) layout.findViewById(R.id.myimage);
im.setImageResource(imageArray[position]);
((ViewPager) collection).addView(layout, 0);
if(imageArra.length-1 == position)
Slide.task.cancel();
return layout;
}
Hope this works
I want to create 600 imageview at runtime and add it to linear layout at runtime.It cause block my user interface. My activity appear when all imageview created and added to linear layout. How to resolve this.
Please help for this.
for(int index = 0; index < ProductItemArray.Image_URL.length; index++)
{
ImageView bottomImageView = new ImageView(context);
bottomImageView.setTag(index);
if(Helper.isTablet(context))
bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(100, context), VirtualMirrorActivity.convertDpToPixel(100, context)));
else
bottomImageView.setLayoutParams(new Gallery.LayoutParams(VirtualMirrorActivity.convertDpToPixel(80, context), VirtualMirrorActivity.convertDpToPixel(80, context)));
UrlImageViewHelper.setUrlDrawable(bottomImageView, ProductItemArray.Image_URL[index]);
bottomImageView.setBackgroundResource(R.layout.border);
linearLayout3.addView(bottomImageView);
bottomImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final int position = (Integer) v.getTag();
linearLayout.removeAllViews();
Thread newThread = new Thread(new Runnable() {
public void run() {
isAlreadyExistInWishlist = true;
URL url_1 = null;
try {
VMProductListPaging.productUrl = ProductItemArray.Image_small_URL[position];
VMProductListPaging.productId = ProductItemArray.productId[position];
VMProductListPaging.productName = ProductItemArray.product_Name[position];
url_1 = new URL(ProductItemArray.Image_small_URL[position]);
bmp = BitmapFactory.decodeStream(url_1.openConnection().getInputStream());
isExecuted = true;
bitmapModelsHandler.sendMessage(bitmapModelsHandler.obtainMessage());
}
catch (Exception e) {
//Toast.makeText(context,"Sorry!! This link appears to be broken",Toast.LENGTH_LONG).show();
}
}
});
newThread.start();
}
});
}
Having 600 images in memory in the same time is probably not a good idea.
You should consider using some lazy loading via an adapter (with a ListView, a Gallery, a GridView, a Spinner,etc...) which will manage recycling/releasing of views.