How to reduce this below java code? - java

Here I've written some code to navigate to different links using different buttons in android. Is there anyway to reduce my code further than I've coded. If it is possible please do help me to reduce the code. here is my code:
Button tv = (Button) findViewById(R.id.my1);
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link1"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
Button tv1 = (Button) findViewById(R.id.my2);
tv1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link2"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
Button tv2 = (Button) findViewById(R.id.my3);
tv2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("link3"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});

Once try as follows take a method for re usability
public void openLink(final String link){
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
and implements onClickListener and in onClick
#Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.my1:
openLink(link1);
break;
case R.id.my2:
openLink(link2);
break;
case R.id.my3:
openLink(link3);
break;
}
Hope this will helps you.

Button tv = (Button) findViewById(R.id.my1);
tv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startAnotherActivity("link1");
}
});
Button tv1 = (Button) findViewById(R.id.my2);
tv1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startAnotherActivity("link2");
}
});
Button tv2 = (Button) findViewById(R.id.my3);
tv2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startAnotherActivity("link3");
}
});
private void startAnotherActivity(final String link){
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}

Create one method for click listener and use if condition.
Here is sample code.
Your OnCreate Code:
Button tv = (Button) findViewById(R.id.my1);
onClick(tv);
tv1 = (Button) findViewById(R.id.my2);
onClick(tv1);
Button tv2 = (Button) findViewById(R.id.my3);
onClick(tv2);
Common Method : Declare mLink Variable as Global
public void onClick(View v)
{
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v == tv)
mLink = "link1";
else if(v == tv1)
mLink = "link2";
else if(v == tv2)
mLink = "link3";
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(mLink));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
}

implement onClickListener on your activity and override the onClick() method and write your code in this manner
#Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.my1:
//your code here
break;
case R.id.my2:
//your code here
break;
}

OK, I'll post an example, but only because there's a little non-trivial concept that needs explaining:
Button tv = (Button) findViewById(R.id.my1);
setListenerForButton(tv, "link1");
Button tv1 = (Button) findViewById(R.id.my2);
setListenerForButton(tv1, "link2");
Button tv2 = (Button) findViewById(R.id.my3);
setListenerForButton(tv1, "link3");
private void setListenerForButton(Button button, final String link) {
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(myscale);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} catch (Exception e) {
Log.e("Exception Caught", e.toString());
}
}
}, 50);
}
});
}
The detail is that for link to be used in the anonymous inner class that you're setting up for the listener, link has to be final.
I've looked this over and believe it will work, but I haven't tried it.

Related

TimerTask behaving like running twice or more

I am trying to make a multiplayer (2 people) turn based game which lets users do whatever they want in 60 seconds. Added Timer and TimerTask to my project. When playing first time all is good, but when I return to main screen (previous intent) with something like exit game button and re-enter game counter seems to be running like twice. Instead of going like 60-59-58 it goes like 60-58-55-53 and so on. Should I do something to stop counter while exiting game?
Here is my code:
public class ikinciekren extends AppCompatActivity{
....
#Override
public void onBackPressed()
{
...
...
cikisonay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
kullanici.status(mDatabase,"lose");
Intent intocan = new Intent(ikinciekren.this, MainActivity.class);
intocan.putExtra("firebaseuser", facebookname);
intocan.putExtra("firebaseuid", myuid);
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
startActivity(intocan);
}
});
cikisiptal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
...
...
// On button click opponents timer starts to run
btn = (Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView number = (TextView) findViewById(R.id.textView4);
String number2 = number.getText().toString();
if(number2!=null ||number2!=""){
if (number2.length()==4) {
status =false;
resetSomeTimer();
launchSomeTimer();
...
...
}
}
}
});
...
...
ValueEventListener postListener2 = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
String turn = String.valueOf(dataSnapshot.getValue());
//Read a node in firebase database and acts according to that
if ("true".equals(turn)) {
status =true;
}
if ("false".equals(turn)) {
status =false;
}
resetSomeTimer();
launchSomeTimer();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Context context = getApplicationContext();
Toast.makeText(context, "Failed to load post.",
Toast.LENGTH_SHORT).show();
}
};
...
...
}
protected void onDestroy(){
super.onDestroy();
///// added this just incase
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
kullanici.status(mDatabase,"off");
finish();
}
public void cikis(View view) {
if(view.getId()==R.id.button3){
...
...
cikisonay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
...
...
///// added this just incase
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
startActivity(intocan);
}
});
cikisiptal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
...
}
}
private void launchSomeTimer() {
runstatus=true;
oppenenttimertext.setText("60");
owntimertext.setText("60");
sayac =60;
counter = new TimerTask() {
#Override
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run () {
sayac--;
if (status) {
owntimertext.setText(String.valueOf(sayac));
} else {
oppenenttimertext.setText(String.valueOf(sayac));
}
if (sayac == 0) {
myTimer.cancel();
kullanici.timenotice(mDatabase);
}
}
});
}
};
myTimer = new Timer();
myTimer.schedule(counter,1000,1000);
}
public void resetSomeTimer(){
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
}
}

application started crashing when trying to login using facebook after ide error

My application was working perfectly then, after adding the following code LoginManager.getInstance().logOut(); to disconnect from the current facebook account (a developper acount), the ide showed that an error occurred while running the app, but the application launched anyway, but when trying to login, it crashed and now it's not logging in, it keeps crashing! even though I changed nothing except adding that line of code to the next activity to make the app disconnect in case the user want to logout!
here's my java code:
public class ConnexionActivity extends AppCompatActivity {
Button b_bb, b_back, ee, b_inscrp_formulaire, fb;
EditText tb_pseudo, tb_mdp;
int id;
String name, gender, email, birthday;
private LoginButton loginButton;
private CallbackManager callbackManager;
Profile profile;
//new try:
private AccessTokenTracker accessTokenTracker;
private Button customFacebookLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
/*List<String> permissionNeeds = Arrays.asList("user_photos", "email",
"user_birthday", "public_profile", "AccessToken");*/
setContentView(R.layout.activity_connexion);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
b_inscrp_formulaire = (Button) findViewById(R.id.b_inscrip_formulaire);
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setText("");
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday"));
//"user_photos", "email","user_birthday", "public_profile"
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
//getting the hash key
try {
PackageInfo info = getPackageManager().getPackageInfo(
"your.package",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
//2nd way to generate hash key (or get it)
try {
PackageInfo info = getPackageManager().getPackageInfo("your.package.name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
b_bb = (Button) findViewById(R.id.b_bb);
b_back = (Button) findViewById(R.id.b_back);
tb_pseudo = (EditText) findViewById(R.id.textbox_pseudo);
tb_mdp = (EditText) findViewById(R.id.textbox_mdp);
/////////////
ee = (Button) findViewById(R.id.button);
////////////
b_bb.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
b_bb.setBackgroundResource(R.drawable.button_bb_selec);
break;
}
case MotionEvent.ACTION_UP: {
b_bb.setBackgroundResource(R.drawable.button_bb);
break;
}
}
return false;
}
});
b_bb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isAuthorized()) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", tb_pseudo.getText().toString());
startActivity(menu_p);
} else {
openDialog();
}
}
});
b_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnexionActivity.this.finish();
}
});
ee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", "Easter");
startActivity(menu_p);
}
});
b_inscrp_formulaire.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent menu_p = new Intent(ConnexionActivity.this, InscriptionActivity.class);
startActivity(menu_p);
}
});
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
graphRequest(loginResult.getAccessToken());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(ConnexionActivity.this, Arrays.asList("user_photos", "email",
"user_birthday", "public_profile"));
profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
Intent menu_p = new Intent(ConnexionActivity.this, MenuPActivity.class);
menu_p.putExtra("pseudo", profile.getFirstName());
startActivity(menu_p);
Toast.makeText(getApplicationContext(), "Connecté : " + profile.getFirstName() + " " + profile.getLastName(), Toast.LENGTH_SHORT).show();
} else {
// user has not logged in
Toast.makeText(getApplicationContext(), "Non-Connecté : Erreur de connexion!!", Toast.LENGTH_SHORT).show();
}
}
});
//To log out of FB:
/*LoginManager.getInstance().logOut();*/
//TODO: check if the user is logged in or not
/* profile = Profile.getCurrentProfile().getCurrentProfile();
if (profile != null) {
// user has logged in
} else {
// user has not logged in
}*/
}
private Boolean isAuthorized() {
if (tb_pseudo.getText().toString().equals("Admin")
&& tb_mdp.getText().toString().equals("0000")
) {
return true;
} else
return false;
}
public void openDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Mauvaise combinaison \"Pseudo\", \"Mot de passe\"");
alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
public void graphRequest(AccessToken token) {
GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Toast.makeText(getApplicationContext(), object.toString(), Toast.LENGTH_LONG).show();
}
});
Bundle b = new Bundle();
b.putString("fields", "id,email,first_name,last_name,picture.type(large)");
request.setParameters(b);
request.executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I guess the problem was just in the IDE, something about indexation!! I closed and reopened the IDE and everything is working just fine.

Save Session Android

I want to do make my app save session to not login again when i kill the process : when i login in the Main.java he weel redirect me to Menu.java then after i kill the precess an runit again he should take me directly to Menu.java without login with saving the username
exactly like this tutu http://www.tutorialspoint.com/android/android_session_management.htm
this is Main.java "Login Page"
public class Main extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
public static final String data = "ett";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button exit = (Button)findViewById(R.id.button18);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(exit);
}
});
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(Main.this, "",
"Verification ...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://192.168.1.4/android/etc.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Main.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
SharedPreferences setting = getSharedPreferences(data, 0);
SharedPreferences.Editor editor = setting.edit();
editor.putString("et", et.getText().toString());
editor.commit();
Intent intent=new Intent(Main.this, Menu.class);
startActivity(intent);
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
Main.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
builder.setTitle("Erreur d'identification");
builder.setMessage("Code ou mot de passe incorrecte")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Menu.java this wher should the app start after saving session
public class Menu extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menus);
Button button1 = (Button)findViewById(R.id.button1);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
Button button14 = (Button)findViewById(R.id.button14);
Button button5 = (Button)findViewById(R.id.button5);
Button exit = (Button)findViewById(R.id.button18);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent1 = new Intent(Menu.this, emploi.class);
startActivity(intent1);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent2 = new Intent(Menu.this, Maritimnews.class);
startActivity(intent2);
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent3 = new Intent(Menu.this, Resultats.class);
startActivity(intent3);
}
});
button14.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent4 = new Intent(Menu.this, Demande.class);
startActivity(intent4);
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent5 = new Intent(Menu.this, Apropos.class);
startActivity(intent5);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
Intent exit = new Intent(Intent.ACTION_MAIN);
exit.addCategory(Intent.CATEGORY_HOME);
exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(exit);
}
});
}
}
i don't know where i put the sharedpreferces exactly to make it save the session
the sharedpreferences there just for passing data between Main.java and Menu.java
i wan't to add another sheredPreferences to save session like facebook means when i login in Main.java ---redirecte--> Menu.java so if i close an run the app again he will start with Menu.java :) and Thank you
if you implement that way the user will login only once in your application and will be forever connected. the best is to do it this way:
first add a checkbox to login to let the user decide if he wants to save his login.
add sharepreferences if checked and delete sharepreferences if uncheck.
read sharedpreferences in the onresume() method of main activity and add some logic to intent directly to menu activity if preferences is not null
I used mySharedPreferences that indicate to me if user already logged in, and I pass a int value from previous activity to know if the user just enter the app or not.
public class ConnectWithFaceBookActivity extends Activity{
int mode = Activity.MODE_PRIVATE;
private SharedPreferences mySharedPreferences;
private String TAG = "ConnectWithFaceBookActivity";
private TextView lblEmail;
private String accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect_with_facebook);
mySharedPreferences = this.getSharedPreferences( "facebook", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor= mySharedPreferences.edit();
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
Intent i = getIntent();
int logout = i.getIntExtra("LOGOUT", 0);
//checking if already sign in
if(logout!=1 && mySharedPreferences.getString("email","")!="")//1 represent logout button preesed
{
String mString;
mString= mySharedPreferences.getString("email","");
lblEmail.setText(mString);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
authButton.setOnErrorListener(new OnErrorListener() {
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
});
// set permission list, Don't foeget to add email
authButton.setReadPermissions(Arrays.asList("public_profile","user_friends","email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback()
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
Boolean open = session.isOpened();
if (open)
{
Log.i(TAG,"Access Token"+ session.getAccessToken());
accessToken = session.getAccessToken();
Request.newMeRequest (session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user,Response response)
{
if (user != null)
{
Log.i(TAG,"User ID "+ user.getId());
Log.i(TAG,"Email "+ user.asMap().get("email"));
String str = user.asMap().get("email").toString();
lblEmail.setText(str);
editor.putBoolean("isLogIn",true);
editor.putString("email",str);
//save the changes that you made
editor.commit();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
}
}).executeAsync();
}
else
{
editor.putBoolean("isLogIn",false);
editor.putString("email","");
//save the changes that you made
editor.commit();
}
}
});
}
public static void callFacebookLogout(Context context) {
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
} else {
session = new Session(context);
Session.setActiveSession(session);
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}

How to kill the activity with back button?

I accidently discovered this. I have a quiz game, and i have a popup for correct answer, for wrong answer and after the game finish I have a popup for result. BUT, today i went back with back button in the middle of the game, to my home screen (not game home screen, my OS home screen) and the game was still in the background, like every other android app. After a few second my wrong answer popped up. :) Time was up, and automatically the answer was wrong. After that my final result popup went on. So, how can I kill that activity when I press back button? I don't know if you guys need any of my code, but just in case here's my game activity:
public class NeogranicenoPetGresaka extends Activity implements OnClickListener{
MyCount brojacVremena = new MyCount(6000, 1000);
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4;
TextView question, netacniOdg, score, countdown;
int brojacPogresnihOdgovora = 0;
int brojacTacnihOdgovora = 0;
public static String tacanOdg;
Runnable mLaunchTask = new Runnable() {
public void run() {
nextQuestion();
brojacVremena.start();
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
brojacVremena.cancel();
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
brojacVremena.cancel();
brojacTacnihOdgovora = brojacTacnihOdgovora + 5;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,1200);
}
/*else{
brojacVremena.cancel();
brojacPogresnihOdgovora++;
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}*/
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.neograniceno);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "myriad.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKvizaN);
netacniOdg = (TextView) findViewById(R.id.tvBrojPitanjaN);
question = (TextView) findViewById(R.id.tvPitanjeN);
bOdgovor1 = (Button) findViewById(R.id.bOdgovorN1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovorN2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovorN3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovorN4);
score = (TextView) findViewById(R.id.tvSkor2N);
countdown = (TextView) findViewById(R.id.tvCountdownN);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
netacniOdg.setTypeface(dugmad);
question.setTypeface(pitanje);
score.setTypeface(dugmad);
countdown.setTypeface(dugmad);
nextQuestion(); //startuje prvo pitanje!
brojacVremena.start(); //startuje brojac vremena
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
brojacPogresnihOdgovora++;
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}
#Override
public void onTick(long millisUntilFinished) {
countdown.setText("" + millisUntilFinished / 1000);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void nextQuestion() {
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
tacanOdg = c.getString(2);
if(brojacPogresnihOdgovora < 20){
question.setText(c.getString(1));
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
netacniOdg.setText("" + brojacPogresnihOdgovora);
score.setText("Score: " + brojacTacnihOdgovora);
}
else{
brojacVremena.cancel();
Intent i = new Intent(getApplicationContext(), Rezultat.class);
i.putExtra("noviRezultat", brojacTacnihOdgovora);
startActivity(i);
String brojacTacnihOdgovoraString = String.valueOf(brojacTacnihOdgovora);
mHandler.postDelayed(mLaunchTaskFinish,4000);
//SwarmLeaderboard.submitScore(6863, brojacTacnihOdgovora);
HeyzapLib.submitScore(this, brojacTacnihOdgovoraString, "Osvojili ste " + brojacTacnihOdgovoraString + " poena!", "1T3");
}
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
I tried placing this in my code, but it didn't work:
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
Also tried this, it didn't work:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
The issue us that the activity is stopped but the background threads you've created are left running. So you need to override onStop and cancel any background threads.
Something like:
#Override public void onStop() {
super.onStop();
brojacVremena.cancel();
}
Intent a = new Intent(this,"another activity class to go to");
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)|Intent.FLAG_ACTIVITY_NO_HISTORY);//leaves no history of the activity and clears the backstack.
startActivity(a);
finish();
Also have a look at this link http://developer.android.com/training/basics/activity-lifecycle/index.html.
To learn about activity back stack http://developer.android.com/guide/components/tasks-and-back-stack.html. The combination of the link above should give you an insight of what you want to do to solve your problem

Can not display text certain millisecond when mp3/aac play over 1 minute

I create App like-karaoke. But , When my app playing mp3/aac over 1 minute. These text i created is not display. However setText(); under 1 minute is display normally. How can i fix that. I must send teacher tomorrow. Code's be simple. Thank you very much.
public class Okkaraoke extends Activity implements MediaPlayerControl,OnClickListener {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
Handler mHandler = new Handler();
public static TextView subtitles2,subtitles21;
#SuppressLint("HandlerLeak")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.myapp2);
subtitles2 = (TextView) findViewById(R.id.subs2);
subtitles21 = (TextView) findViewById(R.id.subs21);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this)
mMediaController.setMediaPlayer(Okekaraoke.this);
mMediaController.setAnchorView(findViewById(R.id.AudioView2));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Next button clicked
Intent intent = new Intent(Okkarake.this, Show1.class);
startActivity(intent);
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
// Previous button clicked
Intent intent = new Intent(Okkaraoke.this, Main.class);
startActivity(intent);
}
});
try {
mMediaPlayer.setDataSource(this, Uri
.parse("android.resource://com.app.suadmon/raw/sorry"));
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final int currentPos = mMediaPlayer.getCurrentPosition();
if (mMediaPlayer.getCurrentPosition() < 28715) {
subtitles2.setText("Let's start");
subtitles21.setText("...................");
}else if(mMediaPlayer.getCurrentPosition()< 33134) {
subtitles2.setText("Oh my god");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition() < 39811) {
subtitles2.setText("function is green");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 44294) {
subtitles2.setText("Working..");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 50940) {
subtitles2.setText("Normally");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 55387) {
subtitles2.setText("Text can show normally");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()< 103807) {
subtitles2.setText("Working");
subtitles21.setText("Text Displaying");
}else if(mMediaPlayer.getCurrentPosition()<108173) {
subtitles2.setText("Text is not show up from here !");
subtitles21.setText("Text's not Display");
} else if(mMediaPlayer.getCurrentPosition()< 112646) {
subtitles2.setText("All text from here can't show");
subtitles21.setText("Text's not Display");
} else if(mMediaPlayer.getCurrentPosition()< 119555) {
subtitles2.setText("TextView din't show up");
subtitles21.setText("Text's not Display");
} else if (mMediaPlayer.getCurrentPosition()< 130356) {
subtitles2.setText("..................");
subtitles21.setText("Text's not Display");
} else if (mMediaPlayer.getCurrentPosition()< 138812) {
subtitles2.setText("************");
subtitles21.setText("Text's not Display");
} else if (mMediaPlayer.getCurrentPosition()< 147369) {
subtitles2.setText("Text's not Display");
subtitles21.setText("*************");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
// mMediaPlayer.reset();
mMediaPlayer.start();
}
});
}
});
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Intent newAc = new Intent(Okkaraoke.this, Show.class);
startActivity(newAc);
}
});
}
I have music 03.45 minute. In handleMassege().
I try final int/long sPos = mMediaPlayer.getCurrentPosition(); too. But, it's not work. setText is same as code above. Thank you very much.

Categories