Logic flow for android game - java

Hi I'm new to android game development and I'd like to ask you guys regarding the correct logic flow for this android game of mine. So here's my game. It's a pretty simple game which user has to choose the correct color. The game has 3 stages. In each stage, it has 10 questions. In each question, it has a 30 seconds timer. with a question and choices, of course it needs to be randomized. If the user chooses the correct color, it will proceed to the next question. But if the user chooses the wrong color, he/she has only 3 trials to choose, if he/she reaches the 3rd trial, Game is OVER and display a TRY AGAIN button.
Here's a piece of code that I tried:
// I created a custom countdown timer c/o Say
counter = new MyCount(30000,1000);
counter.start();
// Call for correct object
getCorrectObject();
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.pause:
if(mLastResourceId == R.drawable.pause){
pause.setImageResource(R.drawable.resume);
mLastResourceId = R.drawable.resume;
counter.cancel();
} else if (mLastResourceId == R.drawable.resume) {
pause.setImageResource(R.drawable.pause);
mLastResourceId = R.drawable.pause;
counter = new MyCount(s1,1000);
counter.start();
}
break;
}
public class MyCount extends CountDownTimer
{
public MyCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
}
TextView tx = (TextView) findViewById(R.id.timer);
#Override
public void onTick(long millisUntilFinished)
{
s1 = millisUntilFinished;
tx.setText("" + millisUntilFinished / 1000);
}
}
What also I'm considering is, if the user chooses the correct answer without the timer has ended, what should I put in onTick method to force the timer to end? And one of the tricky part that I face is the randomization of choices or the objects.
here is also what I've tried so far:
private void getCorrectObject() {
// TODO Auto-generated method stub
List<Integer> objects = new ArrayList<Integer>();
objects.add(1);
objects.add(2);
objects.add(3);
objects.add(4);
objects.add(5);
objects.add(6);
objects.add(7);
Collections.shuffle(objects);
int correctObject = objects.get(0);
Log.d("test", String.valueOf(correctObject));
switch(correctObject)
{
case 1:
bObjectCorrect.setImageResource(R.drawable.tree1);
bObjectCorrect.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_1.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 2:
bObject1.setImageResource(R.drawable.tree1);
bObject1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_1.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 3:
bObject2.setImageResource(R.drawable.tree1);
bObject2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_1.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 4:
bObject3.setImageResource(R.drawable.tree1);
bObject3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_1.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 5:
bObject4.setImageResource(R.drawable.tree1);
bObject4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_1.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 6:
bObject5.setImageResource(R.drawable.tree1);
bObject5.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_1.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 7:
bObject6.setImageResource(R.drawable.tree1);
bObject6.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_1.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
}
}
UPDATED: and another thing is, I'm confused where to put my while loop in here for 3 trials.
// I will put 3 trials logic here
while(trial <= 3){
trial++;
switch(correctObject)
{
case 1:
bObjectCorrect.setImageResource(R.drawable.stage1_1_object1);
bObjectCorrect.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 2:
bObject1.setImageResource(R.drawable.stage1_1_object1);
bObject1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 3:
bObject2.setImageResource(R.drawable.stage1_1_object1);
bObject2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 4:
bObject3.setImageResource(R.drawable.stage1_1_object1);
bObject3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 5:
bObject4.setImageResource(R.drawable.stage1_1_object1);
bObject4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 6:
bObject5.setImageResource(R.drawable.stage1_1_object1);
bObject5.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 7:
bObject6.setImageResource(R.drawable.stage1_1_object1);
bObject6.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 8:
bObject7.setImageResource(R.drawable.stage1_1_object1);
bObject7.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 9:
bObject8.setImageResource(R.drawable.stage1_1_object1);
bObject8.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
} // Last of switch statement
if(trial == 3){
new AlertDialog.Builder(this)
.setTitle("Game Over")
.setMessage("Sorry you reached your 3rd trial")
.setPositiveButton("Try Again?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_2.this, Stage1_1.class);
startActivity(i);
}
})
.setNegativeButton("Back to Menu", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_2.this, ShapingColors.class);
startActivity(i);
}
})
.show();
}
} // Last of while loop
I'd really love to hear your suggestions. Any help from you is truly appreciated. Thanks in advance!

You don't need to put anything in onTick to handle this case. After you've called cancel() (which you do in your click handler), onTick() won't be called again.

Related

How to reduce this below java code?

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.

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);
}
}

Android game 3 trials for user

Hello it's my first time to develop android color game. However I'd like to put 3 trials in each question. I'm a bit confused how or where to put my while loop in my code. Please have a look on what I have tried so far:
int trial = 0;
private void getCorrectObject() {
List<Integer> objects = new ArrayList<Integer>();
objects.add(1);
objects.add(2);
objects.add(3);
objects.add(4);
objects.add(5);
objects.add(6);
objects.add(7);
objects.add(8);
objects.add(9);
Collections.shuffle(objects);
int correctObject = objects.get(0);
Log.d("test", String.valueOf(correctObject));
while(trial <=3){
trial++;
switch(correctObject)
{
case 1:
bObjectCorrect.setImageResource(R.drawable.stage1_1_object1);
bObjectCorrect.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 2:
bObject1.setImageResource(R.drawable.stage1_1_object1);
bObject1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 3:
bObject2.setImageResource(R.drawable.stage1_1_object1);
bObject2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 4:
bObject3.setImageResource(R.drawable.stage1_1_object1);
bObject3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 5:
bObject4.setImageResource(R.drawable.stage1_1_object1);
bObject4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 6:
bObject5.setImageResource(R.drawable.stage1_1_object1);
bObject5.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 7:
bObject6.setImageResource(R.drawable.stage1_1_object1);
bObject6.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 8:
bObject7.setImageResource(R.drawable.stage1_1_object1);
bObject7.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 9:
bObject8.setImageResource(R.drawable.stage1_1_object1);
bObject8.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
} // Last of switch statement
if(trial == 3){
new AlertDialog.Builder(this)
.setTitle("Game Over")
.setMessage("Sorry you reached your 3rd trial")
.setPositiveButton("Try Again?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_2.this, Stage1_1.class);
startActivity(i);
}
})
.setNegativeButton("Back to Menu", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_2.this, ShapingColors.class);
startActivity(i);
}
})
.show();
}
} // end of while loop
I really like to finish this thing so I can continue with the game. Any help is truly appreciated. Thanks in advance.
I added a new method called guessedWrong()
private void guessedWrong(){
trial++;
if(trial == 3){
new AlertDialog.Builder(this)
.setTitle("Game Over")
.setMessage("Sorry you reached your 3rd trial")
.setPositiveButton("Try Again?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_1.this, Stage1_1.class);
startActivity(i);
}
})
.setNegativeButton("Back to Menu", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_1.this, ShapingColors.class);
startActivity(i);
}
})
.show();
}
}
The reason you're confused is that you can't use a loop for this task. When using the Java Android framework, each of your callback functions (for example, an onClick listener, or your Activity's onResume) has to run and finish within one frame of the application. Only after the function returns does your app update the screen. This means that if you're doing something like responding to a series of clicks, you can't do that in a loop. You have to handle each click in a separate call to the callback. for and while loops are appropriate if you want to iterate over a list of items to decide what should happen right now (for example, if you're adding items to a ListView), but you can't iterate over things that happen at different times (such as the user's guesses).
You have to think about your Activity like a state machine. Make trial a member variable (field) of the Activity, which starts out at 0. You might have a function guessedWrong() which increments trial, and goes to the "game over" screen if it's greater than 2. The onClick listener for the wrong answers will call this function. When moving to a new question, reset trial to 0.
You also need to make sure the number of trials (which state you're in) is preserved if your Activity is restarted. The lesson Recreating an Activity in the Android Developers' Training offered by Google shows you how to do this.

How to pass intent to another intent

hey guys im trying to create a quiz, but im having trouble in the intent,after the user will clicked the button, it will automatically intent to another activity.. how can i do that?
please help guys...thanks in advance..
this is the code:
if(btn1.isClickable())
{
img1.setVisibility(View.VISIBLE);
img1.setImageResource(R.drawable.check);
img2.setVisibility(View.INVISIBLE);
img2.setImageResource(R.drawable.wrong);
img3.setVisibility(View.INVISIBLE);
img3.setImageResource(R.drawable.wrong);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Scorecount++;
Intent i = getIntent();
startActivity(i);
Scorecount = i.getIntExtra("score",0);
}
});
}
else if (btn2.isClickable())
{
img2.setVisibility(View.VISIBLE);
img2.setImageResource(R.drawable.wrong);
img1.setVisibility(View.INVISIBLE);
img1.setImageResource(R.drawable.wrong);
img3.setVisibility(View.INVISIBLE);
img3.setImageResource(R.drawable.wrong);
}
else if (btn3.isClickable())
{
img3.setVisibility(View.VISIBLE);
img3.setImageResource(R.drawable.wrong);
img2.setVisibility(View.INVISIBLE);
img2.setImageResource(R.drawable.wrong);
img1.setVisibility(View.INVISIBLE);
img1.setImageResource(R.drawable.wrong);
}
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = getIntent();
startActivity(i);
Scorecount = i.getIntExtra("score",0);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = getIntent();
startActivity(i);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = getIntent();
startActivity(i);
}
});
}
}
first activity
Intent i= new Intent(CurrentActivity.this,
NextActivity.class);
i.putExtra("quiz", array[0]);
i.putExtra("pass_value","Pass value");
startActivity(i);
second activity
String getvalue= getIntent().getSerializableExtra("pass_value").toString();
I'm not sure that I fully understand what you want, but you can add one intent to another one because intent implements parceable.You can do:
intent.putExtra("INTENT_KEY", someOtherIntent);
and then:
intent = getIntent();
Intent someOtherIntent = (Intent)intent.getParcelableExtra("INTENT_KEY");
Does it help?
P.S. Your code is very strange... (I mean wrong and senseless sometimes)
In order to pass the parameters you create new intent and put a parameter map:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);
In order to get the parameters values you must call the get[type]Extra() on the same intent:
Intent myIntent= getIntent(); // gets the previously created intent
String firstKeyName = intent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String firstKeyName = intent.getStringExtra("firstKeyName"); // will return "SecondKeyValue"
If your parameters are ints you would use getIntExtra() instead etc.
Now you can use your parameters like you normally would.

Dialog Box disapears without being clicked

public void onClick(View v) {
if(a){
Intent i = new Intent();
if(type.equals("x")){
showErrorAlert("string");
i = new Intent(Activity1.this, Activity2.class);
i.putExtra("label", var);
i.putExtra("label1", var2);
startActivity(i);
}
else if(type.equals("y")){
i = new Intent(Activity1.this, Activity3.class);
i.putExtra("label2", var3);
}
//startActivity(i);
}
else startActivity(new Intent(Activity1.this, Activity4.class));
}
});
private void showErrorAlert(String errorMsg){
AlertDialog errorDialog = new AlertDialog.Builder(this).create();
errorDialog.setTitle("title");
errorDialog.setMessage(errorMsg);
errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
errorDialog.show();
}
So what happens is the error alert shows, but it will immediately close and the next activity will appear. I want the activity to not start until after "Okay" is selected.
Try this
public void onClick(View v) {
if(a){
Intent i = new Intent();
if(type.equals("x")){
showErrorAlert("string");
}
else if(type.equals("y")){
i = new Intent(Activity1.this, Activity3.class);
i.putExtra("label2", var3);
}
//startActivity(i);
}
else startActivity(new Intent(Activity1.this, Activity4.class));
}
});
private void showErrorAlert(String errorMsg){
AlertDialog errorDialog = new AlertDialog.Builder(this).create();
errorDialog.setTitle("title");
errorDialog.setMessage(errorMsg);
errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("label", var);
i.putExtra("label1", var2);
startActivity(i);
}
});
errorDialog.show();
}
Move your startActivity(i); to inside if (or) else (or) both blocks depending on where you need.
Place startActivity(i); inside the onClick method in your dialog like this:
private void showErrorAlert(String errorMsg){
AlertDialog errorDialog = new AlertDialog.Builder(this).create();
errorDialog.setTitle("title");
errorDialog.setMessage(errorMsg);
errorDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(i);
}
});
errorDialog.show();
}

Categories