Hello everyone I would like to implement a method to touch on my image of a ak47, I have written the code but the method does not work on touch as it should. I would like that if you touch the gun that starts the repetition in my code. Thanks in advance
package org.realgunshot;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
public class B2 extends Activity {
ImageView bulletshot,bulletempty ;
Boolean click=true;
TextView Display;
Button b1;
int counter = 15 ;
Object mediaPlayerspara,mediaPlayersload;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.b2);
bulletshot=(ImageView)findViewById(R.id.bulletshot);
bulletempty=(ImageView)findViewById(R.id.bulletempty);
b1 = (Button)findViewById(R.id.b1);
Display = (TextView)findViewById(R.id.counter);
final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.gun);
final Animation animgunshot = AnimationUtils.loadAnimation(this, R.anim.gunshot);
final Animation animbulletempty = AnimationUtils.loadAnimation(this, R.anim.bulletempty);
b1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
counter --;
Display.setText(""+counter);
if(counter <= 0)
{
counter=1;
mediaPlayerspara = null;
mediaPlayersload = MediaPlayer.create(getBaseContext(),R.raw.sload);
((MediaPlayer) mediaPlayersload).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayersload) {
// TODO Auto-generated method stub
mediaPlayersload.start();
mediaPlayersload.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayersload) {
mediaPlayersload.release();
};
});
}
});
}
else{
bulletshot.setVisibility(View.VISIBLE);
bulletshot.startAnimation(animgunshot);
Handler handlers = new Handler();
handlers.postDelayed(new Runnable() {
public void run() {
bulletshot.setVisibility(View.GONE);
bulletempty.setVisibility(View.GONE);
}
}, 300);
bulletempty.setVisibility(View.VISIBLE);
bulletempty.startAnimation(animbulletempty);
Handler handlers2 = new Handler();
handlers2.postDelayed(new Runnable() {
public void run() {
bulletshot.setVisibility(View.GONE);
bulletempty.setVisibility(View.GONE);
}
}, 2000);
v.startAnimation(animRotate);
final Button button1 = (Button)findViewById(R.id.b1);
button1.setBackgroundResource(R.drawable.ak47_1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
button1.setBackgroundResource(R.drawable.ak47_0);
}
}, 100);
mediaPlayerspara = MediaPlayer.create(getBaseContext(),R.raw.ak47);
((MediaPlayer) mediaPlayerspara).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayerspara) {
// TODO Auto-generated method stub
mediaPlayerspara.start();
mediaPlayerspara.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayerspara) {
mediaPlayerspara.release();
};
});
}
});}
if(event.getAction() == MotionEvent.ACTION_UP){
return true;
}
return false;
}
});
Button apri = (Button)findViewById(R.id.loadoadd);
apri.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater layoutInflater= (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.loadoadd, null);
final PopupWindow popupWindow = new PopupWindow(popupView,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
popupWindow.setAnimationStyle(R.style.Animation);
Button chiudi1 = (Button)popupView.findViewById(R.id.dismiss);
chiudi1.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
Button load = (Button)popupView.findViewById(R.id.load);
load.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter = 15;
Display.setText(""+counter);
}});
Button add = (Button)popupView.findViewById(R.id.add);
add.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter = 1015;
Display.setText(""+counter);
}});
if (click){
popupWindow.showAtLocation(chiudi1, Gravity.CENTER, 0, 0);
click=false;
}else{
popupWindow.dismiss();
click=true;
}
}});
}
}
I don't think anyone can help you - unless you post your code fully. There are so many things missing...Your OnTouchListener doesn't even check for touch events such as ACTION_DOWN, ACTION_MOVE or anything else.
I would suggest that you take the action when user taps i.e.
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
// Do your firing even
break;
case MotionEvent.ACTION_UP:
//action when user removes finger.
break;
default:
return false;
} // end of switch case
return true;
}
Also, just add a break point in onTouch() and debug to know what is happening and what part is not executing and fix it accordingly.
package org.realgunshot;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
public class B2 extends Activity {
ImageView proiettilesparo,proiettilevuoto ;
Boolean click=true;
TextView Display;
Button b1;
int contatore = 15 ;
Object mediaPlayerspara,mediaPlayerscarica;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.b2);
proiettilesparo=(ImageView)findViewById(R.id.proiettilesparo);
proiettilevuoto=(ImageView)findViewById(R.id.proiettilecade);
b1 = (Button)findViewById(R.id.b1);
Display = (TextView)findViewById(R.id.contatore);
final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.pistola);
final Animation animsparoproiettile = AnimationUtils.loadAnimation(this, R.anim.sparoproiettile);
final Animation animproiettilecade = AnimationUtils.loadAnimation(this, R.anim.proiettilecade);
b1.setOnTouchListener(new OnTouchListener() {
private Handler mHandler;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mHandler != null) return true;
mHandler = new Handler();
mHandler.postDelayed(mAction, 1);
break;
case MotionEvent.ACTION_UP:
if (mHandler == null) return true;
mHandler.removeCallbacks(mAction);
mHandler = null;
break;
}
return false;
}
Runnable mAction = new Runnable() {
#Override public void run() {
contatore --;
Display.setText(""+contatore);
if(contatore <= 0)
{
contatore=1;
mediaPlayerspara = null;
mediaPlayerscarica = MediaPlayer.create(getBaseContext(),R.raw.scarica);
((MediaPlayer) mediaPlayerscarica).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayerscarica) {
// TODO Auto-generated method stub
mediaPlayerscarica.start();
mediaPlayerscarica.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayerscarica) {
mediaPlayerscarica.release();
};
});
}
});
}
else{
proiettilesparo.setVisibility(View.VISIBLE);
proiettilesparo.startAnimation(animsparoproiettile);
Handler handlers = new Handler();
handlers.postDelayed(new Runnable() {
public void run() {
proiettilesparo.setVisibility(View.GONE);
proiettilevuoto.setVisibility(View.GONE);
}
}, 300);
proiettilevuoto.setVisibility(View.VISIBLE);
proiettilevuoto.startAnimation(animproiettilecade);
Handler handlers2 = new Handler();
handlers2.postDelayed(new Runnable() {
public void run() {
proiettilesparo.setVisibility(View.GONE);
proiettilevuoto.setVisibility(View.GONE);
}
}, 2000);
b1.startAnimation(animRotate);
final Button button1 = (Button)findViewById(R.id.b1);
button1.setBackgroundResource(R.drawable.ak47_1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
button1.setBackgroundResource(R.drawable.ak47_0);
}
}, 100);
mediaPlayerspara = MediaPlayer.create(getBaseContext(),R.raw.ak47);
((MediaPlayer) mediaPlayerspara).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayerspara) {
// TODO Auto-generated method stub
mediaPlayerspara.start();
mediaPlayerspara.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayerspara) {
mediaPlayerspara.release();
};
});
}
});}
mHandler.postDelayed(this, 100);
}
};
});
Button apri = (Button)findViewById(R.id.caricaoaggiungi);
apri.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater layoutInflater= (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.caricaoaggiungi, null);
final PopupWindow popupWindow = new PopupWindow(popupView,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
popupWindow.setAnimationStyle(R.style.Animation);
Button chiudi1 = (Button)popupView.findViewById(R.id.dismiss);
chiudi1.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
Button carica = (Button)popupView.findViewById(R.id.carica);
carica.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contatore = 15;
Display.setText(""+contatore);
}});
Button aggiungi = (Button)popupView.findViewById(R.id.aggiungi);
aggiungi.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contatore = 1015;
Display.setText(""+contatore);
}});
if (click){
popupWindow.showAtLocation(chiudi1, Gravity.CENTER, 0, 0);
click=false;
}else{
popupWindow.dismiss();
click=true;
}
}});
}
I changed it this way, but every time the animation starts from 0, there is a way to continue an action and does not stop and start it again?
Related
I am using seekBar for soundpool volume control on my app, I use PopupWindow for seekbar and everything works fine except, whenever I change or pause my activity, and I open seekbar popupwindow again, the seekbar is no longer the value I last had saved. But it always returns to its default value 100%, even I use SharedPreferences what works well, but only if I do not leave current activity.
public class ActivityMain extends Activity implements OnTouchListener, OnMenuItemClickListener {
SoundManager snd;
OnSeekBarChangeListener barChange1;
private int soundID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main_activity);
}
public void onRestart() {
super.onRestart();
}
public void onResume() {
super.onResume();
final Button btnOpenPopup = (Button)findViewById(R.id.button6);
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
barChange1 = new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
SharedPreferences prefs = getBaseContext().getSharedPreferences("mySharedPrefsFilename1", Context.MODE_PRIVATE);
prefs.edit().putInt("seekBarValue", seekBar.getProgress()).commit();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
snd.setVolume((float)progress/100.0f);
}
};
SeekBar volbar1 = (SeekBar)popupView.findViewById(R.id.VolBar1);
volbar1.setMax(100);
int value = 0;
SharedPreferences prefs = getBaseContext().getSharedPreferences("mySharedPrefsFilename1", Context.MODE_PRIVATE);
value = prefs.getInt("seekBarValue", 100);
volbar1.setProgress(value);
volbar1.setOnSeekBarChangeListener(barChange1);
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(btnOpenPopup, 60, 20);
}});
{
}
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
snd = new SoundManager(getApplicationContext());
soundID = snd.load(R.raw.sound_1);
ImageView img01 = (ImageView) findViewById(R.id.imageView11);
img01.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
}
snd.play(soundID);
return false;
}
});
}
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
#Override
protected void onPause() {
super.onPause();
snd.unloadAll();
}
}
Put this onResume()
int value = 0;
SharedPreferences prefs = getBaseContext().getSharedPreferences("mySharedPrefsFilename1", Context.MODE_PRIVATE);
value = prefs.getInt("seekBarValue", 100)
volbar1.setProgress(value);
I am doing the same thing. Its working for me. Here is my code. It does not have all the Sound stuff.
package com.titlesource.testproject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.SeekBar;
public class ActivityMain extends AppCompatActivity {
SeekBar.OnSeekBarChangeListener barChange1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_main);
}
public void onRestart() {
super.onRestart();
}
public void onResume() {
super.onResume();
final Button btnOpenPopup = (Button)findViewById(R.id.button6);
btnOpenPopup.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
barChange1 = new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
SharedPreferences prefs = getBaseContext().getSharedPreferences("mySharedPrefsFilename1", Context.MODE_PRIVATE);
prefs.edit().putInt("seekBarValue", seekBar.getProgress()).commit();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
};
SeekBar volbar1 = (SeekBar)popupView.findViewById(R.id.VolBar1);
volbar1.setMax(100);
int value = 0;
SharedPreferences prefs = getBaseContext().getSharedPreferences("mySharedPrefsFilename1", Context.MODE_PRIVATE);
value = prefs.getInt("seekBarValue", 100);
volbar1.setProgress(value);
volbar1.setOnSeekBarChangeListener(barChange1);
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss);
btnDismiss.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
popupWindow.showAsDropDown(btnOpenPopup, 60, 20);
}});
{
}
}
}
Sir, we are developing an app to teach small children write alphabets.. Here we show a screen with two images where one image is on the right side it is just to show the image of the alphabet, and the the other one is a light image where the user can draw on image for practise. I want to validate the image drawn by the user whether he has drawn correctly on the base image or not.!
(Note: I exactly dont know what is the use of "Scaling" which i used in it.)Can i please get a solution because i tried a lot but cudnt get an answer
The code is:
enter code here
package com.example.androidhive;
import com.example.androidhive.ColorPickerDialog.OnColorSelectedListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.support.v4.view.MotionEventCompat;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class FullImgTwoActivity extends Activity implements OnTouchListener {
int pp;
int pickupLinesItemIndex;
int position;
PaintView paintView;
ViewFlipper layout;
int size = 0;
int progress = 0;
ImageView imageView1;
private Bitmap bmp;
private Bitmap operation;
GetScaling scaling;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
paintView = new PaintView(this);
scaling=new GetScaling(this);
layout = (ViewFlipper) findViewById(R.id.view1);
Intent i = getIntent();
position = i.getExtras().getInt("id");
final ImageAdapterTwo imageAdapterTwo = new ImageAdapterTwo(this);
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageResource(imageAdapterTwo.mThumbIdsx[position]);
bmp=imageView1.getDrawingCache();
layout.setBackgroundResource(imageAdapterTwo.mThumbIdsy[position]);
paintView.setLayoutParams(new LinearLayout.LayoutParams(500, 500));
layout.addView(paintView);
ImageView back = (ImageView) findViewById(R.id.imageView3);
back.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (pickupLinesItemIndex < imageAdapterTwo.mThumbIdsw.length) {
if (position <= 0) {
Toast.makeText(getApplicationContext(), "This is the starting alphabet", 90)
.show();
} else {
imageView1
.setImageResource(imageAdapterTwo.mThumbIdsx[--position]);
layout
.setBackgroundResource(imageAdapterTwo.mThumbIdsy[position]);
}
}
}
});
ImageView nexta = (ImageView) findViewById(R.id.imageView4);
nexta.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (pickupLinesItemIndex > imageAdapterTwo.mThumbIdsw.length) {
//if (position <=imageAdapter.mThumbIds.length) {
Toast.makeText(getApplicationContext(), "This level is done", 90)
.show();
} else {
imageView1
.setImageResource(imageAdapterTwo.mThumbIdsx[++position]);
layout
.setBackgroundResource(imageAdapterTwo.mThumbIdsy[position]);
//}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.select_color_menu:
showColorPickerDialogDemo();
break;
case R.id.select_clear_menu:
paintView.clear();
paintView.invalidate();
break;
case R.id.pointers_select_menu:
// pointerDialog();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void pointerDialog() {
// TODO Auto-generated method stub
final Dialog d = new Dialog(FullImgTwoActivity.this);
d.setTitle("Increase pointer size");
d.setContentView(R.layout.pointerssize);
SeekBar bar = (SeekBar) d.findViewById(R.id.seekBar1);
Button save = (Button) d.findViewById(R.id.save);
Button cancel = (Button) d.findViewById(R.id.cancel);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
progress = progresValue;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Display the value in textview
size = seekBar.getMax();
}
});
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
paintView.setSize(progress);
d.dismiss();
}
});
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
d.dismiss();
}
});
d.show();
}
private void showColorPickerDialogDemo() {
int initialColor = Color.WHITE;
ColorPickerDialog colorpick = new ColorPickerDialog(
FullImgTwoActivity.this, initialColor,
new OnColorSelectedListener() {
#Override
public void onColorSelected(int color) {
paintView.setColo(color);
}
});
colorpick.show();
}
public void Checkimage(View v) {
scaling.checktheimage(imageView1);
scaling.checkpaintimage(paintView);
boolean paint=scaling.bmapaint;
boolean image=scaling.bmapimage;
if(paint!=image){
AlertDialog.Builder al=new AlertDialog.Builder(FullImgTwoActivity.this);
al.setTitle("Please Try Again");
al.setIcon(R.drawable.checkno);
al.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
paintView.clear();
paintView.invalidate();
}
}) ;
al.setNegativeButton("NO",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent in=new Intent(FullImgTwoActivity.this, GridLayoutTwo.class);
startActivity(in);
finish();
}
});
AlertDialog dialog=al.create();
dialog.show();
}else {
AlertDialog.Builder al=new AlertDialog.Builder(FullImgTwoActivity.this);
al.setTitle("Please Go To Next Letter");
al.setIcon(R.drawable.checkno);
al.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent in=new Intent(FullImgTwoActivity.this, GridLayoutTwo.class);
startActivity(in);
finish();
}
}) ;
al.setNegativeButton("NO",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
paintView.clear();
paintView.invalidate();
}
});
AlertDialog dialog=al.create();
dialog.show();
}
}
//#Override
public boolean onCreateOptionsMenu1(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_full_img_two, menu);
return true;
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}
i have made a countdown timer using progressbar and a thread,Now i want to stop the progress at the same time when user clicks on a button.I have tried thread.stop(),but it says there is .no such method,I have tried interruot method too with no luck,So can any buddy please help me by viewing my code.My code is as below:
code
package com.amar.lyricalgenius;
import com.amar.lyricalgenius.LoadingActivity.MyCountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class SinglePlayerOption extends Activity implements OnClickListener {
// visible gone
private int progressStatus = 0;
private Handler handler = new Handler();
Intent i;
TextView text_player_second;
ImageView vs_word;
ImageView player_second_pic, player_second_box;
ImageButton red_point1;
TextView text_number_pt1;
TextView text_number1;
ProgressBar pg_loading;
private CountDownTimer countDownTimer;
TextView timer_text;
private final long startTime = 8 * 1000;
private final long interval = 1 * 1000;
Button opt_1, opt_2, opt_3, opt_4;
Thread splashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.single_player_option);
init();
}
private void init() {
// TODO Auto-generated method stub
text_player_second = (TextView) findViewById(R.id.text_player_second);
vs_word = (ImageView) findViewById(R.id.vs_word);
player_second_pic = (ImageView) findViewById(R.id.player_second_pic);
player_second_box = (ImageView) findViewById(R.id.player_second_box);
red_point1 = (ImageButton) findViewById(R.id.red_point1);
text_number_pt1 = (TextView) findViewById(R.id.text_number_pt1);
text_number1 = (TextView) findViewById(R.id.text_number1);
opt_1 = (Button) findViewById(R.id.option_1);
opt_2 = (Button) findViewById(R.id.option_2);
opt_3 = (Button) findViewById(R.id.option_3);
opt_4 = (Button) findViewById(R.id.option_4);
opt_1.setOnClickListener(this);
opt_2.setOnClickListener(this);
opt_3.setOnClickListener(this);
opt_4.setOnClickListener(this);
text_player_second.setVisibility(View.GONE);
vs_word.setVisibility(View.GONE);
player_second_pic.setVisibility(View.GONE);
player_second_box.setVisibility(View.GONE);
red_point1.setVisibility(View.GONE);
text_number_pt1.setVisibility(View.GONE);
text_number1.setVisibility(View.GONE);
countDownTimer = new MyCountDownTimer(startTime, interval);
timer_text.setText(timer_text.getText()
+ String.valueOf(startTime / 1000));
countDownTimer.start();
new Thread(new Runnable() {
public void run() {
while (progressStatus < 100) {
progressStatus += 1;
// Update the progress bar and display the
// current value in the text view
handler.post(new Runnable() {
public void run() {
pg_loading.setProgress(progressStatus);
}
});
try {
// Sleep for 200 milliseconds.
// Just to display the progress slowly
Thread.sleep(62);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
splashThread = new Thread() {
public void run() {
try {
sleep(6000);
// Utils.systemUpgrade(SplashActivity.this);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = null;
intent = new Intent(SinglePlayerOption.this,
NoResponseActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
}
};
splashThread.start();
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i;
switch (v.getId()) {
case R.id.option_1:
splashThread.stop();
countDownTimer.onFinish();
Toast.makeText(SinglePlayerOption.this,
timer_text.getText().toString(), 1).show();
i = new Intent(SinglePlayerOption.this,
DialogLeaderboardActivity.class);
startActivity(i);
break;
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
timer_text.setText("Time's up!");
}
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("" + millisUntilFinished / 1000);
}
}
}
Thread th = new Thread(new Runnable() {
public void run() { ....
th.start();//starts
th.interrupt();//this stops.
and use
while (progressStatus < 100 && (!Thread.currentThread().isInterrupted())){....
instead of
while (progressStatus < 100) {....
Now i want to stop the progress at the same time when user clicks on
a button.I have tried thread.stop()
Thread.stop() is deprecated and you should not use it. The basic concept to understand is that a thread terminates is execution when the last line of code of his run method is executed. In the case of your "ProgressBar Thread*, when the user press the button, you have to set the exit condition of your while-loop (progressStatus = 100) in order to make it terminate
I am trying to play a sound on button click and I am trying to make it call the .start() function only but the problem is I set the i parameter in the onclick function and so it does not pass the i to the onclicklistner function any ideas how to fix that ??
here is my code
package com.example.buttonsdemo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.SimpleCursorAdapter.ViewBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
//Creating Sound arrays
int i=0;
MediaPlayer[] mediaplayer = new MediaPlayer[120];
Button button[] = new Button [120];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize the mediaplayer
for(int z=0;z<120;z++)
{
mediaplayer[z]=null;
}
//Initialize Button Array
for(int x=0;x<120;x++)
{
button[x]=new Button(this);
button[x].setOnClickListener(this);
}
//Creating Media player array
mediaplayer[0]= MediaPlayer.create(this,R.raw.akali);
mediaplayer[1]= MediaPlayer.create(this,R.raw.alistar);
button[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.akali:
i=0;
break;
case R.id.alistar:
i=1;
break;
}
mediaplayer[i].start();
}
} );
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Inside your Listener, you want to use a variable which is declared inside your Listener.
You are trying to use a variable (i) which is declared in code which is not run when the Listener is run.
new View.OnClickListener() {
#Override
public void onClick(View v) {
int idx;
switch(v.getId()) {
case R.id.akali:
idx=0;
break;
case R.id.alistar:
idx=1;
break;
}
mediaplayer[idx].start();
}
}
Or invoke the respective start() method right in the case.
Dump the 'i' declared. Replace method with this (the "Button theButton" needs to stay 'final').
for(int z=0;z<120;z++)
{
final Button theButton = button[z];
theButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
// do what you want.
}
});
}
I believe your onCreate should be created like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize the mediaplayer
for(int z=0;z<120;z++)
{
mediaplayer[z]=null;
}
mediaplayer[0]= MediaPlayer.create(this,R.raw.akali);
mediaplayer[1]= MediaPlayer.create(this,R.raw.alistar);
//Initialize Button Array
for( x=0;x<120;x++)
{
button[x]=new Button(this);
button[x].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaplayer[x].start();
}
} );
}
}
So basically you just need to make several button on the fly which produces different sound when clicked. Try this code:
Button myButton[] = new Button[100];
MediaPlayer mySound = new MediaPlayer();
for (int i=0; i<100; i++) {
myButton[i] = new Button(this);
myButton[i].setId(i+1);
myButton[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Resources res = context.getResources();
int soundId = res.getIdentifier("sound" + v.getId(), "raw", context.getPackageName());
mySound.create(getApplicationContext(), soundId);
mySound.start();
}
});
}
OK so I'm using xml to set this menu which is supported by the following java code
package starting.rt;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Menu extends Activity implements OnClickListener{
View.OnTouchListener gestureListener;
TextView display;
Button begin;
Button random;
Button game;
TextView counter;
Button next;
Button previous;
Button moreapps;
Button rate;
Random myRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(starting.rt.R.layout.menu);
begin = (Button) findViewById(starting.rt.R.id.Begin);
random = (Button) findViewById(starting.rt.R.id.Random);
display = (TextView) findViewById(starting.rt.R.id.tvResults);
counter = (TextView) findViewById(starting.rt.R.id.tvCounter);
next = (Button) findViewById(starting.rt.R.id.Next);
previous = (Button) findViewById(starting.rt.R.id.Previous);
moreapps = (Button)findViewById(R.id.More);
rate = (Button) findViewById(R.id.rate);
game = (Button) findViewById(R.id.game);
// display.setOnTouchListener(this.gestureListener);
begin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.RelationshipTipsActivity");
startActivity(openStartingPoint);
}});
moreapps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:\"Wompa\""));
startActivity(goToMarket);
}});
game.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.GameView");
startActivity(openStartingPoint);
}});
rate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);
}});}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Now what's supposed to be happening is when they click on the game which starts a new java class called GameView it crashes on clicked. Every other button works.
This is the code from GameView
package starting.rt;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread gameLoopThread;
private List<Sprite> sprites = new ArrayList<Sprite>();
private List<TempSprite> temps = new ArrayList<TempSprite>();
private long lastClick;
private Bitmap bmpBlood;
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameLoopThread.setRunning(false);
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.bad1));
// sprites.add(createSprite(R.drawable.bad2));
// sprites.add(createSprite(R.drawable.bad3));
// sprites.add(createSprite(R.drawable.bad4));
// sprites.add(createSprite(R.drawable.bad5));
// sprites.add(createSprite(R.drawable.bad6));
// sprites.add(createSprite(R.drawable.good1));
// sprites.add(createSprite(R.drawable.good2));
// sprites.add(createSprite(R.drawable.good3));
// sprites.add(createSprite(R.drawable.good4));
// sprites.add(createSprite(R.drawable.good5));
// sprites.add(createSprite(R.drawable.good6));
}
private Sprite createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 300) {
lastClick = System.currentTimeMillis();
float x = event.getX();
float y = event.getY();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isCollition(x, y)) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
break;
}
}
}
}
return true;
}
}
The GameView calls a few other classes for things part of the game but it crashes before it can start. I think it's crashing because it's switching from xml layout to the java surfaceview. Help would be appreciated :) Thanks!
First of all, you should always post in your questions the stacktrace with the exception from the Logcat if your app crashes.
You can't start a SurfaceView directly, instead your custom SurfaceView must be embedded in an Activity like any other view in android. For example:
public class GameViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(new GameView(this));
}
}