I have a class in which a string is taken from an input. I want to use the value of the input in a second class.
public class Incontrare extends ActionBarActivity {
public static String nome1=null;
public String variabileNome;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incontrare);
Button button1 = (Button) findViewById(R.id.button1Nome);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
alertDia(); //takes the input from variabileNome
nome1 = variabileNome;
TextView textv1 = (TextView) findViewById(R.id.textView1);
textv1.setText(nome1);
}
});
public static String getNome1() {return nome1;}
}
}
And the second class:
public class IncontrarePersona1 extends ActionBarActivity {
String nome1=Incontrare.getNome1();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incontrare_persona1);
b1=(Button)findViewById(R.id.play);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String toPrint = "There is " + nome1;
Toast.makeText(getApplicationContext(), toPrint, Toast.LENGTH_SHORT).show();
}
});
}
I tried the second class also in this way:
public class IncontrarePersona1 extends ActionBarActivity {
String nome1=Incontrare.getNome1();
public static String no1;
b1=(Button)findViewById(R.id.play);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Incontrare no1= new Incontrare();
String n1= no1.nome1;
String toPrint = "There is " + nome1;
Toast.makeText(getApplicationContext(), toPrint, Toast.LENGTH_SHORT).show();
}
});
}
Where is the mistake? Why do I get always null?
Any help is appreciated. Thanks :)
If you are jumping from activity to another use Bundle.
Bundle example -
Set value
Intent i = new Intent();
i.setClass(this, IncontrarePersona1.class);
i.putExtra("text", "some text");
startActivity(i);
Get Value:
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String data= extras.getString("text");
//data is your param
}
Otherwise use static class with static variables as Will McG said.
I think the issue is that when the second Activity is brought into focus, the data in the previous Activity is lost.
Create a separate class to hold your static variables that both Activitys can access.
Edit:
Another method I use for passing data is the SharedPreferences if I'm worried about the entire application losing focus.
Related
Hi I just need a little bit of a helping hand in completing this shared preferences code I have.
Currently I have a class where I stored in the relevant code for SharedPreferences:
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 void storeClicks(int count)
{
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, count);
editor.apply();
}
public int getNumberOfClicks(){
int clicksNumber = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
return clicksNumber;
}
}
I want to count the number of clicks for buttons jokes, poems and funnystories from the MainActivity class and the 'select another' button from the Content class. So if each button was clicked 4 times, the total click count should be 16.
I want to keep the number of clicks count even after the app is closed and re-open. It's just the syntax of the counting of the clicks I am unsure of. I think for main activity it is correct but I am unsure on how to store it for the Content class.
TO recap, count the number of clicks for all of those buttons mentioned and this number should be accessible and updated no matter which page the user is in.
Below is the Main Activity class:
public class MainActivity extends AppCompatActivity{
final Context context = this;
int clicksCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferencesManager.getInstance(context).storeClicks(clicksCount);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
}
Below is Content class:
public class Content extends AppCompatActivity{
Button backButton;
Button selectAnotherButton;
TextView contentText;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
int clicksCount = SharedPreferencesManager.getInstance(context).getNumberOfClicks();
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
finish();
}
});
}
}
Instead of having the two methods getNumberOfClicks() and storeClicks() in your SharedPreferencesManager, you could only have one like this:
public void increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
}
You call this on every click. No need for the activities to know about the clicks count.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(context);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
}
});
...
}
Also there's no need to store your context as a global variable because your activity is already a context itself, you can just use this or MainActivity.this for a context.
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE="com.example.ferhat.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN="com.example.ferhat.geoquiz.answer_shown";
private static final String CHEATER="com.example.ferhat.geoquiz.cheated";
private Boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mIsCheater;
public static Intent newIntent(Context packageContext, boolean answerIsTrue){
Intent i=new Intent(packageContext,CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE,answerIsTrue);
return i;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
//Cevabı gösteriyor ve Kopya çekildi bilgisi veriliyor
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
mIsCheater=true;
setAnswerShownResult();
}
});
if(savedInstanceState!=null){
mIsCheater=savedInstanceState.getBoolean(CHEATER,false);
}
}
private void setAnswerShownResult(){
Intent data=new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN,mIsCheater);
setResult(RESULT_OK,data);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(CHEATER,mIsCheater);
}
}
I try to solve challenge in Anroid Programming, Big Nerds Ranch Guide (Chap.5)
Challenge asks me to keep Cheat data while rotation of screen and transaction between questions.Main Activity holds questions and CheatActivity has answers from Main activity. And i created BooleanArray to hold cheat data for questions.
Problem is ,i cheated for first question and then when i am in the CheatActivity(CheatPage) of other questions ,program crashes if i rotate the screen.
Error caused by this line savedInstanceState.putBoolean(CHEATER,mIsCheater);
i think i need to clear data from previous Cheat Data(BooleanArray already holding it) but i dont know how to do it.
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE = "com.example.ferhat.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.example.ferhat.geoquiz.answer_shown";
public static final String EXTRA_CHEATED = "com.example.ferhat.geoquiz.cheated";
private static final String CHEATER = "com.example.ferhat.geoquiz.cheated";
private Boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mAnswerEverShown;
private Boolean twoStep=false;
//Yeni intent methodu yarattık Cevabı alıyor ve bu activity i başlatıyor
public static Intent newIntent(Context packageContext, boolean answerIsTrue, boolean checked) {
Intent i = new Intent(packageContext, CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
i.putExtra(EXTRA_CHEATED, checked);
return i;
}
private void setAnswerShownResult(Boolean isAnswerShown) {
Intent data = new Intent();
**if(mAnswerEverShown) {
isAnswerShown=mAnswerEverShown;
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}else {
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
twoStep=isAnswerShown;**
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
**mAnswerEverShown = getIntent().getBooleanExtra(EXTRA_CHEATED, false);**
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
//Cevabı gösteriyor ve Kopya çekildi bilgisi veriliyor
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
twoStep=true;
setAnswerShownResult(twoStep);
}
});
**if (savedInstanceState != null) {
setAnswerShownResult(savedInstanceState.getBoolean(CHEATER, false));
}
}
#Override
public void onSaveInstanceState (Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(CHEATER, twoStep);
}
}**
i found solution like for every situation.
first think i did; i get info from main activity
mAnswerEverShown = getIntent().getBooleanExtra(EXTRA_CHEATED, false);
And Then i changed setAnswerShownResult for two situation.If it is not cheated ever program sends current data(cheated or not).
i marked where i changed with *.
You need to putBoolean before callback the super method.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putBoolean(CHEATER,mIsCheater);
super.onSaveInstanceState(savedInstanceState);
}
if not the CHEATER won't be saved and you can't call it when resume activity
I have one button in mainactivity when i click on button formactivty opened then after saved the data and i killed the app it display from main activity, it doesn't show welcome activity by using shared preference. any one can solve this one
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
FormActivty
public class Form extends Activity {
SharedPreferences sp;
public static String Filename= "LoginFile";
public static String key = "status";
EditText namee,emaill;
String Name,Email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
boolean res = sp.getBoolean(key,false);
if (res) {
setContentView(R.layout.welcom);
} else {
setContentView(R.layout.form);
}
}
public void save(View v) {
namee = (EditText)findViewById(R.id.name);
emaill = (EditText)findViewById(R.id.email);
Name = namee.getText().toString();
Email = emaill.getText().toString();
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(key,true);
ed.putString("k1",Name);
ed.putString("k2",Email);
ed.commit();
Intent i = new Intent(this,Welcome.class);
startActivity(i);
}
}
Welcome Activity
public class Welcome extends Activity {
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcom);
sp = getSharedPreferences(Form.Filename,MODE_PRIVATE);
TextView tv= (TextView)findViewById(R.id.text);
TextView tv1= (TextView)findViewById(R.id.text1);
String username,email;
Intent i = getIntent();
Bundle b = new Bundle();
b= i.getExtras();
username = sp.getString("k1","");
email = sp.getString("k2","");
tv.setText(username);
tv1.setText(email);
}
public void logout(View v) {
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(Form.key,false);
ed.commit();
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
On your MainActivity, under onCreate(), there should be a code that checks if your SharedPreference is empty. If it's empty, it should go to Form.class or it should not do anything since you have a button there in MainActivity. If not, then go to Welcome.class. You're almost there, just do some minor tweaks on your code and you'll get it.
public class MainActivity extends AppCompatActivity {
SharedPreferences sp;
public static String Filename= "LoginFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
String name = sp.getString("k1", "");
if(!name.isEmpty()){
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
}
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
If you'll notice on this code, every time the app is killed and you start it again, it'll check if sharedpreference is empty. If not, it will go directly to Welcome.class.
I have been trying to get a string to go from one java class to another for a project of mine. The code I have been experimenting with is not working. When I press the button, I know it opens the other Java class because it creates the other layout, but it doesn't show the string. Please help me.
First Java Class:
public class MainActivity extends AppCompatActivity {
private Button button;
Context context;
private EditText editText;
String number = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString() != null) {
String value = "value";
Intent secondscreenIntent = new Intent(context, SecondScreenJ.class);
secondscreenIntent.putExtra("Number", editText.getText().toString());
startActivity(secondscreenIntent);
}
}
});
}
}
Second Java Class:
public class SecondScreenJ extends Activity {
String number = null;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
textView = (TextView) findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if (extras != null){
number = extras.getString("number");
}
textView.setText(number);
}
}
you are putting "Number" as key but, in your second activity you are trying to retrieve "number"
so change number to Number and it will work.
Its case Sensitive.
Don't make your keys hard-coded in that way.
Just declare public static variable in MainActivity and use it from SecondScreenJ
public class MainActivity extends AppCompatActivity {
private Button button;
Context context;
private EditText editText;
public static String NUMBER_KEY = "Number";
String number = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString() != null) {
String value = "value";
Intent secondscreenIntent = new Intent(context, SecondScreenJ.class);
secondscreenIntent.putExtra(NUMBER_KEY , editText.getText().toString());
startActivity(secondscreenIntent);
}
}
});
}
}
Second Java Class:
public class SecondScreenJ extends Activity {
String number = null;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
textView = (TextView) findViewById(R.id.textView);
Bundle extras = getIntent().getExtras();
if (extras != null){
number = extras.getString(MainActivity.NUMBER_KEY);
}
textView.setText(number);
}
}
Beware when using the key for putting and getting the extras. They're case sensitive. Replace "number" with "Number" in your second activity.
I have search a lot in different sites to solve this problem but I can't till now.
I have a simple app with 50 articles, two buttons, previous and next.
All works fine till the last article 50 where the problem is that the user can't choose the previous button 49, only can load from the beginning.
Here is my code: MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView meditCenterText;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
meditCenterText = (TextView) findViewById(R.id.editCenterText);
mStartButton = (Button) findViewById(R.id.startButton);
meditCenterText.setMovementMethod(new ScrollingMovementMethod());
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TextView = meditCenterText.getText().toString();
startStory(TextView);
}
});
}
private void startStory(String TextView) {
Intent intent = new Intent(this, StoryActivity.class);
intent.putExtra("TextView", TextView);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
meditCenterText.setText("..... ");
}}
StoryActivity.java
public class StoryActivity extends AppCompatActivity {
public static final String TAG = StoryActivity.class.getSimpleName();
private Story mStory = new Story();
private ImageView mImageView;
private TextView mTextView;
private Page mCurrentPage;
private String mName;
private Button mPreviousButton;
private Button mNextButton;
private ScrollView mScrollView;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story2);
//Intent intent = getIntent();
//mName = intent.getStringExtra(getString(R.string.key_name));
if(mName == null){
mName = "";
}
Log.d(TAG, mName);
mImageView = (ImageView)findViewById(R.id.storyImageView);
mTextView = (TextView)findViewById(R.id.storyTextView);
mPreviousButton = (Button)findViewById(R.id.previousButton);
mNextButton = (Button)findViewById(R.id.nextButton);
mTextView.setMovementMethod(new ScrollingMovementMethod());
loadPage(0);
}
private void loadPage(int choice){
mCurrentPage = mStory.getPage(choice);
Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
mImageView.setImageDrawable(drawable);
String pageText = mCurrentPage.getText();
//add the name if placeholder included.
//pageText = String.format(pageText,mName);
mTextView.setText(pageText);
if(mCurrentPage.isSingle()){
mPreviousButton.setVisibility(View.VISIBLE);
mNextButton.setText("Start From The Beginning");
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPreviousButton.setVisibility(View.VISIBLE);
loadPage(0);
}
});
}else{
mPreviousButton.setText(mCurrentPage.getChoices().getText1());
mNextButton.setText(mCurrentPage.getChoices().getText2());
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousPage = mCurrentPage.getChoices().getPreviousPage();
loadPage(previousPage);
}
});
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoices().getNextPage();
loadPage(nextPage);
}
});
}}
}
Thanks for help.
It's probably the logic in your Page class. Have a proper look at it, otherwise from the android side everything is alright. One last thing, you should probably use a ViewPager for your app instead of changing the text every time you load a new oage