I have couple of activities. On the mainActivity I have 4 buttons each leads to another activity.
On three of the activities I activate a thread which draws in a canvas and in each of them I have a button to return to the mainActivity. I have tried using:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// i tried also (theClassName.this,MainActivity.Class)
startActivity(i);
When I clicked on the return button, I did return to the mainActivity but the app stopped responding (it alerted me that the app isn't responding and I had to choose between waiting or exiting the app. Waiting doesn't help).
When I used
finish();
instead,
And clicked on the return button, I returned to the home screen of the device (went out of the app) but didn't exit it - I could still go back to the app using the task manager, and when I did it put me back in the activity I entered and not the mainActivity.
As I said I have 4 buttons on the mainActivity and when I use the fourth one it goes to another activity that doesn't activate a thread, it only has listView, and when I return from it to the mainActivity it does work.
How can I fix it? Thanks for the help
*when the problem occurs there is no error stack trace.
*if you need to see any code tell and I'll be happy to post it here
The code:
MainActivity:
public class MainActivity extends Activity {
Button classic;
Button vsPlayer;
Button vsComp;
// Button settings;
Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
classic=(Button) findViewById(R.id.Classic);
classic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ClassicActivity.class);
startActivity(i);
}
});
vsPlayer=(Button) findViewById(R.id.PlayerVSPlayer);
vsPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsPlayerActivity.class);
startActivity(i);
}
});
vsComp=(Button) findViewById(R.id.PlayerVSComp);
vsComp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsCompActivity.class);
startActivity(i);
}
});
/* settings=(Button) findViewById(R.id.Settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
});
*/
scores=(Button) findViewById(R.id.Scores);
scores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ScoresActivity.class);
startActivity(i);
}
});
}//onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mains, menu);
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
MainActivity.this.finish();
}
}
-=------ some other activity:
public class ClassicActivity extends Activity {
Classic g;
ImageView left;
ImageView right;
ImageView up;
ImageView down;
TextView pause;
TextView back;
TextView scoretv;
LinearLayout surface;
LinearLayout screen;
LinearLayout stoped;
LinearLayout gameover;
ScoreDataSource sds;
Button no;
Button yes;
EditText name;
Button continueb;
Button leave;
//protected static TextView MyScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
v= new GameView1(this);
setContentView(v);
*/
setContentView(R.layout.activity_classic);
sds=new ScoreDataSource(this);
gameover=(LinearLayout) findViewById(R.id.gameover);
screen = (LinearLayout)findViewById(R.id.screen);
surface = (LinearLayout)findViewById(R.id.surface);
g= new Classic(this, surface);
surface.addView(g);
//MyScore=(TextView) findViewById(R.id.MyScore);
//MyScore.setText("My score:"+gv.getPoints());
left=(ImageView) findViewById(R.id.left);
right=(ImageView) findViewById(R.id.right);
up=(ImageView) findViewById(R.id.up);
down=(ImageView) findViewById(R.id.down);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="LEFT"&&g.snake.getDir()!="RIGHT"){
g.snake.Left();
}
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="RIGHT"&&g.snake.getDir()!="LEFT"){
g.snake.Right();
}
}
});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="UP"&&g.snake.getDir()!="DOWN"){
g.snake.Up();
}
}
});
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="DOWN"&&g.snake.getDir()!="UP"){
g.snake.Down();
}
}
});
pause=(TextView) findViewById(R.id.Pause);
back=(TextView) findViewById(R.id.Back);
stoped=(LinearLayout) findViewById(R.id.stoped);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getRunning()){
pause.setText("continue");
g.setRunning(false);
}
else{
pause.setText("pause");
g.setRunning(true);
new Thread(g.snakethread).start();
}
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
g.setRunning(false);
stoped.setVisibility(View.VISIBLE);
}
});
no=(Button) findViewById(R.id.no);
yes=(Button) findViewById(R.id.yes);
continueb=(Button) findViewById(R.id.Continue);
leave=(Button) findViewById(R.id.leave);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
name=(EditText) findViewById(R.id.name);
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String date = df.format(c.getTime());
sds.open();
Score s=new Score(0,name.getText().toString(),date, g.getPoints(),"Classic");
s=sds.createScore(s);
sds.close();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
continueb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stoped.setVisibility(View.GONE);
g.setRunning(true);
new Thread(g.snakethread).start();
}
});
leave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
scoretv=(TextView) findViewById(R.id.scoretv);
screen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getGameover()){
scoretv.setText("Your score is:"+g.getPoints());
gameover.setVisibility(View.VISIBLE);
g.setGameover(false);
}
}
});
}
#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;
}
}
----ClassicActivity usus this activity:
public class Classic extends SurfaceView implements Runnable {
private boolean isRunning=false;
private final long FPS=8;//MAX is 16
final float scale = Resources.getSystem().getDisplayMetrics().density;
float PART_SIZE= 10*scale;
private SurfaceHolder holder;
Thread snakethread;
static SnakePlayer snake;
Arena a;
LinearLayout view;
Bitmap arena;
Food food1;
Boolean gameover;
int points;
Paint writePB=new Paint();
Paint writePR=new Paint();
public Classic(Context context,LinearLayout view) {
super(context);
this.gameover=false;
this.view=view;
this.a=new Arena(view,PART_SIZE,33,36,1,0);
this.food1=new Food(PART_SIZE,"GRAY");
points=0;
writePB.setColor(Color.BLACK);
writePB.setTextSize(PART_SIZE);
writePR.setColor(Color.RED);
writePR.setTextSize(PART_SIZE);
snakethread=new Thread(this);
holder= getHolder();
holder.addCallback(new SurfaceHolder.Callback(){
#Override
public void surfaceCreated(SurfaceHolder arg0) {
setRunning(true);
snakethread.start();
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,int arg3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
setRunning(false);
while(true){
try {
snakethread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
snake=new SnakePlayer(0+3*PART_SIZE, 0+3*PART_SIZE, "RIGHT",PART_SIZE,2,"RED","BLACK");
}
#SuppressLint("WrongCall")
#Override
public void onDraw(Canvas c) {
a.onDraw(c);
c.drawText("Your Score:"+points, 5*scale, 10*scale, writePB);
food1.drawFood(c);
snake.onDraw(c);
}
#SuppressLint("WrongCall")
#Override
public void run() {
long stepPerSecond=1000/FPS;
long startTime;
long sleepTime;
Canvas c = null;
while(isRunning){
startTime=System.currentTimeMillis();
c = null;
try{
c=this.getHolder().lockCanvas();
onDraw(c);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
AllChecks(c);
sleepTime= stepPerSecond-(System.currentTimeMillis()-startTime);
if(sleepTime>0)
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(gameover){
try{
c=this.getHolder().lockCanvas();
c.drawText("GAMEOVER", 125*scale, 150*scale, writePR);
c.drawText("Touch Anywhere To Continue ", 87*scale, 162*scale, writePR);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
}
}
boolean firstTime=true;
public void AllChecks(Canvas c){
/*
* Call all the right function, to check if the snake has bumped in a wall, or eaten a food.
*/
if(Arena.WallCollision(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(snake.snakeCollisionNoHead(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(firstTime){
firstTime=false;
changeFoodLoc(food1);
}
if(food1.hasEaten(snake.getxLoc(), snake.getyLoc())){
changeFoodLoc(food1);
snake.Add();
points+=10;
}
}
public void changeFoodLoc(Food food){
/*
* if a snake has eaten a food it changes the location of the food randomly
*/
Random rnd = new Random();
food.x=(rnd.nextInt(32) + 3)*food.SIZE;
food.y=(rnd.nextInt(35) + 1)*food.SIZE;
if(snake.snakeCollision(food.getX(), food.getY()))
changeFoodLoc(food);
}
public void setRunning(boolean b){
isRunning=b;
}
public Boolean getRunning(){
return isRunning;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public Boolean getGameover() {
return gameover;
}
public void setGameover(Boolean gameover) {
this.gameover = gameover;
}
}
First I would try removing the override on the MainActivity for onPause - you do not need to call finish. In your second activity, if you want to go back to the MainActivity- call finish on the 2nd activity and it should go back to the MainActivity.
Related
Actually i have 2 activities , in the main activity i am displaying all the songs using recycler view and setup an onClickListner on it, and when someone taps on it , it launches a new activity(MediaPlayer Activity) and start playing the song along with media controls like (paly, pause and seekBar).
But when i get back to the main activity and click on a button (which basically takes to the MediaPlayer activity again) all the mediaPlayer and seekBar progress are gone also the (play, pause, next and previous buttons) are not responding to the clicks.
This is from where i am starting the MediaPlayer activity :
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.Song.setText(mData.get(position).title);
holder.Artist.setText(mData.get(position).artist);
Glide.with(mcontext).load(mData.get(position).imagePath).
placeholder(R.drawable.unknown_art).into(holder.PhotoId);
holder.Options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mcontext, "You clicked on options", Toast.LENGTH_SHORT).show();
}
});
holder.RL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mcontext, MediaPlayerActivity.class);
intent.putExtra("songPosition",position);
mcontext.startActivity(intent);
}
});
These are the codes in the MediaPlayerActivity :
public class MediaPlayerActivity extends AppCompatActivity {
static MediaPlayer mediaPlayer=null;
static int pos=0;
SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent intent = getIntent();
pos = intent.getIntExtra("songPosition",pos);
seekBar = (SeekBar)findViewById(R.id.seekBar);
Button next = (Button)findViewById(R.id.button_1);
Button previous = (Button)findViewById(R.id.button_2);
final Button play_pause = (Button)findViewById(R.id.button_3);
final TextView info = (TextView)findViewById(R.id.songInfo);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
playMedia(pos);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(++pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the last song!!!",Toast.LENGTH_SHORT).show();
}
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(--pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the first song!!!",Toast.LENGTH_SHORT).show();
}
}
});
play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
play_pause.setText(R.string.mp_play);
mediaPlayer.pause();
}
else{
play_pause.setText(R.string.mp_Pause);
mediaPlayer.start();
}
}
});
}
public void playMedia(int pos){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(VerticalRecyclerViewAdapter.mData.get(pos).songPath);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
setSeekbarProgress();
onSeekbarChange();
playNext();
}
public void playNext(){
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
mediaPlayer.release();
playMedia(++MediaPlayerActivity.pos);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this, "Already the last song", Toast.LENGTH_SHORT).show();
}
}
});
}
public void setSeekbarProgress(){
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
if (mediaPlayer != null) {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
}
catch (RuntimeException e){
Log.i("CRASH",""+e.getMessage());
}
}
},0,1000);
}
public void onSeekbarChange(){
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(b) {
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
And this is where from i wanted to go back to the MediaPlayer Activity (on button click ) :
mFloatingToolbar.setClickListener(new FloatingToolbar.ItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.music:
Intent intent = new Intent(getActivity(),MediaPlayerActivity.class);
startActivity(intent);
break;
case R.id.pause :
break;
case R.id.next :
Toast.makeText(getContext(), "Next", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getContext(), "Back", Toast.LENGTH_SHORT).show();
verticalRecyclerViewAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onItemLongClick(MenuItem item) {
}
});
this is my code....
StudentLogin.java class
public class StudentLogin extends Activity implements OnClickListener, OnItemSelectedListener{
Spinner sp1,sp2;
EditText reg;
Button b1,b2,b3;
String a1,a2,studreg,studdept,studyr;
SQLiteDatabase db1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_login);
reg=(EditText) findViewById(R.id.editText1);
sp1=(Spinner)findViewById(R.id.spinner1);
sp2=(Spinner)findViewById(R.id.spinner2);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Cursor c=db1.rawQuery("Select * from StudReg", null); // Im getting an error here
int count=c.getCount();
int flag=0;
c.moveToFirst();
String regno=reg.getText().toString();
String yr=a1;
String dept=a2;
Toast.makeText(getApplicationContext(), regno, Toast.LENGTH_LONG).show();
if(regno.trim().length()>0&&!yr.equals("Select Year")&&!dept.equals("Select Dept"))
{
for(int i=0;i<count;i++)
{
studreg=c.getString(c.getColumnIndex("register"));
studdept=c.getString(c.getColumnIndex("deptmt"));
studyr=c.getString(c.getColumnIndex("year"));
if(regno.equals(studreg)&&yr.equals(studyr)&&dept.equals(studdept))
{
flag=1;
break;
}
c.moveToNext();
}
c.close();
if(flag==1)
{
Intent inn=new Intent(StudentLogin.this,StudyMaterials.class);
startActivity(inn);
}
else
{
Toast.makeText(getApplicationContext(), "Invalid User!\nKindly try again..", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Kindly fill all the fields..", Toast.LENGTH_SHORT).show();
}
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intt=new Intent(StudentLogin.this,StudentRegister.class);
startActivity(intt);
}
});
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent int1=new Intent(StudentLogin.this,Update.class);
startActivity(int1);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a1=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a1, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> p, View v,
int a, long l) {
// TODO Auto-generated method stub
a2=p.getItemAtPosition(a).toString();
//Toast.makeText(getApplicationContext(), a2, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
List<String> categories = new ArrayList<String>();
categories.add("Select Department");
categories.add("CSE");
categories.add("IT");
categories.add("CIVIL");
categories.add("MECH");
categories.add("ECE");
categories.add("EEE");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(dataAdapter);
List<String> categories1 = new ArrayList<String>();
categories1.add("Select Year");
categories1.add("I");
categories1.add("II");
categories1.add("III");
categories1.add("IV");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, categories1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp1.setAdapter(dataAdapter1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.student_login, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onItemSelected(AdapterView<?> p, View v, int it,
long l) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
This code validates whether the user is already registered or not..
Please help me solve this error...
you need to initialize database
//dbHelper its a helper class for database
database = dbHelper.getWritableDatabase();
You have given the table name but you are not saying it on which db the table exists(as db1 is not initialized).So follow #Madhur answer to solve this null pointer exception.Also a suggestion when working with db(better to use loaders instead of working on MainThread).
Can I know how to create AsyncTask for Android from all of these? I would like to remove the buttons and let all of these run in the background then redirect to the MainPage.java after clicking Logout.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Button btnDelete = (Button)findViewById(R.id.delete);
Button btnSignUp = (Button)findViewById(R.id.btnSignUp);
Button btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),HomePage.class);
startActivity(intent);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,SignUp.class);
startActivity(intent);
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cDB.resetTables();
mDB.resetTables();
db.resetTables();
pDB.resetTables();
}
});
}
here is one AsyncTask Example. This will show a peogress dialog while executing the task.
private class LoginProcessing extends AsyncTask<Object, Void, Void> {
private LoginCredentials myLoginCredentials;
private ProgressDialog progressDialog;
public LoginProcessing(LoginCredentials Credentials) {
super();
myLoginCredentials=Credentials;
}
protected void onPreExecute (){
progressDialog = ProgressDialog.show(context, "", "Please Wait...",true);
}
#Override
protected Void doInBackground(Object... arg0) {
// TODO Auto-generated method stub
//Code to do the process in background
return null;
}
protected void onPostExecute(Void result){
progressDialog.dismiss();
//Your code after the process
}
}
You can call this Task as,
new LoginProcessing(loginCredentials).execute();
In this Example loginCredentials is the parameter I am passing to the AsyncTask. You can change it to your own parameter.
I integrated Google+ button, and I see it in my app but it's "greyed out" or white, it's not red and white and when I click it nothing happens. Here's my code:
public class Menu extends Activity implements OnClickListener, ConnectionCallbacks,
OnConnectionFailedListener{
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
private PlusOneButton mPlusOneButton;
ImageButton exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final PlusOneButton mPlusOneButton = new PlusOneButton(this);
mPlusClient = new PlusClient.Builder(this, this, this).clearScopes()
.build();
mPlusOneButton.initialize("https://market.android.com/details?id=" + getPackageName(),
new OnPlusOneClickListener() {
#Override
public void onPlusOneClick(Intent intent) {
mPlusOneButton.setVisibility(View.INVISIBLE);
startActivityForResult(intent, 0);
}
});
setContentView(R.layout.menu);
inicijalizujVars();
}
#Override
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(this,
REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
mConnectionResult = result;
}
#Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR
&& responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
private void inicijalizujVars() {
exit = (ImageButton) findViewById(R.id.imageButtonExit);
exit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onResume(){
super.onResume();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
And my button in my layout xml:
<com.google.android.gms.plus.PlusOneButton
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="#+id/plus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:layout_marginTop="-30dp"
android:gravity="center"
plus:annotation="bubble"
plus:size="tall" />
I need to have a button that is suppose to have two functions.
If I tap on it once, it will go to the next page.
If I hold down on the button, it will allow me to edit the text on the button.
The button is able to go to the next page upon tapping on it, but how do I implement the second function which allows me to change the text If I hold down the button?
Does anybody know?
java code
public class MainActivity extends Activity {
Button button1;
Button button2;
Button button3;
Handler h;
private Socket socket;
private boolean mInSettingsMode;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "192.168.43.83";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
// living button click start
button1 = (Button) findViewById(R.id.btnliving);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun, 0);
}
});
button2 = (Button) findViewById(R.id.btnbed);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun2, 0);
}
});
button3 = (Button) findViewById(R.id.btndin);
button3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
h = new Handler();
h.postDelayed(irun3, 0);
}
});
}
Runnable irun = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, living.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
Runnable irun2 = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, bed.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
Runnable irun3 = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, din.class);
startActivity(i);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
};
/*
* #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; }
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
// new Thread(new ClientThread()).start();
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
xml code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical"
android:background="#drawable/back1"
tools:context=".MainActivity" >
<Button
android:id="#+id/btnliving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Light Control"
/>
<Button
android:id="#+id/btnbed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fan Control"
/>
<Button
android:id="#+id/btndin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Thermostat Control"
/>
</LinearLayout>
You can set second function as a setOnLongClickListener as:
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
//change text here
return true;
}
});
and first function is same setOnclickListener as:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
check this Documentation
button.setOnTouchListener(new View.OnTouchListener() {
private static final long MAX_CLICK_TIME = 400;
long time = 0;
#Override
public boolean onTouch(View view, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
time = System.currentTimeMillis();
} else if (MotionEvent.ACTION_UP == event.getAction()) {
long pressingTime = System.currentTimeMillis() - time;
if (pressingTime > MAX_CLICK_TIME) {
// do change text logic
} else {
// show new page logic
}
}
return true;
}
});
If you want to change the text of a button without having to wait until the user removes his finger from the button, you can use TimerTask.Code with TimerTask:
button.setOnTouchListener(new View.OnTouchListener() {
private static final long MAX_CLICK_TIME = 400;
long time = 0;
Timer timer = new Timer();
#Override
public boolean onTouch(View view, MotionEvent event) {
if (MotionEvent.ACTION_DOWN == event.getAction()) {
time = System.currentTimeMillis();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
// do change text logic
}
};
timer.schedule(timerTask, MAX_CLICK_TIME);
} else if (MotionEvent.ACTION_UP == event.getAction()) {
long pressingTime = System.currentTimeMillis() - time;
if (pressingTime <= MAX_CLICK_TIME) {
timer.cancel();
// show new page logic
}
}
return true;
}
});
I have not tested, but should work. In any case, the idea should be clear.