How to pass intent to another intent - java

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.

Related

How to use If condition in Button intent call?

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.

how to get intent when alertbox close?

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.

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

Can't make button invisible from another activity

First, I click on Go to level one button in MainActivity to go to the LevelOne Activity from MainActivity, then I am going back to MainActivity and now here I need Go to level one button to be INVISIBLE.
I tried to accomplish this via SharedPreferences, but couldn't make it.
The code I posted below is working just fine, it just doesn't make my Go to level one button invisible when I go back to MainActivity.
I've done this so far:
MainActivity.java:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLevelOne:
Intent i = new Intent(this, LevelOne.class);
startActivityForResult(i, 1);
break;
case R.id.bLevelTwo:
break;
case R.id.bLevelThree:
break;
case R.id.bLevelFour:
break;
case R.id.bLevelFive:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String result = data.getStringExtra("result");
if (result == "milos") {
level1.setVisibility(View.INVISIBLE);
}
}
}
}
LevelOne.java:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.bMenu:
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "milos");
setResult(RESULT_OK, returnIntent);
finish();
break;
case R.id.bNextLevel:
break;
}
}
you have a problem over here.
if (result == "milos") {
level1.setVisibility(View.INVISIBLE);
}
it should rather be
if (result.equalsIgnoreCase("milos") {
level1.setVisibility(View.INVISIBLE);
}

How to receive multiple values using an intent

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

Categories