Sending value from onpostexecute - java

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

Related

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

How do I add data I have keyed in a EditText box into an array to list in another activity?

Below are the 3 java classes which I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array. But I am quite confused on how the logic must be for the code to send the data keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. I do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java -
https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java -
https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java -
https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
}
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
as mentioned above, the correct way would be to use the startActivityForResult method. Check this.
And how to go about it, Damn easy!
Modifying your code:
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent,123);
}
});
}
}
and in the same activity (MainActivity) listen for the result
Also would recommend you to use the parceler.org lib for sending objects
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_OK && requestCode==123){
// perform your list addition operation here and notify the adapter for change
// the returned data comes in 'data' parameter and would recommend you to use parcels.org lib
// for sending parcelable pojo across activities and fragments.
list.add(Parcels.unwrap(data.getParcelableArrayExtra(YOUR_KEY)));
adapter.notifyDataSetChanged();
}
}
And in your AddActivity, when you add just do this.
public void addStudent() {
// add the 'add' button view to the oncreatemethod
// add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do not restart the activity that opened this activty
// this activity is anyways on top of the MainActivity. Just finish this activty setting the result
// Intent intent = new Intent(AddActivity.this, MainActivity.class);
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
// startActivity(intent);
// How to do that?
Student student = new Student(Fname, FphoneNumber);
Intent intent = new Intent();
intent.putExtra(YOUR_KEY, Parcels.wrap(student));
// you can also do it without the parcels lib
// intent.putExtra("studentName",name.getText().toString() );
// intent.putExtra("phoneNumber",phone.getText().toString());
setResult(123,intent); // set the result code. it should be the same one as the one your listening on in MainAcitivty
// then just finish this activity.
finish();
// this calls the onActivtyResultMethod in MainActivity which furtther does the logic
// students.add(student);
}
});
}
That should work! Cheers!
Use StartActivityForResult for AddActivity and return object from here and use in MainActivity. For example see here
Since you store the data in a file, the add activity should just write the data to the file. Then the main activity should always read the file to refresh the list.
I will suggest using a static class if you don't want to use a Database.
Or if you should use a file is just very simple to write into a file when you add and read from it in the next activity.
Just create a Static class like this.
public static class MyStaticClass{
private static ArrayList <Student> mStudents = new ArrayList<Student>()
public static void addStudent(Student theNewStudent){
mSudents.add(theNewStudent);
}
public static List<Student> getStudents(){
return mStudents;
}
}
or with a file:
public static class MyFileClass{
private static String pathFile = "Your path";
public static void addStudent(Student theNewStudent){
File file = new OutputStreamWriter(new FileOutputStream(pathFile,true)); //the true is to append to the file
file.write(/*parse your student as a string*/);
file.close();
}
public static List<Student> getStudents(){
ArrayList<Student> students = new ArrayList<>()
File file = new File(pathFile);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
//parse your line to a student object
students.add(yourNewStudent);
}
sc.close();
return students;
}
}
Just call the add student and the get students in the proper class as follows.
MyStaticClass.addStudent(student);
or
MyFileClass.addStudent(student);
Hope it helps.
In your onclick listener:
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
Student student = new Student(Fname, FphoneNumber);
MyStaticClass.addStudent(student); // or the FileClass
startActivity(intent);
}
and i cant see where do you retrieve the list. but just use the getStudents of the class.
Intent yourFirstAct= new Intent(firstAct.this,second.class);
yourFirstAct.putExtra("","");
startActivitForResult(yourFirstAct);
in first Activity,
#Override
public void onAcitivityResult(....){
super();
}
in your second activity when you done,
do your stuff whatever you want in second activity. and pass it to mainActivity
Intent yoursecAct= new Intent();
yourSecAct.putExtra("","");
setResult(yourSecAct);
finish();
IF YOU ARE USING IN FRAGMENT
if you do startActivityResult() in fragment means,
your fragment mainActivity must return super() in
public void onAcitivityResult(...){super()}
After getting the details from the student, put the respective details in a bundle and just use intent to go back to the main activity. Then use bundles to extract the data in the main activity.
You can use startActivityForResult for the same. if you haven't found the answer yet then please let me know. I will provide you the code.
Many above answers already defined this thing in a very good way.
This is about communication between Activities. You can use event bus to realize this.
https://github.com/JackZhangqj/EventBus
Then 1. Add event bus dependency to the App's build.grade
compile "de.greenrobot:eventbus:3.0.0
Register and unregister your subscribe in the MainActivity.java
#Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
3.Post event in the AddActivity.java
EventBus.getDefault().post(new Student(name.getText().toString(), phone.getText().toString()));
4.Implement event handling method in MainActivity
//The student is the added student in the AddActivity.java
public void onEventMainThread(Student student) {
}
To kind of expand a little bit on MadScientist's answer, ListView's need adapters in order set the data in it's view. You'll need to define an ArrayAdapter for your list view to communicate with. This will need to go in your MainActivity and will be initialized in the onCreate method. Assuming you want to display both types of information, you'll need to construct your adapter with the built in layout for showing two items via android.R.layout.simple_list_item_2. If you would like to create your own layout, however, you can look up how to do that here.
public class MainActivity extends AppCompatActivity {
Button addStudent;
ArrayAdapter<Student> adapter;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, students);
ListView listView = (ListView) findViewById(R.id.listView);
listView.addAdapter(adapter);
add();
}
Call the startActivityForResult(intent, 123) in your Listener to start the new activity. Then, once you have typed in your data, add your items to the intent and call finish() in your AddActivity. Override the onActivityResult in your MainActivity to pull the items off your intent and add them to your list. Finally, notify the adapter of the changes via adapter.notifyDataSetChanged()

Sending data without having to start a new Activity

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

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.

How do you pass a string from one activity to another? [duplicate]

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 9 years ago.
I'm wondering how to pass and read a string that is in one activity from another activity. I have two activities. I'll call them Activity1 and Activity2. I have a string in Activity1 called course. I want to read that string in Activity2.
I've tried doing this but the string came out empty.
public class Activity2 extends Activity1 {
I've seen people use the Intent function but I couldn't figure out how to use it.
Any suggestions? Thanks!
Pass values using intents.
In your first activity
Intent i= new Intent("com.example.secondActivity");
i.putExtra("key",mystring);
// for explicit intents
// Intent i= new Intent(ActivityName.this,SecondActivity.class);
// parameter 1 is the key
// parameter 2 is the value
// your value
startActivity(i);
In your second activity retrieve it.
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
//get the value based on the key
}
To pass custom objects you can have a look at this link
http://www.technotalkative.com/android-send-object-from-one-activity-to-another-activity/
your first activity, Activity1
public class Activity1 extends Activity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
btn=(Button) findViewById(R.id.payBtn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent=new Intent(Activity1.this,Activity2.class);
intent.putExtra("course", "courseValue");
startActivity(intent);
}
});
}
}
Activity2
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
String course=getIntent().getExtras().getString("course").toString();
Log.d("course",course);
}
}
Hope this will help you.
You're on the right track - you're using an intent to launch the second activity. All you have to do is add intent.putExtra("title", stringObject); where stringObject is the string you want to pass, and title is the name you want to give that object. You use that name to refer the object passed in the second activity as follows:
String s = (String)getIntent().getExtras().getSerializable("title");
From Activity 1 call something like this :
Intent intent= new Intent("path.secondActivity");
intent.putExtra("keyString",sampleString);
startActiivty(intent);
and in activity 2 try something like this :
Bundle values = getIntent().getExtras();
if (values != null) {
String keyString = values.getString("keyString");
}
In your MainActivity
Intent i= new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("key",yourstring);
startActiivty(i);
In your second activity onCreate()
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
}
Try this
public class Activity2 extends Activity1

Categories

Resources