Sending data without having to start a new Activity - java

So basically my question is just explained in the title. How can I send data between activities without having to start that activity which receive the data. Here's my code: This is the main activity sending the data :
public class MainActivity extends Activity {
private EditText mainedit1;
private TextView maintext1;
private Button mainadd1;
private Button maindone1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
maindone1=(Button) findViewById(R.id.maindone);
mainedit1=(EditText)findViewById(R.id.mainedit1);
maintext1=(TextView)findViewById(R.id.maintext1);
mainadd1=(Button)findViewById(R.id.mainadd);
mainadd1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test1= mainedit1.getText().toString();
Intent intent = new Intent(MainActivity.this,test.class);
intent.putExtra("word",test1);
startActivity(intent);
}
});
And this is the activity receiving the data :
public class test extends Activity {
TextView testtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fortest);
testtext=(TextView)findViewById(R.id.testtext);
Intent intent = getIntent();
String Word = intent.getStringExtra("word");
testtext.setText(Word);
}
So what I did in here is to send the data but also starting the activity, and this is not what I want to share. Please show me how do I fix my code?

It seems you're just looking to save a string for later use. In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);

You can use sharedprefrence of android following code you can implement
In your MainActivity, just do the following to save the string:
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();
Then when you're ready to retrieve it in your test activity, just do so like this:
String Word = getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
testtext.setText(Word);
OR
Sending data without having to start a new Acitivity, by create static variable
ex.
public class First_Activity extends Activity {
public static String USER_FORMATED_NUMBER = null;
USER_FORMATED_NUMBER="Data you want to pass";
}
public class Second_Activity extends Activity {
String data=First_Activity.USER_FORMATED_NUMBER;
}

Related

TextEdit values are passed to another activity but when revisiting next activity values are lost in Android Studio using JAVA

So I've made two textedits. When you click "submit" I want to transfer it to another activity as TextView. I've managed to do this, but only problem is that, when I go to another activity and revisit this activity, those textviews that I've changed it with "submit" button are lost. It just says "null". Can some one help me to fix it. So it can just stay there and not lose it's data. Here's my java 1Activity code:
public class TwoTeam extends AppCompatActivity {
EditText first_name, second_name;
String name_first, name_second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two_team);
first_name = findViewById(R.id.first_name);
second_name = findViewById(R.id.second_name);
}
public void submit_button(View view) {
Intent intent = new Intent(TwoTeam.this, Begin.class);{
name_first = first_name.getText().toString();
name_second = second_name.getText().toString();
intent.putExtra("name1", name_first);
intent.putExtra("name2", name_second);
startActivity(intent);
finish();
}
}
}
And this is 2Activity code:
public class Begin extends AppCompatActivity {
private TextView first_name, second_name;
String name_first, name_second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin);
first_name = findViewById(R.id.name_first);
second_name = findViewById(R.id.name_second);
name_first = getIntent().getExtras().getString("name1");
first_name.setText(name_first);
name_second = getIntent().getExtras().getString("name2");
second_name.setText(name_second);
}
Why do you call finish() method after startActivity? If you use this method this class will be killed after Begin class started so you lose information on the TwoTeam class.

Pass a string from first activity to last activity but running another activity before starting last activity

I'm very new in Android, if the question is repeated please avoid and send the link.
There are three activities A, B and C. Activity A gets a username which I want to get displayed in activity C, but I want to run Activity B first and then run Activity C. The problem using intent is that I have to run C first. If singleton, bundle, or parcelable is the solution can you please provide the code?
Activity A
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText nameText = findViewById(R.id.nameText);
nameText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String name = nameText.getText().toString();
return true;
}
});
}
Activity B
public class qPage2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_q_page2);
android.os.SystemClock.sleep(500);
}
}
Activity C
public class lastPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last_page);
}
}
It's easy than you thought. For example if you want to send a Tasif string from A to C via B.
In activity A
Intent intent = new Intent(A.this, B.class);
intent.putExtra("username", "Tasif");
startActivity(intent);
In activity B
Intent intent = new Intent(B.this, C.class);
intent.putExtras(getIntent()); // Add this line, it will copy all data in intent which starts activity B (including `username`).
startActivity(intent);
In activity C
String username = getIntent().getStringExtra("username");
Declare the String inside Activity "A" as public static and store the string in it from Activity "A" .
eg: Activity A.java
public static String first = "hello";
Then in Activity "C" call it like
Actiivity C.java
String last = A.first;
There are many options for this :
You can use intent as you mentioned
You can make a static Class and declare a static variable with type string
and access it in the C activity .
Code For first option :
For adding value to intent
Intent n = new Intent(FirstActivity.class,SecondActivity.class);
n.putExtra("name" , name);
n.startActivity();
For retrieving it :
Intent intent = getIntent();
String name = intent.getStringExtra("name");
2.Create a static class member and acess it
class static StaticClass{
static name = " ";
}
Update this variable in the first activity and retrive it in last activity
You can store that string in SharedPreferences and can access that string anywhere in your project. If you are not familiar with SharedPreferences read the documentation from this SharedPrefernces Link
A simple and clean approach is to use SharedPreferences data storage option. It is used to save a small collection of data like Key-Value pair.
Save the username in SharedPreferences as below in Activity A:
SharedPreferences sharedPref = getSharedPreferences(
getString("MyKeyPairFileName"), Context.MODE_PRIVATE);
sharedPref.edit().putString("userKey", "Your username").apply;
Read the value from any Activity(B or C or D or...Z) as below:
SharedPreferences sharedPref = getSharedPreferences(
getString("MyKeyPairFileName"), Context.MODE_PRIVATE);
String username = sharedPref.getString("userKey", null);
/*null is the default value, if value for the key is not available*/);
Be careful when using getSharedPreferences vs getPreferences from Activity. You can read more on SharedPreferences here

Android Studio cant process questionmark in String when using equals Method?

Currently I try to learn about creating an android app and work through a Tutorial on it using android studio.
So far, I've created two activites.
The Main activity features a Plain Text Field and a Button. The other activity displays the input of the Plain Text Field when pressing the Button.
The Tutorial ends here.
For fun purpose, I want to change it to the second activity displaying certain text on one special input. Now the line to determine if input is equal to certain String looks like this:
String result = message.equals("foo?") ? "bar" : "wrong";
As long as I leave the Questionmark at the end of "foo?", it sets result to "wrong", although I intend it to be bar.
(With message being the content of the Plain Text Field from the Main Activity)
MCVE Attempt
Main Activity
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Go Button */
public void sendMessage(View view)
{
Intent intent = new Intent(this,DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString(); //User puts in "foo?"
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}}
Second Activity (Showing the result)
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = findViewById(R.id.textView3);
String result = message.equals("foo?") ? "Bar" : "wrong"; //result is set to "wrong"
textView.setText(result);
//But "Bar" expected
}}
Changing userinput to foo instead of foo? and removing the questionmark in .equals("foo?") (to .equals("foo")) produces correct output. Hope thats enough

Sending value from onpostexecute

I am using AsyncTask to perform Background task, After completing my task, I want to set the resultant string from onPostExecute method to another activity's constructor and from there I want to set that string to TextView. when I print log inside the constructor it's printing the string, but when i set the same string on textview, it gives empty string.(the string set on textview is empty, so it simply prints nothing.)
My AsyncTask Code :
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("Answer1",s);
new Answer(s);
}
My Answer Activity, in which I am setting the string via constructor and setting value of this string on textview, but this string is empty.
public class Answer extends AppCompatActivity {
TextView textView;
String str;
// Dont Delete this
Answer(){
}
// Here, Log will print right string, but not on textview
Answer(String str){
this.str = str;
Log.d("Answer2",this.str);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
textView = findViewById(R.id.SetSteps);
// The String set here is empty, can you please elaborate???
textView.setText(str);
}
}
You should never instantiate an Activity youself. The correct way is to pass the desired data througn an intent to the new activity:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Intent intent = new Intent(CurrentActivity.this, Answer.class);
intent.putExtra("MY_DATA", s);
startActivity(intent);
}
Then in your Answer activity you can receive the value:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_answer);
textView = findViewById(R.id.SetSteps);
String result = getIntent().getExtras().getString("MY_DATA","");
textView.setText(result);
}
1 - Add a Context variable to your AsyncTask
Context context = getApplicationContext();
2 - in onPostExecute, create a new intent, add your string to the intent and start the activity :
Intent intent = new Intent(context, Answer.class);
intent.putExtra("Answer1",s);
context.startActivity(intent);
3- in your Answer activity, you can get the string from the intent like below:
Intent intent = getIntent();
String answer = intent.getStringExtra("Answer1");
if(answer !=null){
// do what you want
}
PS: Please please, remove constructors from your Activity, it is not recommended

How call method from second activitty and return value

I have two activity, first on activity "LoginActivity",and second activity "student_ activity".
Please till me how call method "call" from second activity and return value bool to first activity for know user if id and password correct or not correct.
First activity get id and password from "edittext" then send id and password to method in second activity for sure from data from server.
code first activity is :
public class LoginActivity extends Activity{
EditText EdtId;
EditText EdtPassword;
Button btn1;
SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
EdtId=(EditText)findViewById(R.id.IdStudent);
EdtPassword=(EditText)findViewById(R.id.PasswordStudent);
btn1=(Button)findViewById(R.id.btnLogin);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createLoginSession(Integer.parseInt(EdtId.getText().toString()),EdtPassword.getText().toString());
//here call second activity for sure from data
Intent intent = new Intent(LoginActivity.this,tofi.android.Student_Activity.class);
startActivity(intent);
finish();
startActivity(new Intent(LoginActivity.this,com.jcxavier.widget.test.BadgeButtonTestActivity.class));
}
});
}
//this method store data in SharedPreferences for get this data in second activity
public void createLoginSession(int id, String password){
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("id", id);
editor.putString("password", password);
editor.commit();
}
}
code second activity is:
public class Student_Activity {
SharedPreferences prefs = this.getSharedPreferences(this.getApplicationContext().getPackageName(), Context.MODE_PRIVATE);
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.program_student);
NewsLoader call = new NewsLoader();
call.execute(this, true);
}
private Context context;
private boolean pullFromServer = false;
class NewsLoader extends AsyncTask<Object, Void, List<student>> {
private Context context;
private boolean pullFromServer = false;
protected List<student> doInBackground(Object... params) {
context = (Context) params[0];
pullFromServer = (Boolean) params[1];
dataSource.open();
if (pullFromServer) {
//get attribute from SharedPreferences
int id = prefs.getInt("id", 24);
String password = prefs.getString("password","wce");
// studentHandler class for sure password content method call for send to server and //return value if correct or not correct and return value type bool.
bool s;
s = StudentHandler.getInstance().call(context,id,password);
}
}
}
1. Call startActivityForResult() (documentation) and override onActivityResult() (documentation) in the first activity.
2. In the second activity perform whatever validation you need to do (this could also be done in the first activity by passing the data via an Intent) and call setResult(int resultCode, Intent data) (documentation) and then finish(); from the second activity.
If using startActivityForResult() is not feasible for your situation, then you can simply use setResult() and startActivity(), pass any data you need via an Intent, and validate it in onActivityResult().
I just skimmed over this, but here's an example of it in action.

Categories

Resources