lab problems for corse - java

hey every one i am sorry but i have to ask this question, it seems like a very easy issue but i just stuck! i have spent the last 2 hours going through the form and android developer resource site and i cant find the problem with my code.
first of all the startActivityForResult() will not send me the text back.
second every time i click on the Implicit Activation button the app crashes.
here is the main activity file:
public class ActivityLoaderActivity extends Activity {
static private final int GET_TEXT_REQUEST_CODE = 1;
static private final String URL = "http://www.google.com";
static private final String TAG = "Lab-Intents";
// For use with app chooser
static private final String CHOOSER_TEXT = "Load " + URL + " with:";
// TextView that displays user-entered text from ExplicitlyLoadedActivity runs
private TextView mUserTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loader_activity);
// Get reference to the textView
mUserTextView = (TextView) findViewById(R.id.textView1);
// Declare and setup Explicit Activation button
Button explicitActivationButton = (Button) findViewById(R.id.explicit_activation_button);
explicitActivationButton.setOnClickListener(new OnClickListener() {
// Call startExplicitActivation() when pressed
#Override
public void onClick(View v) {
startExplicitActivation();
}
});
// Declare and setup Implicit Activation button
Button implicitActivationButton = (Button) findViewById(R.id.implicit_activation_button);
implicitActivationButton.setOnClickListener(new OnClickListener() {
// Call startImplicitActivation() when pressed
#Override
public void onClick(View v) {
startImplicitActivation();
}
});
}
// Start the ExplicitlyLoadedActivity
private void startExplicitActivation() {
Log.i(TAG,"Entered startExplicitActivation()");
// TODO - Create a new intent to launch the ExplicitlyLoadedActivity class
Intent explicitIntent = new Intent (ActivityLoaderActivity.this, ExplicitlyLoadedActivity.class);
// TODO - Start an Activity using that intent and the request code defined above
startActivityForResult(explicitIntent, GET_TEXT_REQUEST_CODE);
}
// Start a Browser Activity to view a web page or its URL
private void startImplicitActivation() {
Log.i(TAG, "Entered startImplicitActivation()");
// TODO - Create a base intent for viewing a URL
// (HINT: second parameter uses Uri.parse())
Intent baseIntent = new Intent (Intent.ACTION_VIEW, Uri.parse(URL));
// TODO - Create a chooser intent, for choosing which Activity
// will carry out the baseIntent
// (HINT: Use the Intent class' createChooser() method)
Intent chooserIntent = null;
chooserIntent.createChooser(baseIntent, CHOOSER_TEXT);
Log.i(TAG,"Chooser Intent Action:" + chooserIntent.getAction());
// TODO - Start the chooser Activity, using the chooser intent
startActivity(chooserIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
// TODO - Process the result only if this method received both a
// RESULT_OK result code and a recognized request code
// If so, update the Textview showing the user-entered text.
if (resultCode == RESULT_OK){
mUserTextView.setText(data.getStringExtra("resulttext"));
}}}
and here is the explicit intent file:
public class ExplicitlyLoadedActivity extends Activity {
static private final String TAG = "Lab-Intents";
private EditText mEditText;
String resulttext="still waiting";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.explicitly_loaded_activity);
// Get a reference to the EditText field
mEditText = (EditText) findViewById(R.id.editText);
// Declare and setup "Enter" button
Button enterButton = (Button) findViewById(R.id.enter_button);
enterButton.setOnClickListener(new OnClickListener() {
// Call enterClicked() when pressed
#Override
public void onClick(View v) {
enterClicked();
}
});
}
// Sets result to send back to calling Activity and finishes
private void enterClicked() {
Log.i(TAG,"Entered enterClicked()");
// TODO - Save user provided input from the EditText field
resulttext= mEditText.getText().toString();
// TODO - Create a new intent and save the input from the EditText field as an extra
Intent returntrip = new Intent ();
returntrip.putExtra("wayback", resulttext);
// TODO - Set Activity's result with result code RESULT_OK
setResult(RESULT_OK, returntrip);
// TODO - Finish the Activity
finish();
}
}
thank you guys so much i know i am a bother!

You are sending an extra data called "wayback" not "resulttext"
returntrip.putExtra("wayback", resulttext);
this will fix your code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "Entered onActivityResult()");
if (resultCode == RESULT_OK){
mUserTextView.setText(data.getStringExtra("wayback"));
}

Well, you won't get the result back correct from your onActivityResult because you are not using the correct key. You look inside for data.getStringExtra("resulttext") but you originally set the key as "wayback". You need to grab with that key.

Related

How i can Do an action in another activity ?android

I have 2 activities ,activity A is having webview and activity B is having button with transparent layout. I want close the activity B and refresh or do something in activity A when I press button from activity B.
I tried shared preferences but that not working without restarting activity A.
Have a look at the docs for Getting a Result from an Activity
Updated to include example
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
// Do something with the contact here (bigger example below)
}
}
}
create a method as refreshmethod in Activity A and call it from Activity B something like this:
ActivityA activitya:
//stuff
activitya = new ActivityA();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activitya.refreshmethod();
}
});
hope it helps.

setText on button from another activity android

I have a problem, I want to click on the list, calling a new activity and rename the button to another name.
I tried several things, nothing worked, can someone please help me?
My class EditarTimes:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
CadastroTimes cad = new CadastroTimes();
CadastroTimes.salvar.setText("Alterar");
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
public class CadastroTimes extends AppCompatActivity {
private Time t;
private timeDatabase db;
private EditText edID;
private EditText edNome;
public Button salvar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_times);
edID = (EditText) findViewById(R.id.edID);
edNome = (EditText) findViewById(R.id.edNome);
db = new timeDatabase(getApplicationContext());
salvar = (Button) findViewById(R.id.btnCadastrar);
salvar.setText("Cadastrar");
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("Alterar");
}
} else {
newString= (String) savedInstanceState.getSerializable("Alterar");
}
//button in CadastroTimes activity to have that String as text
System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
salvar.setText(newString);
}
public void salvarTime(View v) {
t = new Time();
t.setNome(edNome.getText().toString());
if (salvar.getText().equals("Alterar")) {
db.atualizar(t);
exibirMensagem("Time atualizado com sucesso!");
} else {
db.salvar(t);
exibirMensagem("Time cadastrado com sucesso!");
}
Intent intent = new Intent(this, EditarTimes.class);
startActivity(intent);
}
private void limparDados() {
edID.setText("");
edNome.setText("");
edNome.requestFocus();
}
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
public class EditarTimes extends AppCompatActivity {
private Time t;
private List<Time> times;
private timeDatabase db;
private ListView lvTimes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editar_times);
lvTimes = (ListView) findViewById(R.id.lvTimes);
lvTimes.setOnItemClickListener(selecionarTime);
lvTimes.setOnItemLongClickListener(excluirTime);
times = new ArrayList<Time>();
db = new timeDatabase(getApplicationContext());
atualizarLista();
}
private void excluirTime(final int idTime) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Excluir time?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Deseja excluir esse time?")
.setCancelable(false)
.setPositiveButton(getString(R.string.sim),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (db.deletar(idTime)) {
atualizarLista();
exibirMensagem(getString(R.string.msgExclusao));
} else {
exibirMensagem(getString(R.string.msgFalhaExclusao));
}
}
})
.setNegativeButton(getString(R.string.nao),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.create();
builder.show();
atualizarLista();
}
private void atualizarLista() {
times = db.listAll();
if (times != null) {
if (times.size() > 0) {
TimeListAdapter tla = new TimeListAdapter(
getApplicationContext(), times);
lvTimes.setAdapter(tla);
}
}
}
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
t = times.get(pos);
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
String strName = "Alterar";
intent.putExtra("Alterar", strName);
startActivity(intent);
}
};
private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
excluirTime(times.get(pos).getId());
return true;
}
};
private void exibirMensagem(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public void telaCadastrar(View view) {
Intent intent = new Intent(this, CadastroTimes.class);
startActivity(intent);
}
public void botaoSair(View view) {
Intent intent = new Intent(this, TelaInicial.class);
startActivity(intent);
}
}
You can pass the button caption to CadastroTimes with intent as
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("buttontxt","Changed Text");
startActivity(intent);
Then in CadastroTimes.java set the text of the button to the new value that you passed. The code will look like:
button = (Button)findViewById(R.id.button); // This is your reference from the xml. button is my name, you might have your own id given already.
Bundle extras = getIntent().getExtras();
String value = ""; // You can do it in better and cleaner way
if (extras != null) {
value = extras.getString("buttontxt");
}
button.setText(value);
Do remember to do it in onCreate after setContentView
//From Activity
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
intent.putExtra("change_tag", "text to change");
startActivity(intent);
//To Activity
public void onCreate(..){
Button changeButton = (Button)findViewById(R.id.your_button);
// Button to set received text
Intent intent = getIntent();
if(null != intent &&
!TextUtils.isEmpty(intent.getStringExtra("change_tag"))) {
String changeText = intent.getStringExtra("change_tag");
// Extracting sent text from intent
changeButton.setText(changeText);
// Setting received text on Button
}
}
1: Use intent.putExtra() to share a value from one activity another activity, as:
In ActivityOne.class :
startActivity(
Intent(
applicationContext,
ActivityTwo::class.java
).putExtra(
"key",
"value"
)
)
In ActivityTwo.class :
var value = ""
if (intent.hasExtra("key")
value = intent.getStringExtra("key")
2: Modify button text programatically as:
btn_object.text = value
Hope this will help you
For changing the button text:
Use a static method to call from the other activity to directly modify the button caption.
Use an intent functionality, which is preferable.
Use an Interface and implement it, which is used for communicating between activities or fragment in a manner of fire and forget principle.
Now, i got you:
Your EditarTimes activity with listview:
//set setOnItemClickListener
youtListView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent i = new Intent(EditarTimes.this, CadastroTimes.class);
//text which you want to display on the button to CadastroTimes activity
String strName = "hello button";
i.putExtra("STRING_I_NEED", strName);
}
});
In CadastroTimes activity,
under onCreate() method, get the text string as:-
String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
} else {
newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
//button in CadastroTimes activity to have that String as text
yourButton.setText(newString);
Ok, so the first step would be to take the button you want and make it a public static object (and put it at the top of the class).
public static Button button;
Then you can manipulate that using this in another class:
ClassName.button.setText("My Button");
In your case it is
CadastroTimes.salvar.setText("Alterar");
if you want to change value from that do not do not go the activity via intent you can use file to save value to file or you have multiple values the use database and access
the value oncreate to set the value of text....
In my case, I had to send an EditText value from a Dialog styled Activity, which then got retrieved from a Service.. My Example is similar to some of the above answers, which are also viable.
TimerActivity.class
public void buttonClick_timerOK(View view) {
// Identify the (EditText) for reference:
EditText editText_timerValue;
editText_timerValue = (EditText) findViewById(R.id.et_timerValue);
// Required 'if' statement (to avoid NullPointerException):
if (editText_timerValue != null) {
// Continue with Button code..
// Convert value of the (EditText) to a (String)
String string_timerValue;
string_timerValue = editText_timerValue.getText().toString();
// Declare Intent for starting the Service
Intent intent = new Intent(this, TimerService.class);
// Add Intent-Extras as data from (EditText)
intent.putExtra("TIMER_VALUE", string_timerValue);
// Start Service
startService(intent);
// Close current Activity
finish();
} else {
Toast.makeText(TimerActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
And then inside my Service class, I retrieved the value, and use it inside onStartCommand.
TimerService.class
// Retrieve the user-data from (EditText) in TimerActivity
intent.getStringExtra("TIMER_VALUE"); // IS THIS NEEDED, SINCE ITS ASSIGNED TO A STRING BELOW TOO?
// Assign a String value to the (EditText) value you retrieved..
String timerValue;
timerValue = intent.getStringExtra("TIMER_VALUE");
// You can also convert the String to an int, if needed.
// Now you can reference "timerValue" for the value anywhere in the class you choose.
Hopefully my contribution helps!
Happy coding!
Accessing view reference of another Activity is a bad practice. Because there is no guarantee if the reference is still around by the time you access it (considering the null reference risk).
What you need to do is to make your other Activity read values (which you want to display) from a data source (e.g. persistence storage or shared preferences), and the other Activity manipulates these values. So it appears as if it changes the value of another activity, but in reality it takes values from a data source.
Using SharedPreferences:
Note: SharedPreferences saves data in the app if you close it but it will be lost when it has been deleted.
In EditarTimes.java:
private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
t = times.get(pos);
SharedPreferences.Editor editor = getSharedPreferences("DATA", MODE_PRIVATE).edit();
editor.putString("btnText", "Your desired text");
editor.apply();
Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
startActivity(intent);
}
};
In CadastroTimes.java
public Button salvar;
salvar.setText(getSharedPreferences("DATA", MODE_PRIVATE).getString("btnText", ""));
//note that default value should be blank
As far as my thoughts go, I can realize that the problem is not with the code you provided as it seems to be implemented correctly. It is possible that you have saved the activityState somewhere in your actual code and because it is not implemented properly, the savedInstanceState found in the onCreate method is not null but the required information is missing or not correct. That's why newString is getting null and salvar textview is getting blank.
Here, I need to know which one is more useful to you - information from getIntent() or from savedInstanceState? The code you provided insists me to assume that savedInstanceState has got the preference.
If you prefer savedInstanceState, then you may use SharedPreferences like this to get the same value you want:
private SharedPreferences mPrefs;
private String newString;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from preference
mPrefs = getSharedPreferences("MyData", MODE_PRIVATE);
newString = mPrefs.getString("alterarValue", "");
if (newString.equals("")){
// we have not received the value
// move forward to get it from bundle
newString = getIntent().getStringExtra("Alterar");
}
// now show it in salvar
salvar.setText(newString);
}
protected void onPause() {
super.onPause();
// you may save activity state or other info in this way
SharedPreferences.Editor ed = mPrefs.edit();
ed.putString("alterarValue", newString);
ed.commit();
}
Or if you don't need to get it from savedInstanceState, please use it:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
// try to get the value of alterarValue from bundle
String newString = getIntent().getStringExtra("Alterar");
// now show it in salvar
salvar.setText(newString);
}
That's all I know. Hope it will help. If anything goes wrong, please let me know.

In Android Studio, cannot invoke Activity B from Activity A more than once

Further to my previous post, I now want to invoke a child activity from the main activity a number of times. In my real project (as opposed to the noddy test below), when the child activity is invoked, its header displays, "Enter first data set" then invites the user to enter some data. This data is actually stored in a common class rather than being returned to the main activity. Then the child needs to be called again with a new prompt "Enter second data set", and the same thing happens.
What I cannot work out is how to do this. If I include two calls to the child, every time, only the second call appears to happen, the prompt appearing in the child activity being "Enter second data set" every time. This startActivityForResult() method is I believe, designed to be used when you want to call an activity and wait for the result (which you do with an onActivityResult() do you not), but it does not wait.
How on earth do I do this? Sample code follows.
Thank you to anyone who can clearly explain where I'm going wrong and what the right code should be.
MainActivity code extract
#Override
public void onResume(){
super.onResume();
TextView maintop = (TextView)findViewById(R.id.maintop);
maintop.setText(Common.mess1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mainbutton = (Button)findViewById(R.id.mainbutton);
mainbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent1 = new Intent(MainActivity.this,Child.class);
intent1.putExtra("Prompt", "Enter first data set");
startActivityForResult(intent1,1);
onActivityResult(1,1,intent1);
}
});
mainbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent2 = new Intent(MainActivity.this,Child.class);
intent2.putExtra("Prompt", "Enter second data set");
startActivityForResult(intent2,1);
onActivityResult(1,1,intent2);
}
});
}
You can only have one click listener in the button, so when you call set for the 2nd time it replaces the listener.
What you need to do is set the click listener for the enter first data, don't call to onActivityResult(1,1,intent1) that's not how you do it, you need override the method, and in onActivityResult call the 2nd.
Something like this:
static final int FIRST_INTENT = 1;
static final int SECOND_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mainbutton = (Button)findViewById(R.id.mainbutton);
mainbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent1 = new Intent(MainActivity.this,Child.class);
intent1.putExtra("Prompt", "Enter first data set");
startActivityForResult(intent1,FIRST_INTENT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FIRST_INTENT) {
if (resultCode == RESULT_OK) {
Intent intent2 = new Intent(MainActivity.this,Child.class);
intent2.putExtra("Prompt", "Enter second data set");
startActivityForResult(intent2,SECOND_INTENT);
}
}
}
And in your child activity
//DO SOMETHING
....
setResult(RESULT_OK)
finish();
}
For more check
[http://developer.android.com/intl/es/training/basics/intents/result.html]
[http://developer.android.com/intl/es/reference/android/app/Activity.html#setResult%28int%29]

Displaying current user's data to other user

My app is a blood donation app in which first we get the info from users, maintain it into Parse.com database. then displaying that data into 2 different listviews as for donor and acceptor,
Now when the user click on the any one user from the list, that current user's data is sent to the user mentioned in that list with a notification. requested user get the notification with an activity, now this is where is problem is coming, I'm unable to get that data displayed on that activity to the user being requested.
//This is the reciver class that's opening that acitivty to the requested user
private static final String TAG = "Receiver";
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
try {
ParseObject perseonj = new ParseObject(arg1.getExtras().getString(
"com.parse.Data"));
String event_id = ParseUser.getCurrentUser().getObjectId();
Intent eventIntent = new Intent(arg0, ShowPopUp.class);
eventIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
eventIntent.putExtra("id", event_id);
String struser = ParseUser.getCurrentUser().getUsername().toString();
String bg = ParseUser.getCurrentUser().getString("BloodGroup").toString();
Intent i = new Intent();
i.putExtra("idd", struser.toString());
i.putExtra("bg", bg.toString());
arg0.getApplicationContext().startActivity(eventIntent);
System.out.println(event_id);
} catch (android.net.ParseException e) {
Log.d(TAG, "PARSEException: " + e.getMessage());
}
}
}
// This is the acitivty which actually displays the data
public class ShowPopUp extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTitle("COPAN");
setContentView(R.layout.popupdialog);
TextView tv = (TextView) findViewById(R.id.textView1);
final String current = getIntent().getExtras().getString("idd");
tv.setText(current);
TextView vtv = (TextView) findViewById(R.id.textView3);
final String currentt = getIntent().getExtras().getString("bg");
vtv.setText(currentt);
}
try intent.getStringExtra("bg"); you are saving the data in the intent. when you are calling intent.getExtras() you are getting back the Bundle of that intent
final String currentt = getIntent().getString("bg");
Also notice that there is no reason to call toString on a string object...
--- EDIT ----
eventIntent.putExtra("idd", struser.toString());
eventIntent.putExtra("bg", bg.toString());
instead of using new Intent i which you are not setting and passing...

How to reload an activity with previous state saved?

I have a game activity and using an sqlite database I populate some buttons, randomly without repetition, and when the game gets finished I popup an alert dialog with OK button an some info. Now, I need when I press OK, to close that popup and in that game activity reload some other data to my buttons, without repetition. This I need to happen twice. I do this in my other game but that popup does not have OK button, it pops up for 3 seconds and using handler closes and my activity reloads with new data without repetition, and that works like a charm. In this game, only OK button is a difference, and it does not work. And I need that OK button. Two problems I have with this.
I successfuly reload my activity but with repetition, which tells me that my activity loads from scratch.
When the activity loads for the second time, when I press back button I can see previous game activity, which again tells me that I get one activity loaded twice. I only need it once with new data every time.
Also, my counter does not work, cause after second load, I get 3rd, 4th and so on.
Here are my game and popup activity:
public class ToploHladno extends Activity implements View.OnClickListener{
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, bIzlaz, bDalje;
String mButtonText1, mButtonText2, mButtonText3, mButtonText4, mButtonText5, mButtonText6,
mButtonText7, mButtonText8, mButtonText9, mButtonText10, opis, odgovorNormalized;
MediaPlayer buttonClicks, buttonFinal, buttonBack;
public boolean music;
final Context context = this;
Editable ukucanRezultat;
String tacanRezultat, ukucanRezultatVelikaSlova;
int brojPoena;
int counter = 0;
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
addListenerOnButton();
nextQuestion();
}
private void addListenerOnButton() {
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
bIzlaz = (Button) findViewById(R.id.bIzlaz);
bDalje = (Button) findViewById(R.id.bDalje);
}
public void nextQuestion() {
counter++;
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{
mDbHelper.open();
Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
mButtonText1 = c.getString(2);
mButtonText2 = c.getString(3);
mButtonText3 = c.getString(4);
mButtonText4 = c.getString(5);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
if(counter < 3){
b1.setText("30 poena");
b2.setText("25 poena");
b3.setText("22 poena");
b4.setText("20 poena");
}else{
finish();
}
}
finally{
mDbHelper.close();
}
}
Popup:
public class Popup_opis extends Activity implements OnClickListener{
TextView tvOpis;
int brojPoenaPrimljeno;
Button OK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_opis);
initVariables();
}
private void initVariables() {
OK = (Button) findViewById(R.id.bOK);
tvOpis = (TextView) findViewById(R.id.tvOpis);
OK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
Intent intent = new Intent(Popup_opis.this, ToploHladno.class);
//intent.putExtra("myMethod", "nextQuestion"); //I tried also this
startActivity(intent);
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
If I understand you correctly, you are restarting your ToploHladno Activity from your Popup_opis Activity using an Intent. If the ToploHladno Activity hasn't been finished, which I don't think it has been, then no need for Intent. You can call invalidate() on the Views that you want to be repopulated in onResume() after calling setText() on them or whatever changes you need to make to those Views
#Override
public void onResume()
{
// change your Buttons however you need in here then say you have btn1
btn1.invalidate();
}
Your first Activity isn't being finished so you don't need or probably even want to start it with an Intent. You will just return to it after closing your Dialog Activity and onResume() will be called so you can do what you need in there. This will keep you from redrawing the whole Layout by not creating a new instance of your Activity.Let me know if this works for what you need or not
Invalidate
startActivityForResult() example:
Intent intent = new Intent(ToploHladno .this, Popup_opis .class);
intent.putExtra("counter", counter);
startActivityForResult( intent, 0 ); //second param is a request code. You will need this later
then in pop up activity
public class Popup_opis extends Activity implements OnClickListener{
TextView tvOpis;
int brojPoenaPrimljeno;
Button OK;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_opis);
//Get intent
Intent recIntent = getIntent();
counter = recIntent.getIntExtra("counter"); //get counter variable from previous activity
OK.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
counter++;
Intent intent = new Intent(Popup_opis.this, ToploHladno.class);
intent.putExtra("counter", counter); //SEND BACK COUNTER
setResult(RESULT_OK, intent); // send result
finish();
then in your previous activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
// would use REQUEST CODE sent earlier if more than one activity sends back intents here
if (resultCode == RESULT_OK)
{
counter = data.getInteExtra("counter", 0); // get updated counter variable
}
}
More about startActivityForResult in Docs

Categories