Android Studio getIntent from one activity but not from other - android

I have a question that whatever I search i can't find the answer for.
So I have 3 Activities:StartActivity, LoginActivity and MainActivity
In StartActivity I have 2 buttons:
-Login - it sends me to LoginActivity
-Continue as guest - it sends me to MainActivity
In Login activity i have:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(loginUser(false)) {
String username = String.valueOf(userName);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("USERNAME", username);
startActivity(intent);
finish();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
});
and in MainActivity I have :
private String username = getIntent().getStringExtra("USERNAME");
But when I try to login as guest the String username has nothing to get and gives me error. So how can I make String username getIntent only when I open the activity from LoginActivity and don't do anything when I open it from ContinueAsGuest button in StartActivity?

button in StartActivity only take you as guest right?if so code will look like this
guestBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String username = String.valueOf(userName);
Intent intent = new Intent(StartActivity.this, MainActivity.class);
intent.putExtra("USERNAME", username);
startActivity(intent);
finish();
}
} catch (SQLException e) {
e.printStackTrace();
}
});

Related

Role Based Auto Login in Android Studio

I'm creating a app in which 5 different users are available FOUR are WORKERS and ONE is CLIENT. All users are able to login in app using their email and password, but i want that 4 users from those 5 are redirect to one activity and remaining one user redirect to another different activity, Which is working fine, but at time time of auto-login i want the same thing will happen but whenever i logged in as WORKER and then clear the app from memory, and at the time of auto-login the CLIENT is logged in every time.
At the time of registration every users have to select their designation and the client designation will remain EMPTY every time now trying to let users auto-login based on their designation Which i used as USER TYPE.
I want at time auto-login FOUR USERS(WORKERS) redirect to different one activity and the ONE user which is CLIENT redirect to another different activity. What i have to user for this, which method is better for me?
I Have user Session To Save Current Login User-Type, and it is working great.
Here is my session code:-
private SharedPreferences prefs;
private static AppSession session;
public static AppSession getInstance(Context cntx) {
if (session == null)
session = new AppSession(cntx);
return session;
}
public AppSession(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setHasLoging(boolean value) {
prefs.edit().putBoolean("hasLoging", value).commit();
}
public void setUserHasLoging(boolean value){
prefs.edit().putBoolean("UserHasLoging", value).commit();
}
public boolean getHasLoging() {
return prefs.getBoolean("hasLoging", false);
}
public boolean getUserHasLoging(){
return prefs.getBoolean("UserHasLoging", false);
}
public void clear() {
prefs.edit().clear().commit();
}
Login Activity Code:-
userDatabaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(RegisteredUserID);
userDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userType = dataSnapshot.child("designation").getValue().toString();
if (userType.equals("CA")){
mAppSession.setHasLoging(true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else if (userType.equals("CLIENT")){
mAppSession.setUserHasLoging(true);
Intent intent = new Intent(LoginActivity.this, DashBoardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else if (userType.equals("ADVOCATE")){
mAppSession.setHasLoging(true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else if (userType.equals("CMA")){
mAppSession.setHasLoging(true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else if (userType.equals("CS")){
mAppSession.setHasLoging(true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else {
SweetToast.info(LoginActivity.this, "Email is not verified. Please verify first");
mAuth.signOut();
}
}
Here Splash Screen I used as Launcher Activity to check the condition which user is logged in.
AppSession mSession;
private FirebaseAuth mAuth;
private DatabaseReference mDatabaseReference;
#Override
protected void onStart() {
super.onStart();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
if (user == null){
Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else if (user != null){
mDatabaseReference.child(user.getUid()).child("online").setValue(ServerValue.TIMESTAMP);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mSession = AppSession.getInstance(this);
rightAction();
}
private void rightAction(){
if (mSession.getHasLoging()) {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else if (mSession.getUserHasLoging()){
Intent intent1 = new Intent(SplashActivity.this, DashBoardActivity.class);
startActivity(intent1);
finish();
}

Logout. back button pressed, again logged in

From this page I am logging out. It is logging out properly but when back button is pressed it gets logged in again. i have given a proper intent function but yet it is not acting as per my commands. Please advice me a solution for this problem.
WELCOME PAGE CODE:-
public class Welcome extends AppCompatActivity {
Button __btnlogout;
Button btn1;
Button btn2;
DatagramSocketThread mDatagramSocketThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
__btnlogout = (Button)findViewById(R.id.btnLogout);
__btnlogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", false);
editor.commit();
Intent intent = new Intent(Welcome.this,
login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
btn1 = (Button)findViewById(R.id.btn11);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("MainActivity", "22");
mDatagramSocketThread = new DatagramSocketThread();
mDatagramSocketThread.start();
Intent intent = VpnService.prepare(getApplicationContext());
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Log.e("MainActivity", "23");
Intent intent = new Intent(Welcome.this, MyClass.class);
Log.e("MainActivity", "24");
startService(intent);
}
btn2 = (Button)findViewById(R.id.btn22);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("MainActivity", "25");
Intent intent;
intent = new Intent(Welcome.this, MyClass.class);
Log.e("MainActivity", "26");
stopService(intent);
}
});
}
}
And i want to be in Login page when logged out and even after pressing back button.
LOGIN PAGE CODE:-
public class login extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Button __btnLogin;
EditText __txtEmail,__txtPass;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.d("login","13");
openHelper = new DatabaseHelper(this);
db=openHelper.getReadableDatabase();
__btnLogin = (Button)findViewById(R.id.btnLogins);
__txtEmail = (EditText)findViewById(R.id.txtEmails);
__txtPass = (EditText)findViewById(R.id.txtPasss);
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", true);
editor.commit();
Log.d("login","14");
__btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = __txtEmail.getText().toString();
String pass = __txtPass.getText().toString();
if (pass == "" || email == "") {
Toast.makeText(getApplicationContext(),"No Entry", Toast.LENGTH_LONG).show();
}
Log.d("login","15");
cursor = db.rawQuery("SELECT * FROM "+ DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.COL_5 + " =? AND " + DatabaseHelper.COL_4 + " =? ", new String[]{email,pass});
Log.d("login","16");
if(cursor!=null) {
Log.d("login","17");
if (cursor.getCount()>0) {
Log.d("login","18");
//cursor.moveToNext();
Log.d("login","19");
startActivity(new Intent(login.this, Welcome.class));
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
}
else {
Log.d("login","20");
Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
Log.d("login","21");
}
}
}
});
}
}
THANK YOU
You can override onBackPressed on login page, then when users click on back, you can handle it your way:
#Override
public void onBackPressed()
{
//super.onBackPressed(); // disable this
}
You need to finish() all previous Activity when logging out. Try the code below You can emit flag Intent.FLAG_ACTIVITY_NEW_TASK.
Intent intent = new Intent(login.this, Welcome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
About your question you said i want to be in Login page when logged out and even after pressing back button.
Thats not the proper behavior for any app . The app should close when you back press from last Activity on Stack . So do not disable onBackPressed() in Login Activity.
I think you shouldn't clear the shared preferences properly or should check shared preferences value before rendering welcome activity. Then you should add finish(); after startActivity()
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", false);
editor.commit();
Intent intent = new Intent(Welcome.this,login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
To prevent this accidental login you should check sharedPreferences value is set before. Back button disabling is not a good option.
You have to finish Welcome Activity when you are logging, so user will not be able to come back this activity again except when the log in again. You have to add finish(); on logout
Intent intent = new Intent(Welcome.this,login.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
and in you login page you can also handle what you want to do when you press back button, either exit from app or do something else, by override onBackPressed(); method.
#Override
public void onBackPressed()
{
super.onBackPressed();
}
Changed isLogin Flag after success login ,
Update your Login Activity Code,
public class login extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
Button __btnLogin;
EditText __txtEmail,__txtPass;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Log.d("login","13");
openHelper = new DatabaseHelper(this);
db=openHelper.getReadableDatabase();
__btnLogin = (Button)findViewById(R.id.btnLogins);
__txtEmail = (EditText)findViewById(R.id.txtEmails);
__txtPass = (EditText)findViewById(R.id.txtPasss);
Log.d("login","14");
__btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = __txtEmail.getText().toString();
String pass = __txtPass.getText().toString();
if (pass == "" || email == "") {
Toast.makeText(getApplicationContext(),"No Entry", Toast.LENGTH_LONG).show();
}
Log.d("login","15");
cursor = db.rawQuery("SELECT * FROM "+ DatabaseHelper.TABLE_NAME + " WHERE " + DatabaseHelper.COL_5 + " =? AND " + DatabaseHelper.COL_4 + " =? ", new String[]{email,pass});
Log.d("login","16");
if(cursor!=null) {
Log.d("login","17");
if (cursor.getCount()>0) {
Log.d("login","18");
//cursor.moveToNext();
Log.d("login","19");
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLogin", true);
editor.commit();
startActivity(new Intent(login.this, Welcome.class));
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG).show();
}
else {
Log.d("login","20");
Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
Log.d("login","21");
}
}
}
});
}
}
Navigate into login activity if click logout button and listen for back pressed on login activity
Intent ...
finish();
onBackPressed();
Solution is
#Override
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
}

TextInputLayout issue at Login time

I have TextInputLayout in login, when i click on login button if username is empty then show error same as with password when password is empty then show error but if username is empty and password is non empty at that time error is not shown so how can i solve this problem? My Code is like below!!!
#Override
public void onClick(View v) {
Intent mIntent;
switch (v.getId()) {
case R.id.txtSignIn:
hideKeyboard(mActivity, v);
if (etUserName.getText().toString().equals("")) {
etUserName.requestFocus();
etUserName.setCursorVisible(true);
tilPassword.setErrorEnabled(false);
tilUserName.setErrorEnabled(true);
tilUserName.setError(getString(R.string.username_required));
} else if (etPassword.getText().toString().equals("")) {
etPassword.requestFocus();
etPassword.setCursorVisible(true);
tilUserName.setErrorEnabled(false);
tilPassword.setErrorEnabled(true);
tilPassword.setError(getString(R.string.password_required));
} else {
tilUserName.setErrorEnabled(false);
tilPassword.setErrorEnabled(false);
showToast(mActivity, getString(R.string.successfully_login), 0);
mIntent = new Intent(SignIn.this, DashBoard.class);
startActivity(mIntent);
}
break;
case R.id.txtSignUp:
mIntent = new Intent(mActivity, SignUp.class);
startActivity(mIntent);
break;
case R.id.txtForgotPassword:
mIntent = new Intent(mActivity, ForgotPassword.class);
startActivity(mIntent);
break;
}
try {
} catch (Exception e) {
LOGD(getClass().getSimpleName(), e.getMessage());
LOGE(getClass().getSimpleName(), e.getMessage());
}
}
Use isEmpty() method since null and "" <- this is not equal you cannot derive if the EditText is empty or not .
Something like this below will pop an error on the screen is either password or username field is empty
if (etUserName.isEmpty() && etPassword.isEmpty()) {
<your code if nothing is entered>
}
For additional help check this out :
Check if EditText is empty.

Android Intent with NullPointerException

There are many many questions about starting new Intent from another Intent but i'm unable to find solutions of mine. In my main Activity i started an Activity this way
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
and trying to get extra String value this way
public class DownloadManagerSettings extends Activity {
private Button dmOk;
private Bundle extra;
private String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dm_settings);
extra = getIntent().getExtras();
dmOk = (Button) findViewById(R.id.dm_settings_ok);
final Bundle strExtra = extra;
dmOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
try {
Intent intent = new Intent(DownloadManagerSettings.this, Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
But in my LogCat shows following error
08-28 14:19:33.777: E/AndroidRuntime(17837): java.lang.NullPointerException08-28 14:19:33.777: E/AndroidRuntime(17837): at com.downloadmanager.settings.DownloadManagerSettings$1.onClick(DownloadManagerSettings.java:101)
Here 101 Line is
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
UPDATE
new error
08-28 14:55:11.237: E/AndroidRuntime(24623): Caused by: java.lang.NullPointerException 08-28 14:55:11.237: E/AndroidRuntime(24623): at com.downloadmanager.settings.DownloadManagerSettings.onCreate(DownloadManagerSettings.java:66)
66 Line is
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
NEW UPDATE1
Now
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
Another Activity
className = getIntent().getStringExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY");
final String newClass = className;
Log.d("DM_AAAAAAAA", className);
dmOk.setOnClickListener(new View.OnClickListener() {
Find in LogCat
08-28 15:09:14.670: E/AndroidRuntime(27291): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.addon.downloadmanager/com.downloadmanager.settings.DownloadManagerSettings}: java.lang.NullPointerException: println needs a message
Thanks in advance
try this:
public class DownloadManagerSettings extends Activity {
private Button dmOk;
private Bundle extra;
private String className;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dm_settings);
extra = getIntent().getExtras();
dmOk = (Button) findViewById(R.id.dm_settings_ok);
final Bundle strExtra = extra;
className = strExtra.getString("DM_SETTINGS_ACTIVITY");
dmOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method
try {
Intent intent = new Intent(DownloadManagerSettings.this, Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
Get the String data in onCreate first and then use it in onClick.
Update :
seems you'll have to add your package name as the prefix, see this. After that, use getStringExtra/getCharSequenceExtra to get the string data.(note we don't use Bundle any more). This should work.
update 1:
The following code work on my device.
Intent newIntent = new Intent(getApplicationContext().getPackageName());
newIntent.setClass(this, SecondActivity.class);
newIntent.putExtra(getApplicationContext().getPackageName()+".abc", "test");
startActivity(newIntent);
and in the other activity:
String data = getIntent().getStringExtra(getIntent().getAction()+".abc");
From the javadoc of Intent.putExtra(String,String) :
The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
So try this :
intent.putExtra(getPackageManager().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
and later:
className = strExtra.getString(getPackageManager().getPackageName()+".DM_SETTINGS_ACTIVITY");
Use getStringExtra() instead of getExtra()
or you can also do in from other side during intenet creation
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
Bundle extras = new Bundle();
extras.putString("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
Try this way,hope this will help you to solve your problem.
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
intent.putExtra("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
className = className = getIntent().getStringExtra("DM_SETTINGS_ACTIVITY");
OR
Intent intent = new Intent(MainActivity.this, DownloadManagerSettings.class);
Bundle bundle = new Bundle();
bundle.putString("DM_SETTINGS_ACTIVITY", "MainActivity");
startActivity(intent);
className = className = getIntent().getBundleExtra().getString("DM_SETTINGS_ACTIVITY");
The problem in your code is here,
intent.putExtra(getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY", "MainActivity");
Just replace this line with
intent.putExtra("MainActivity",getApplicationContext().getPackageName()+".DM_SETTINGS_ACTIVITY");
Check this code :
1. **MainActivity.java**
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("MY TEXT", getApplicationContext().getPackageName()+".TestActivity");
startActivity(intent);
2. **MainActivity2.java**
Intent i = getIntent();
final String className = i.getStringExtra("MY TEXT");
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity2.this,Class.forName(className));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
This is worked on my device.

How to send Intent Extra?

I am a beginner of Android. I want to pass the result from FirstActivity to the SecondActivity as below. How to remove results in intent extra? Or any way to pass the result to SecondActivity and show on the TextView?
(I have make a mistake and replace, my main question is how to delete the result, because i want to set another new result in it.)
FirstActivity.java
public class FirstActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//code...
try {
myDbHelper.createDatabase();
}
catch (IOException ioe) {
Log.d("Error","Error while createing Database");
ioe.printStackTrace();
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}
catch(SQLException sqle){
Log.d("Error","Error while Opening Database");
sqle.printStackTrace();
throw sqle;
}
send.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
//...code
//checking for slection
results = queryData(table, type);
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
}
public String queryData(String table, String type){
//...
//do somthing to get result
return result;
}
}
SecondActivity.java
public class SecondActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_item);
TextView tv;
tv = (TextView)findViewById(R.id.tv);
Bundle extras=getIntent().getExtras();
String value1=extras.getString("results");
tv.setText("Result\n" + value1);
}
}
You can do in 2 ways:
1. You can use startActivityForResult(), onActivityResult() from the Activity A, to pass the data on to Activity B, then after some computation, passing the result back to Activity A.
2. Now if you want to just send some data from Activity A to Activity B, and then display it in TextView, then use putExtra() and getExtras()...
Sending from Activity A to B:
Intent i = new Intent(Activity_A.this, Activity_B.class);
i.putExtra("name",Name);
startActivity(i);
Receiving the value on Activity B:
Intent i = getIntent();
String n = i.getExtras().getString("name");
change startActivityForResult(intent, 0) to startActivity(intent);
like this
private void showResult() {
results = queryData(table, type);
Intent intent = new Intent(firstActivity.this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
}
Make new intent and pass
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent);
You were done your way of method that pass the data to next Activity is right. But, you made a mistake with starting the activity. Starting an Activity in your code should be like below -
private void showResult() {
//...code
//checking for slection
results = queryData(table, type);
Intent intent = new Intent(this,SecondActivity.class);
intent.putExtra("results", results);
startActivity(intent); // This is the way to start a new Activity which is in seperate class
}
And, just have a look at below -
How do I pass data between Activities in Android application?
Passing data between activities in Android

Categories

Resources