In my first Activity a "+" button opens the second activity. On the second activity I want to click a button to add to a counter and pass that increment number to my first activity. Right now I am able to add to the counter from the first activity only.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button addBtn;
int quantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBtn = (Button) findViewById(R.id.addBtn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openAddStarActivity();
}
});
}
public void openAddStarActivity() {
Intent intent = new Intent(this, AddStarActivity.class);
startActivity(intent);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
TextView textView = (TextView)
findViewById(R.id.quantity_text_view);
textView.setText(data.getStringExtra("textViewText"));
}
}
}
public void increment(View view) {
if (quantity == 100) {
return;
}
quantity = quantity + 1;
displayQuantity(quantity);
}
private void displayQuantity(int numberOfStars) {
TextView quantityTextView = (TextView)
findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + numberOfStars);
}
}
AddStarActivity.java
public class AddStarActivity extends AppCompatActivity {
int quantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_star);
}
public void increment(View view) {
if (quantity == 100) {
return;
}
quantity = quantity + 1;
displayQuantity(quantity);
}
private void displayQuantity(int numberOfStars) {
TextView quantityTextView = (TextView)
findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + numberOfStars);
}
#Override
public void onBackPressed(){
TextView textView = (TextView) findViewById(R.id.quantity_text_view);
Intent i = new Intent(this,MainActivity.class);
setResult(RESULT_OK, i);
i.putExtra("textViewText", textView.getText().toString());
startActivityForResult(i,0);
}
}
I added a Textview on the second activity so that I could simply pass that textview data to the textview data field on my first activity
Make quantity public static in MainActivity and increment the same static variable in AddStarActivity. So your function will be
public void increment(View view) {
if (MainActivity.quantity == 100) {
return;
}
MainActivity.quantity++;
displayQuantity(MainActivity.quantity);
}
You can do this thing with tow way which is bellow
Broadcast Receiver
Register Broadcast in your first activity and fire action from your second activity with data like below example
In your first activity
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null && intent.getAction().equals("SendCounter")) {
counter=intent.getIntExtra("value",0);
}
}
};
registerReceiver(receiver,new IntentFilter("value"));
In your second activity
Intent intent=new Intent("SendCounter");
intent.putExtra("value",counterValue);
sendBroadcast(intent);
Static Member
Define one variable in your activity and define as static so you can access that particular member as static.
In your first activity
public static int counter;
Now in your second activity, you can add value in your first activity variable like bellow
ActivityFirst.counter=30 //New value
Your MainActivity should not be calling startActivity, but instead should call startActivityForResult, when starting AddStarActivity. Then in AddStarActivity, you would call setResult when you are incrementing. And finally, remove onBackPressed from AddStarActivity. When the user clicks the back button to go from your AddStarActivity back to MainActivity (meaning the system will finish the AddStarActivity), then MainActivity#onActivityResult will be invoked.
Related
I am learning Android Studio and I have a question: I wanna say something in chinese and there compare the word/phrase I said with the one that was displayed at the screen. And if these two words are equals - make text green. else - red. But it always red after I press the mic button.
Will appriciate any help
public class SpeakingActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SPEECH_INPUT = 1000;
TextView mTextView;
TextView input;
ImageButton mImageButton;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speakingfromhome);
button = findViewById(R.id.nextSpeaking);
mTextView = findViewById(R.id.output);
mImageButton = findViewById(R.id.image);
input = findViewById(R.id.input);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
changeQuestions();
mTextView.setTextColor(Color.BLACK);
}
});
mImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
checkIfCorrect();
}
});
}
private void checkIfCorrect() {
if (input.toString().equals(mTextView.toString()))
mTextView.setTextColor(Color.GREEN);
else
mTextView.setTextColor(Color.RED);
}
private void changeQuestions() {
input.setText("基辅");
}
private void speak() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.CHINA.toString());
try {
startActivityForResult(intent, REQUEST_CODE_SPEECH_INPUT);
} catch (Exception ex) {
Toast.makeText(this, "" + ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mTextView.setText(result.get(0));
}
break;
}
}
}
}
The function checkIfCorrect() is the problem
Change it to:
input.toString() -> input.getText()
mTextView.toString() -> mTextView.getText()
Like:
input.getText().equals(mTextView.getText())
with getText() get the text of the TextView, doint input.toString() convert the object TextView to String
your checkIfCorrect function must look like:
private void checkIfCorrect() {
if (input.getText().equals(mTextView.getText()))
mTextView.setTextColor(Color.GREEN);
else
mTextView.setTextColor(Color.RED);
}
A better way:
private void checkIfCorrect() {
mTextView.setTextColor((input.getText().equals(mTextView.getText())) ? Color.GREEN : Color.RED )
}
I'm using two activities, MainActivity & SubActivity.
MainActivity.class
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sub = new Intent(this, SubActivity.class);
sub.putExtra("name", "a");
startActivity(sub);
}
}
}
}
SubActivity
public class SubActivity extends AppCompatActivity {
EditText text;
#Override
protected void onCreate() {
...
text.setText(getIntent().getStringExtra("name"));
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
In this case, if I change the text in EditText in SubActivity, I want to send changed text data to MainActivity when back button pressed in SubActivity(It means SubActivity onDestroy()). I don't want to make the second MainActivity like this in SubActivity.
#Override
public void onBackPressed() {
Intent intent = new Intent (this, MainActivity.class);
intent.putExtra("name", text.getText().toString());
startActivity(intent);
}
Is there any way to send text data when SubActivity removed from the activity stack?
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sub = new Intent(this, SubActivity.class);
sub.putExtra("name", "a");
startActivityForResult(sub , 2);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("name");
textView1.setText(message);
}
}
}
And
#Override
public void onBackPressed() {
Intent intent = new Intent (this, MainActivity.class);
intent.putExtra("name", text.getText().toString());
setResult(2,intent);
}
You need to use startActivityForResult() if you expect to have a return from the started activity.
After that, you'll also need to implement onActivityResult() method on the start activity to actually read the returned data.
Use startActivityForResult instead of startActivity
MainActivity :
public class MainActivity extends AppCompatActivity {
Button button;
String name= "a";
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sub = new Intent(this, SubActivity.class);
sub.putExtra("name", name);
startActivityForResult(sub,100);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 100) {
String name = data.getStringExtra("name);
text.setText(name);
}
}
}
}
SubActivity:
public class SubActivity extends AppCompatActivity {
EditText text;
#Override
protected void onCreate() {
...
text.setText(getIntent().getStringExtra("name"));
}
#Override
public void onBackPressed() {
Intent resultIntent = new Intent();
resultIntent.putExtra("name", "your_editext_value");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
You can use SharedPreference for storing value and update it or use it anywhere instead of using Intent
like In MainActivity
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate() {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Editor edit=sp.edit();
edit.putString("name","a");
edit.commit();
Intent sub = new Intent(this, SubActivity.class);
startActivity(sub);
}
}
} }
and In SubActivity
public class SubActivity extends AppCompatActivity {
EditText text;
#Override
protected void onCreate() {
...
text.setText(sp.getString("name",""));
text.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Editor edit=sp.edit();
edit.putString("name",s.toString);
edit.commit();
} });
}
#Override
public void onBackPressed() {
super.onBackPressed();
}}
To use value from SharedPreference
sp.getString("name","");
For using SharedPreference look at this https://developer.android.com/training/data-storage/shared-preferences#java
Guys I have 2 activity when I clicked button in main starting new activity(message.java) and I'm trying to get data from my message activity
to mainActivity .In message activity, I have edittext and when clicked button go back mainactivity and show that info in textview. This code working but problem is when I clicked button in mainActivity
it's first delete textview's text and then message activity begining . This is not what I want and also , it's taking info from message activity that's OK but in mainActivity I must clicked again mainActivtiy button to show in textview. Any suggest?
This is what I want
This picture shows problem
Parent -> MainActivity
Child ->message
public class MainActivity extends AppCompatActivity {
private RelativeLayout rLayout;
private Button bt,bt2;
private TextView tv;
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rLayout=(RelativeLayout) findViewById(R.id.relativeLayout);
tv=(TextView)findViewById(R.id.textView2);
bt2=(Button)findViewById(R.id.button4);
final Intent i=new Intent(getBaseContext(),MessageActivity.class);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(i, 1);
tv.setText(s);
}
});
}//end of onCreate
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
s=data.getStringExtra("info");
}
}
}
}//end of mainActivity
here message.java
public class MessageActivity extends Activity {
private Button bt;
private TextView tv;
private EditText et;
private String s;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.message);
bt=(Button)findViewById(R.id.button);
et=(EditText)findViewById(R.id.editText);
tv=(TextView)findViewById(R.id.textView);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
s=et.getText().toString();
data.putExtra("info", s);
setResult(RESULT_OK, data);
finish();
}
});
}
}
Im not sure if I understood your question correctly, but if you would like to show your text in MainActivity when you come back from MessageActivity, you should just be setting the text in onActivityResult() method, not in the clickListener.
So your code will look like this:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
s=data.getStringExtra("info");
tv.setText(s);
}
}
}
Why don't you try to set the textView text in the activity result function. Is the better place to do it. Think than when you start a child Activity, the flow of parent activity stops. And when you finish child activity, flow goes directly to onActivityResult function. Try it. Regards.
In your MainActivity you need to set the text on your textview once you receive it. Problem is that startActivityForResult is asynchronous call. Once call to this method is gone it will start other activity but your onClick() method will not stop here. Its a normal listener that calls onActivityResult when your activity is destroyed.
public class MainActivity extends AppCompatActivity {
private RelativeLayout rLayout;
private Button bt,bt2;
private TextView tv;
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rLayout=(RelativeLayout) findViewById(R.id.relativeLayout);
tv=(TextView)findViewById(R.id.textView2);
bt2=(Button)findViewById(R.id.button4);
final Intent i=new Intent(getBaseContext(),MessageActivity.class);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(i, 1);
}
});
}//end of onCreate
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
s=data.getStringExtra("info");
tv.setText(s);
}
}
}
}
Accept and upvote if it works.
i have following problem:
I've made a simple android app that adds 1 to an integer every 1000 ms using a handler, and then display this integer.
The problem is that when i start another activity the same thing happens, which would be fine, if that was intended. The mentioned function is not called in the new activity and yet it seems to be. Please look over my code and show me where it went wrong..
MainActivity:
public class MainActivity extends ActionBarActivity {
protected TextView text;
protected int position;
private Handler handler = new Handler();
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
position=0;
SetButtonCLickListener();
counter();
}
protected void SetButtonCLickListener() {
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SwitchActivity();
}
});
}
private void counter() {
handler.removeCallbacks(count);
handler.postDelayed(count, 1000);
}
private Runnable count = new Runnable() {
public void run() {
i++;
text.setText("Count: " + i);
handler.postDelayed(count, 1000);
}
};
protected void SwitchActivity() {
if (position == 1) {
finish();
} else {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
}
SecondActivity
public class MainActivity2 extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
text = (TextView) findViewById(R.id.text);
SetButtonCLickListener();
position=1;
}
}
MainActivity2 has an onCreate() method. In the onCreate() method, you call super.onCreate(), which triggers the MainActivity implementation of onCreate(). The MainActivity implementation of onCreate() is where you are starting your counter thing, via its call to the counter() method. Hence, when MainActivity2 starts up, its onCreate() calls MainActivity's onCreate(), which calls counter().
My guess is that MainActivity2 should inherit from Activity, not from MainActivity.
I have a program that starts on one activity goes to the next and their is button to click, after a certain amount of time it goes back to the starting page and reports the number of clicks.
Here's my code: clickcount is the first activity
public class ClickCountActivity extends Activity {
/** Called when the activity is first created. */
Button next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next=(Button) findViewById(R.id.NextButton);
//---------------------------------------------------------------
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(ClickCountActivity.this, startClickActivity.class);
i.putExtra("comingFrom", "come");
final int result=1;
startActivityForResult(i,result);
}
});
//---------------------------------------------------------------------------
}
}
public class startClickActivity extends Activity {
/** Called when the activity is first created. */
Button clicker;
int counter ;
Timer timer = new Timer(); // use timer to start a new task
MyTimerTask task = new MyTimerTask();
final long seconds = 3;
Intent p = getIntent();
String answer = p.getStringExtra("comingFrom");
class MyTimerTask extends TimerTask {
public void run()
//override run method
{
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", answer);
setResult(RESULT_OK,x);
startActivity(x);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action);
clicker=(Button) findViewById(R.id.Clicker);
//---------------------------------------------------------------
clicker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++; // counts number of clicks
task.cancel(); // cancels current task
task = new MyTimerTask(); //create new task
timer.schedule(task,seconds*1000L); // start a new timer task in 5seconds (timertask, seconds(long))
// System.out.println(counter);
}
});
}
}
Your code in run method should be this:
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", counter);
setResult(RESULT_OK,x);
finish();
You need to pass the no. of counts i.e. counter in intent and collect it from onActivityResult(int requestCode, int resultCode, Intent data) method of ClickCountActivity class. The value is passed in the data intent and can be queried using int counterValue = data.getIntegerExtra("returnStr", 0);