Not sure what is wrong with my code - java

Hey I was getting back into android programming, and was doing the developer.google.com tutorial and I dont know what is wrong here...
In the "public void sendMessage(View view) {" line, i get the error ';' expected.
Thanks in advance for your help.
package com.apps.graham.myfirstapp;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
public class MyActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.apps.graham.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Called when the user clicks the send button next to the text field.
if (id == R.id.action_settings) return true;
{
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewByID(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
}
}

Tricks:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Called when the user clicks the send button next to the text field.
if (id == R.id.action_settings) {
//sendMessage(your-view); here, if you want to do that.
return true;
}
return super.onOptionsItemSelected(item);
}
And your new method can't be defined inside another method:
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewByID(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}

Related

Android Studio Multiple onCreate methods in MainActivity.java

For a school project I am creating a simple app. However, I run into one problem to finalize the app.
I've been trying to make two buttons on my main layout. The buttons are supposed to open a second layout, one called barcode_scanner.xml and another called vragen.xml
However, only the first button opens the scanner. The second button does not do anything.
This is my current code from MainActivity.java
package com.kvprasad.zbarbarcodescanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button scannerButton;
#Override
//Barcodescanner knop
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.scannerButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class bovenbouw extends MainActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.bovenbutton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Vragen.class);
startActivityForResult(myIntent, 0);}});}}}
I don't see any problems in the code. What am I possibly doing wrong?
Thank you.
Do not make multiple onCreate methods for the same activity. Handle all your button clicks in the same onCreate method. What you can do is this:
package com.kvprasad.zbarbarcodescanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button scannerButton;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
//Barcodescanner knop
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next1 = (Button) findViewById(R.id.scannerButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
Button next2 = (Button) findViewById(R.id.bovenbutton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Vragen.class);
startActivityForResult(myIntent, 0);}
});
}
}
You don't need 2 onCreate() methods for two buttons. As both of them are in the same layout, you can set onClickListener on both of them in one method only.
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.scannerButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(this, BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
Button next1 = (Button) findViewById(R.id.bovenbutton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(this, Vragen.class);
startActivityForResult(myIntent, 1);
//Make sure the second parameter is not 0, so that you can differentiate between them in onActivityReult method.
}
});
}
}
You don't have to create another class for vragen.class after bovenbutton is pressed.
just create another button for bovenbutton in the main class oncreate method besides the scanner_button
#Override
//Barcodescanner knop
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.scannerButton);
Button vragen = (Button) findViewById(R.id.bovenbutton);//button for vragen
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
//here goes the onclicklistener for vragen button
vragen.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Vragen.class);
startActivityForResult(myIntent, 0);
}
});
}
You're not supposed to register two Activities in single .java file. You must create separate Activity.
package com.example.photosapp
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}

New layout doesn't pop up

I am making an app in android Studio and if you open the app on your phone you see the Launcer activity. I have a button that sends you to a new activity where te game is located. Once i click the Start button, The app closes and doesn't goes to the other activity. Why is that?
This is my code of the Launcher activity:
package joenio.sirname;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class SirName_launcher extends AppCompatActivity {
public static Button button_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sir_name_launcher);
StartButton();
}
public void StartButton(){
button_start = (Button) findViewById(R.id.button_start);
button_start.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent("joenio.sirname.Game");
startActivity(intent1);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_sir_name_launcher, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code of the second activity:
package joenio.sirname;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;
public class Game extends AppCompatActivity {
public static EditText editText_surname;
public static TextView textView_name;
public static Button button_check;
int x =0; //to keep track of qustions
//Context editText_this = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Displayquestions();
}
public void Displayquestions(){
final ArrayList<String> mQuestionList = new ArrayList<>();
mQuestionList.add("1+2");
mQuestionList.add("6+8");
mQuestionList.add("5 * 6");
mQuestionList.add("8*5");
mQuestionList.add("6+16");
mQuestionList.add("18-5");
textView_displayquestion.setText((mQuestionList.get(x)));//displayquestion is textview
final ArrayList<String> mAnswerList=new ArrayList<>();
mAnswerList.add("3");
mAnswerList.add("14");
mAnswerList.add("30");
mAnswerList.add("40");
mAnswerList.add("22");
mAnswerList.add("13");
//button_check is the button when user click it will first check answer and than move to next question if answer is correct
button_check.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//editText_this;
String answer = editText_ans.getText().toString();
if (answer.equals(mAnswerList.get(x))) {
x = x + 1;
textView_displayquestion.setText(mQuestionList.get(x)); //answer is correct display next quesion
Toast.makeText(getApplication().getBaseContext(),
(R.string.Nice), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(),
(R.string.tryagain), Toast.LENGTH_SHORT).show();
}
}
});
}
}
You are no where initializing your TextView and Button which must be causing NullPointerException.
Change your Game activity like this
TextView textView_displayquestion;
Button button_check;
EditText editText_ans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
textView_displayquestion = (TextView)findViewById(R.id.displayquestion); //change as per your id
button_check = (Button)findViewById(R.id.buttoncheck); //change as per your id
editText_ans = (EditText)findViewById(R.id.answer); //change as per your id
Displayquestions();
}
In your button click , change the code as below.
Intent intent1 = new Intent(SirName_launcher.this, Game.class);
startActivity(intent1);
And also add the new Game Activity in your Manifest file too.

Passing an drawable image from 1st activity to 2nd does not work (only from 2nd to 1ast does) Android

enter code hereThis is my First Activity::> I need:
1) select an option
2) click send an image (from drawable) should go to the second activity but it does not only from 2nd to 1st works fine all my xml and manifest files are correct (I double checked)
package com.example.damianlopez.myassignment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button toBob;
private ImageView burgerImage;
private RadioGroup radioGroupChoice;
private RadioButton radBurger;
private RadioButton radScare;
private RadioButton radSick;
private final int MY_SELECTION = 111;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_main);
//get radio Buttons
//radioGroupChoice = (RadioGroup) findViewById(R.id.radGroupChoice);
radBurger = (RadioButton)findViewById(R.id.radBurger);
radScare = (RadioButton)findViewById(R.id.radScare);
radSick = (RadioButton)findViewById(R.id.radSick);
//display app icon
ActionBar ab = getSupportActionBar();
ab.setDisplayShowHomeEnabled(true);
ab.setIcon(R.mipmap.ic_launcher);
//getting Intent
Intent getIntent = getIntent();
Bundle myBundle2 = getIntent.getExtras();
setResult(Activity.RESULT_OK, getIntent);
//
}catch(Exception e ){
}
}//End onCreate()
public void onClickButton(View v){
try {
//get radio gruop id's
radioGroupChoice = (RadioGroup) findViewById(R.id.radGroupChoice);
int mySelection = radioGroupChoice.getCheckedRadioButtonId();
if(radioGroupChoice.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(), "Please make a selection", Toast.LENGTH_LONG).show();
}else {
//creating new Intent
Intent msgToBob = new Intent(MainActivity.this, Main22Activity.class);
Bundle myBundle = new Bundle();
myBundle.putInt("imageChoice", mySelection);
msgToBob.putExtras(myBundle);
startActivityForResult(msgToBob, MY_SELECTION);
}
}catch(Exception e ){
}
}//End of onClick()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent myData) {
super.onActivityResult(requestCode, resultCode, myData);
Log.i("OnActivityResult() call", "***********");
radioGroupChoice = (RadioGroup) findViewById(R.id.radGroupChoice);
int selected = radioGroupChoice.getCheckedRadioButtonId();
//get Images
burgerImage = (ImageView) findViewById(R.id.pumpkin_burger);
if(radioGroupChoice.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(), "Please make a selection", Toast.LENGTH_LONG).show();
}
else {
switch (requestCode) {
case MY_SELECTION: {
if (resultCode == Activity.RESULT_OK) {
if (radBurger.isChecked()) {
burgerImage.setImageResource(R.drawable.pumpkin_burger);
} else if (radScare.isChecked()) {
burgerImage.setImageResource(R.drawable.pumpkin_scared);
} else if (radSick.isChecked()) {
burgerImage.setImageResource(R.drawable.pumpkin_sick);
};
}
break;
}//end case
}//end switch
}//end else if
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();``
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my Second Activity===>
package com.example.damianlopez.myassignment;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class Main22Activity extends AppCompatActivity {
private RadioGroup radioGroupChoice2;
private RadioButton radBurger;
private RadioButton radScare;
private RadioButton radSick;
private Button toAlice;
private ImageView currentImage;
private ImageView scareImage;
private ImageView sickImage;
private final int MY_SELECTION2 = 222;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
//display app icon
ActionBar ab = getSupportActionBar();
ab.setDisplayShowHomeEnabled(true);
ab.setIcon(R.mipmap.ic_launcher);
//Buttons
radioGroupChoice2 = (RadioGroup)findViewById(R.id.radGroupChoice);
//toAlice = (Button) findViewById(R.id.sndToAlice);
//get the intent called
Intent myLocalIntent = getIntent();
Bundle myBundle = myLocalIntent.getExtras();
myLocalIntent.putExtras(myBundle);
setResult(Activity.RESULT_OK, myLocalIntent);
}
public void onClickButton2(View v){
try {
radioGroupChoice2 = (RadioGroup) findViewById(R.id.radGroupChoice);
if (radioGroupChoice2.getCheckedRadioButtonId() == -1) {
Toast.makeText(getApplicationContext(), "Please make a selection", Toast.LENGTH_LONG).show();
} else {
Intent myIntent2 = new Intent();
Bundle myBundle2 = new Bundle();
int myImage = radioGroupChoice2.getCheckedRadioButtonId();
myBundle2.putInt("selectedImage", myImage);
myIntent2.putExtras(myBundle2);
setResult(Activity.RESULT_OK, myIntent2);
}
}catch(Exception e) {
}
finish();
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main22, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

launching Activity only once(First app use) Using Boolean flags

So i got my firstScreen that i want to be shown just on the first app use.
and i have my mainActivity which will follow the firstScreen.
Im only starting with android and i don't want to use the solutions brought in here: How to launch activity only once when app is opened for first time? AND Can I have an android activity run only on the first time an application is opened? because i dont know SharedPreferrences yet.
So how can i achieve that using Boolean flags?
I have got:boolean firstTimeUse = false; In my firstScreenActivity
And when i start myMainActivity i set the flag to true;
firstTimeUse = true;
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
The problem is the MainActivity doesn't recognize the Boolean variable.
Am i doing it wrong? Or i can still make some modifications and do it with flags?
EDIT
FirstScreen.java:
package com.example.predesignedmails;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class FirstScreen extends AppCompatActivity
{
TextView welcomeTextTextView;
String welcomeText;
ImageButton goToMainImageButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_screen);
viewsInitialization();
welcomeText = "Welcome to Pre Designed Mails.\n"
+ "In here you will have a tons of Emails templates for about every purpose you will need.\n"
+ "Just fill the small details and click Send.\n\n"
+ "Send E-mails fast and efficient!";
welcomeTextTextView.setText(welcomeText);
welcomeTextTextView.setMovementMethod(new ScrollingMovementMethod());
goToMainImageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume()
{
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true))
{
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
// First launch code
Log.d("FirstLaunchCheckUp","First Launch");
}
}
private void viewsInitialization()
{
welcomeTextTextView = (TextView) findViewById(R.id.welcome_text_text_view_id);
goToMainImageButton = (ImageButton) findViewById(R.id.go_to_main_button_id);
}
}
The onResume() method i added manually. It wasn't added automatically when i crated a new activity in Eclipse.
MainActivity.java:
package com.example.predesignedmails;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
Button hatefullMailButton;
Button loveMailsButton;
Button welcomeScreenButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color)); // Setting background color
viewsInitialization();
hatefullMailButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,HatefulMailsActivity.class);
startActivity(intent);
}
});
loveMailsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,LoveMailsActivity.class);
startActivity(intent);
}
});
welcomeScreenButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,FirstScreen.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void viewsInitialization()
{
hatefullMailButton = (Button) findViewById(R.id.hateful_email_button_id);
loveMailsButton = (Button) findViewById(R.id.love_email_button_id);
welcomeScreenButton = (Button) findViewById(R.id.welcome_screen_button_id);
}
}
In your Activity
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true)){
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
//your first launch code
}
}
SharedPreference helper class
public class SettingsManager
{
public static final String FIRST_LAUNCH= "first_lauch";
public static String getString(Context context, String key, String defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defValue);
}
public static int getInt(Context context, String key, int defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defValue);
}
public static boolean getBoolean(Context context, String key, boolean defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defValue);
}
public static void saveString(Context context, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
}
public static void saveInt(Context context, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).commit();
}
public static void saveBoolean(Context context, String key, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
}
}
For the future you can write more simple methods on this SettingsManager, like
public static int getFirstLaunch(Context context) {
return getBoolean(context, FIRST_LAUNCH, true);
}
public static int saveFirstLaunch(Context context, boolean value) {
return saveBoolean(context, FIRST_LAUNCH, value);
}
And use it like
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getFirstLaunch(this)){
SettingsManager.saveFirstLaunch(this, false);
//your first launch code
}
}
The reason why firstScreen does not recognize boolean firstTimeUse in mainActivity is because it does not yet exist. Only after you have executed the line startActivity(intent) will there exist an object of class mainActivity. Basically, you cannot set a boolean on something that does not yet exist.
Instead, what you can do is pass extra information to an activity that is to be started. When the just-started-activity is initializing itself it can read the extra information and act on it.
So build your intent for the activity you want to start and also set extra information in the 'extras':
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
intent.putExtra("firstTimeUse", true);
startActivity(intent);
Now for your MainActivity to know the value of firstTimeUse it must read the extras:
public class MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstTimeUse = getIntent().getBooleanExtra("firstTimeUse", false);
// do processing dependent on whether it's the first time or not
}
}
This should solve your problem of "the MainActivity doesn't recognize the Boolean variable".

Android SDK public void gets an error

I have a problem by following a tutorial for making an app. But now I get an error by adding an respond
for a button. It gives an error at public void sendMessage, but I cant see what is wrong.
package com.example.myfirstapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
/** Called when the user clicks the Send button */
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
those lines
/** Called when the user clicks the Send button */
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
go into your class, after
public class MainActivity extends ActionBarActivity {
Your function is outside the activity.
Move
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
inside Activity like this:
public class MainActivity extends ActionBarActivity {
//other code i.e. onCreate etc
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
}
}

Categories

Resources