In my app, I am deleting data from my databasehelper class, and I want the Textview in the mainActivity to display the new changed data.So far this is my code.
public void DeleteData(){
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(etID.getText().toString());
if(deletedRows > 0) {
reload.Redraw();
Toast.makeText(MainActivity.this, "Shit should work", Toast.LENGTH_LONG).show();
}
}})
This is in my second activity, where I call the refresh function
public void Redraw() {
displayMsg.postInvalidate();
}
Just in case, my text
public void nexttime() {
Cursor res = myDb.GetFirstTime();
if (res.getCount() == 0) {
displayMsg.setText("No Appointment was found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
StringBuffer nextA = buffer.append("Date :" + res.getString(4) + "\n");
displayMsg.setText(nextA);
}}
Have your main activity update its own TextView in its onResume().
Whenever one activity is running, other activities do not exist. More precisely, they may exist, but you can never depend on it. Never attempt to directly access one activity instance from another.
Related
I am trying to direct the user from the login page to another activity.
trying to get a return value out of the login method => 1 correct username and passwort, 0 wrong details
-cant call the onCLick method, so i cant get any values and cant execute the if function.
If there are other ways to direct the user from the login activity to the other activity let me know! (i just started)
TextView passwort =(TextView) findViewById(R.id.passwort);
MaterialButton anmeldenbtn = (MaterialButton) findViewById(R.id.anmeldenbtn);
//eventlistener
anmeldenbtn.setOnClickListener(new View.OnClickListener() {
#Override
public int onClick(View view) {
if(anmeldename.getText().toString().equals("Test") && passwort.getText().toString().equals("Test")) {
Toast.makeText(MainActivity.this, "ANMELDUNG ERFOLGREICH", Toast.LENGTH_SHORT).show();
return 1;
}
else {
Toast.makeText(MainActivity.this, "nicghsdfs ", Toast.LENGTH_SHORT).show();
return 0;
}//fielse
}
});
//in den taschenrechner
int i = onClick();
if (i == 1) {
public void openRechner() {
Intent intent = new Intent(this, Rechner.class);
startActivity(intent);
}
} ```
The codes are messy at this point since I've been going back and forth so much. Every time user clicks the yes/no button I want the results of counts the button has been clicked to display in another activity. I also want to reset the number of clicks from the second activity as well. All that's needed in the first activity is the question and the yes/no button. Is this possible? Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final String TAG = "SurveyActivity";
private static final String YES_INDEX = "yes votes";
private static final String NO_INDEX = "no votes";
Button mYesButton;
Button mNoButton;
Button mResetButton;
TextView mSurveyQuestion;
private int yesVoteCount = 0;
private int noVoteCount = 0;
private int resetVotes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Use res ID to retrieve inflated objects and assign to variables
mYesButton = findViewById(R.id.yes_button);
mNoButton = findViewById(R.id.no_button);
mResetButton = findViewById(R.id.reset_button);
mSurveyQuestion = findViewById(R.id.survey_question);
mYesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
mNoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addVote();
}
});
// Resetting vote count
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
***Should this supposed to be in the second activity?
}
});
}
private void addVote() {
if (mYesButton.isPressed()) {
yesVoteCount++;
} else if (mNoButton.isPressed()) {
noVoteCount++;
}
}
In your main activity
btnShowResut.setOnClickListener(new View.OnClickListener() {
#Override
// Create intent for going to another activity
Intent intent = new Intent(this, AnotherActivity.class);
// Put counts datas to intent
intent.putExtra("yesCountKey", yesVoteCount);
intent.putExtra("noCountKey", noVoteCount);
// NEW : Go to another activity by calling it instead
// REQUEST_CODE is an integer variable
startActivityForResult(intent, REQUEST_CODE);
}
});
In Another activity, you can retrieve datas in onCreate method like this and send action to clear counts of your main activity.
...
onCreate(...){
...
// Retrieve datas from intent
int yesCount = getIntent().getIntExtra("yesCountKey", 0);
int noCount = getIntent().getIntExtra("noCountKey", 0);
mResetButton.setOnClickListener(new View.OnClickListener() {
#Override
// Send a boolean to main activity for clearing votes
Intent intent = new Intent();
intent.putExtra("resetVotes", true);
setResult(RESULT_OK, intent);
// Close second activity
finish();
}
});
}
Finally in the main activity override this method and clear votes
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == 2000 && resultCode == RESULT_OK){
boolean reset = data.getBooleanExtra("resetVotes", false);
if(reset){
yesVoteCount = 0;
noVoteCount = 0;
}
}
}
As the mentioned above, you can get the counts by using intent extras.
However if you want to reset the counts in in the second activity you might want to start the Activity B as startActivityForResult() see the Android documentation here.
Then when Activity B end you can reset the counts in the call back method onActivityResult().
If you don't want to do it like this the next best way might be to reset the counts onResume() of Activity A so that when you return to the activity you will start with fresh counts. See life cycle documentation here
In my MainActiviy class I want to display image views of smiley faces based on the number of clicks that occur on the buttons jokes, poems and funnystories combined. However my switch statement does not seem to working as no images appear. Also if any of those image views become visible, then they should remain visible even after the user closing the app and reopening it.
I also notice a click count increasing by one when the user opens the app which is not correct. It should increase based on the buttons mentioned previously being clicked.
public class MainActivity extends AppCompatActivity {
SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
ImageView yellowSmileyFace = findViewById(R.id.yellow_happy);
ImageView greenSmileyFace = findViewById(R.id.green_happy);
ImageView redSmileyFace = findViewById(R.id.red_happy);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("jokes");
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("poems");
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("funnystories");
}
});
TextView clickCountText = findViewById(R.id.click_count);
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
switch (prefManager.increaseClickCount()){
case 4 :
yellowSmileyFace.setVisibility(View.VISIBLE);
break;
case 8 :
greenSmileyFace.setVisibility(View.VISIBLE);
break;
case 12 :
redSmileyFace.setVisibility(View.VISIBLE);
break;
default :
yellowSmileyFace.setVisibility(View.INVISIBLE);
greenSmileyFace.setVisibility(View.INVISIBLE);
redsmileyFace.setVisibility(View.INVISIBLE);
}
}
private void openContentPage(String v) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intentContentPage.putExtra("keyPage", v);
startActivity(intentContentPage);
}
}
below is the Shared preferences class
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String NUMBER_OF_CLICKS = "numberOfClicks";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs = context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public int increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
return clickCount;
}
}
You need to add a getter for your clicks
public int getClicks(){
return sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
}
Whenever you want to get your clicks currently you are calling increaseClickCount() which causes your clicks to increment before returning them. That is why it gains clicks every time you open the stage and why your switch isn't working correctly
so add the above getter to your SharedPrefrenceManager and change these two lines
switch (prefManager.increaseClickCount()){
to
switch (prefManager.getClicks()){
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
to
clickCountText.setText(Integer.toString(prefManager.getClicks()));
Tell me if that fixes your problem
The reason for counts' increase is you use increaseClickCount() to receive click count.You have to create another method to receive current clickCount. Your switch statement works only when they equal to 4,8 or 12. Maybe you should use if instead.
I also notice a click count increasing by one when the user opens the app which is not correct
It looks to me like this line of code, in MainActivity.onCreate() method will pass a text String of count 1 to clickCountText.
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
Also, every time you call SharedPreferencesManager.increaseClickCount, you are assigning a value to clickCount, and whatever was there gets overwritten.
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
What is that value?
System.out.println is your friend.
I use this pattern
System.out.println("MyClass, MyMethod, MyVariable:" + myVariable);
I always include the class and method because it can be annoying trying to figure out where println are coming from if you leave several in for debugging purposes and want to get rid of them later.
For so far. I have created a simple quiz application on Android Studio. Everything works fine, including when I go from the FirstActivity.java to the Next Activity, which is named SecondActivity.java, and close the first activity with finish(),when the button is pressed, as shown in the following code:
public void onClick () {
button_next = (Button)findViewById(R.id.nextbtn);
button_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
finish();
}
});
The code works great But when I try to go from the Second Activity to the First Activity (Closing the Second Activity and going back to the first Activity), neither finish() nor onBackPressed() is working, it just closes the application completely, what code do I need to as soon as I press the button, close the SecondActivity.class and go to the FirstActivity.class?
If you want to go back to previous activity, dont put finish after you change your activity.
public void onClick() {
button_next = (Button) findViewById(R.id.nextbtn);
button_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
}
});
}
If you have so many activities ,there is another way handle activity life cycle:
public class MyActivityManager {
private static MyActivityManager instance;
private Stack<Activity> activityStack;//activity's stack
private MyActivityManager() {
}
//singleton
public static MyActivityManager getInstance() {
if (instance == null) {
instance = new MyActivityManager();
}
return instance;
}
//push an activity to stack
public void pushOneActivity(Activity actvity) {
if (activityStack == null) {
activityStack = new Stack<Activity>();
}
activityStack.add(actvity);
}
//get last activity,fifo
public Activity getLastActivity() {
return activityStack.lastElement();
}
//remove an activity
public void popOneActivity(Activity activity) {
if (activityStack != null && activityStack.size() > 0) {
if (activity != null) {
activity.finish();
activityStack.remove(activity);
activity = null;
}
}
}
//finish all activity
public void finishAllActivity() {
if (activityStack != null) {
while (activityStack.size() > 0) {
Activity activity = getLastActivity();
if (activity == null) break;
popOneActivity(activity);
}
}
}
}
at the FirstActivity,you shall add
MyActivityManager.getInstance().pushOneActivity(FirstActivity.this);
at the SecondActivity, you want to go FirstActivity or other activity:
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
MyActivityManager.getInstance().finishAllActivity();
finish();
I don't know why I am struggling with this so bad! I have two fragments that are communicating by an interface. The callback should change some data, then trigger a method to change the text of a button. This is the code for the fragment that should be changing button text.
public void updateIngredients(final ArrayList<Ingredient> ingredients){
for (Ingredient I : ingredients) {
recipe.addIngredients(I);
}
Log.d(TAG, "Ingredients size: " + ingredients.size());
updateIngredientText();
}
public void updateIngredientText(){
if(recipe.getIngredients() != null) {
Button bIng = (Button) getView().findViewById(R.id.bAddIngredientsToRecipe);
bIng.setText("Ingredients (" + recipe.getIngredients().size() + ")");
}
}
NOTE I am getting the log with expected results. But the button text does not change at all. I am getting no errors.
I have tried running this in a runOnUiThread, I have tried running it in onAttach and onResume. The button id is correct, because I use bIng to open the other fragment.
Does anyone know why this is not changing my text of my button?
Update
I think it has something to do with this. This is the method called to go back to the fragment with the button that needs changed:
public interface OnIngredientChangedListener {
public void onIngredientAdded(ArrayList<Ingredient> i);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnIngredientChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnIngredientChangedListener");
}
}
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//save button clicked
//notify AddRecipeActivity that ingredients have been added
mCallback.onIngredientAdded(selectedArray);
end();
}
});
private void end() {
//fragment Transaction here
AddRecipe addRecipe = new AddRecipe();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main_fragment_frame, addRecipe).commit();
}
I think the problem is I am creating a new instance of my fragment.