I have created two activities:
Play
MorpionAI
decide and checkedplayer are both some integers.
How can I make my app so that when the button is clicked the app selects and calls one of the intents based on following:
if(decide==checkedplayer){
public void MorpionAI_Acitivity(View view) {
Clean();
deleteplayer();
Intent play = new Intent(this, MorpionAI.class);
startActivity(play);
}}
else{
public void Play_Activity(View view) {
Clean();
deleteplayer();
Intent play = new Intent(this, Play.class);
startActivity(play);
}}
I tried to do this using following code:
morpionbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (decide==checkedplayer){
Clean();
deleteplayer();
Intent play = new Intent(view.getContext(), Play.class);
startActivity(play);
}
else{
Clean();
deleteplayer();
Intent play = new Intent(view.getContext(), MorpionAI.class);
startActivity(play);
}
}
});
But it did not worked.
In your activity , defined a Context class field :
private Context mContext;
in the onCreate() function of this activity , initialize the field :
mContext = this;
then
morpionbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (decide == checkedplayer){
Clean();
deleteplayer();
Intent play = new Intent(mContext, Play.class);
mContext.startActivity(play);
}
else {
Clean();
deleteplayer();
Intent play = new Intent(mContext, MorpionAI.class);
mContext.startActivity(play);
}
}
});
Hope this helps.
Related
In my app, there is a login activity first and a home activity. After logging in using volley and passing parameters to home activity in an intent, I'm able to start a foreground service that keeps the app running in background with notifications and getting back to home activity by clicking on the notification with the help of pending intent.
Now, I'm searching for how to open the app from main menu and accessing directly home activity with the pending intent of the foreground service. Maybe should I pass the parameters of the pending intent to the login activity and check them to redirect to home activity, but i'am stuck with this and don't understand.
Here is the login activity Page :
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.signIn);
// Login On Button Click
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();}
});
// THIS IS THE SOLUTION THAT I THOUGHT ABOUT : if the intent is not null open HomeActivity
Intent startinIntent = getIntent();
if (startinIntent.getStringExtra("userLogged") != null && !startinIntent.getStringExtra("userLogged").isEmpty()) {
String userLogged = startinIntent.getStringExtra("userLogged");
Intent startAgain = new Intent(this, HomeActivity.class);
tackBackWork.putExtra("userLogged", userLogged);
startActivity(startAgain);
Log.d("this is the ilue", userLogged);
}
}
private void login(){
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject object = new JSONObject();
try {
//input your API parameters
object.put("u",username.getText());
object.put("p",password.getText());
} catch (JSONException e) {
e.printStackTrace();
}
// Enter the correct url for your api service site
String url = getResources().getString(R.string.loginUrl);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
String msg = response.getString("msg");
if(msg.contains("true")){
Intent loggedIn = new Intent(LoginActivity.this, HomeActivity.class);
loggedIn.putExtra("userLogged", response.toString());
startActivity(loggedIn);
finish();
}else{
Toast.makeText(getApplicationContext(), "Identifiants Incorrectes", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e){
Toast.makeText(getApplicationContext(), "erreur - 200 ", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Volley on error listener", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
Here is the Home activity
public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
String userLogged = getIntent().getStringExtra("userLogged");
}
#Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
public void onResume(){
super.onResume();
Intent serviceIntent = new Intent(this, ForegroundServiceNoPopup.class);
stopService(serviceIntent);
}
#Override
protected void onStop() {
super.onStop();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
#Override
protected void onPause() {
super.onPause();
Intent serviceIntent = new Intent(this, ForegroundService.class);
Intent intent = getIntent();
String userLogged = intent.getStringExtra("userLogged");
serviceIntent.putExtra("userLogged", userLogged);
startService(serviceIntent);
}
}
Here is foreground Service Page :
public class ForegroundService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
String userLogged = intent.getStringExtra("userLogged");
Intent backToHomeActivity = new Intent(this, HomeActivity.class);
backToHomeActivity.putExtra("userLogged", userLogged);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, backToHomeActivity, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Example Service")
// .setLargeIcon()
// .setColor()
.setContentIntent(pendingIntent)
.setContentText(input)
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I'm new to all of this. please help me.
The solution is to use SharedPreferences.
public class LoginActivity extends AppCompatActivity {
Button login;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.loginBtn);
sp = getSharedPreferences("login",MODE_PRIVATE);
if(sp.getBoolean("logged",false)){
goToMainActivity();
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToMainActivity();
sp.edit().putBoolean("logged",true).apply();
}
});
}
public void goToMainActivity(){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
See the Tutorial below
https://medium.com/#prakharsrivastava_219/keep-the-user-logged-in-android-app-5fb6ce29ed65
I got the first-page working but got a youtube tutorial for the second but can't seem to get it working the way I want it to.the pages are done differently.
This is the working page
private void setSingleEvent(GridLayout mainGrid) {
//Loop all child item of Main Grid
for (int i = 0; i < mainGrid.getChildCount(); i++) {
//You can see , all child item is CardView , so we just cast object to CardView
CardView cardView = (CardView) mainGrid.getChildAt(i);
final int finalI = i;
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (finalI == 0) // open page 1
{
Intent intent = new Intent (MainActivity.this, StarterVapes.class);
startActivity(intent);
}
else if (finalI == 1) // open page 2
{
Intent intent = new Intent (MainActivity.this, UpgradeVapes.class);
startActivity(intent);
}
This is the nonworking page
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
viewHolder.imgView.setImageResource(imagesList.get(i));
viewHolder.txtTitle.setText(titleList.get(i));
final int finalI = i;
viewHolder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (finalI == 0) // open page 1
{
Intent intent = new Intent (context, AboutUS.class);
context.startActivity(intent);
}
else if (finalI == 1) // open page 2
{
Intent intent = new Intent (context.this, AboutUS.class);
context.startActivity(intent);
}
// Intent intent = new Intent(context, DetailActivity.class);
// intent.putExtra("title", titleList.get(i));
// context.startActivity(intent);
}
});
I want it to were you click on the first tile it goes to a page, you click on the second tile it goes to a different page and so on.
Got it working
Heading
````
if (finalI == 0) // open page 1
{
Intent intent = new Intent (context, AboutUS.class);
intent.putExtra("title", titleList.get(i));
context.startActivity(intent);
}
````
What I am doing is sending Intent to MainActivity from Listview the listview item I am displaying in alertbox.
holder.txtStore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String value = holder.txtStore.getText().toString();
Intent myIntent = new Intent(view.getContext(),MainActivity.class);
myIntent.putExtra("restaurant_name", value);
try {
context.startActivity(myIntent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
Toast.makeText(context, "yourActivity is not founded", Toast.LENGTH_SHORT).show();
}
}
});
In MainActivity right now I am using button to start getIntent but I don't want to use button I just want to start getIntent function when alertbox disappear or ya when MainActivity start I try to use onResume or onRestart. But not work for me.
This is my code to call getIntent using button:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String restaurant_name = intent.getStringExtra("restaurant_name");
Toast.makeText(MainActivity.this, restaurant_name, Toast.LENGTH_LONG).show();
if(restaurant_name != null ) {
if (restaurant_name.equals("Romys")) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(26.89209, 75.82759), 15.0f));
mMap.addMarker(new MarkerOptions()
.position(new LatLng(26.89553, 75.82842))
.title("ROMYS"))
.showInfoWindow();
}
}else {
Toast.makeText(MainActivity.this,"It was not", Toast.LENGTH_LONG).show();
}
}
});
Use onNewIntent to update MainActivity. Kind of like this:
#Override
public void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
String restaurant_name = intent.getStringExtra("restaurant_name");
Toast.makeText(MainActivity.this, restaurant_name, Toast.LENGTH_LONG).show();
}
If you are displaying the alertbox from the MainActivity, consider adding flags to your intent to maintain the activity stack.
I have my main activity using the startActivityForResult method which calls an activity that i need to return two string values from. I have it working to return one, but even with all the tutorials and other questions on here i have read i cant seem to get it to return the two values. Below is my code.
here is where i start the second activity:
Button button = (Button) findViewById(R.id.add);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(addM, 1);
}
});
Here is the activity it starts, i need to return the text that is in the titleField(which works now) and the yearField
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.setData(Uri.parse(titleField.getText().toString()));
setResult(RESULT_OK, data);
//data.setData(Uri.parse(yearField.getText().toString()));
//setResult(RESULT_OK, data);
finish();
}
});
}
}
Here is the method in my main class that receives results
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getData().toString();
//tempYear = data.getStringExtra("movieYear");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
The code that is commented out was one attempt at making it receive multiple values, although they failed. Any help with this situation would be great. Thanks!
You should use something like:
Intent returnIntent = new Intent();
returnIntent.putExtra("title",titleField.getText().toString());
returnIntent.putExtra("year",yearField.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
And on your main activity, onActivityResult:
tempTitle = data.getStringExtra("title");
tempYear = data.getStringExtra("year");
use data.putExtra("keys", data); instead of data.setData(.....)
and get data like;
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
String value = extras.getString("keyName");
}
You should be able be put extras on your intent and get that data through an associated tag. This is how I'm doing it from an Activity's onCreate.
Intent mIntent = new Intent(this, MainActivity.class);
mIntent.putExtra("your_tag", "the string you want to get");
startActivity(mIntent);
finish();
Then in the activity you want that data (the MainActivity or whatever you're calling it)....
Intent intent = getIntent();
String value = intent.getExtras().getString("your_tag");
It may also be worth noting that you can Override the onNewIntent in your MainActivity to handle new Intents coming in, mine currently looks like...
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
}
Try this
public class AddMovie extends Activity {
String movieTitle, movieYear;
EditText titleField, yearField;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_movie);
titleField = (EditText) findViewById(R.id.titleField);
yearField = (EditText) findViewById(R.id.yearField);
save = (Button) findViewById(R.id.saveMovie);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra("title_field", titleField.getText().toString);
data.putExtra("year_field", yearField.getText().toString);
setResult(RESULT_OK, data);
finish();
}
});
}
And this
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == request_Code)
{
if(resultCode == RESULT_OK)
{
tempTitle = data.getStringExtra("title_field");
tempYear = data.getStringExtra("year_field");
Toast.makeText(this, tempTitle, Toast.LENGTH_SHORT).show();
dbAddMovie(tempTitle, tempYear);
}
}
}
You can use a putExtra method on your Intent:
data.putExtra("title", movieTitle);
data.putExtra("year", movieYear);
Then in the Activity that opens, you can get this data as follows:
String title, year;
Intent data = getIntent();
if (data != null) {
title = data.getExtras().getString("title");
year = data.getExtras().getString("year");
}
You can create a new intent and then add your two variables
Intent i = new Intent(getApplicationContext(), asd8.as.hwapp.timemonday.class);
i.putExtra("username",username);
i.putExtra("password", password);
startActivity(i);
And then retrieving the information in your new activity as so;
public void getInformation(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
username = extras.getString("username");
password = extras.getString("password");
}
}
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.