Syntax error in Eclipse for Android Application [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I think I am going insane, Eclipse throwing up these errors "Syntax error, insert ";" to complete Statement" "Syntax error, insert ")" to complete Expression" "Syntax error, insert "}" to complete ClassBody" "Syntax error, insert "}" to complete MethodBody" and I cant seem to work out why!
Q: Can anybody work out where the syntax errors are or why Eclipse would be saying that there are errors?
Note: The idea of the code is to change the text on the button once it is pressed using the reference: Change button text and action - android development
These errors came up after I added the following lines of code:
/** Called when user clicks Start */
public void sendStart(View view) {
// Do something in response to button
final Button b_start = (Button) findViewById(R.id.b_start);
b_start.setTag (1);
b_start.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
b_start.setText("Stop");
v.setTag(0);
} else {
b_start.setText("Start");
v.setTag(1);
}
}
The entire class code is as follows:
package com.example.rius;
import android.support.v7.app.ActionBarActivity;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View; // view method to create methods
import android.widget.Button;
import android.widget.EditText;
import android.widget.ToggleButton;
import android.content.Intent; // Intent class for new activities (windows)
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.rius.MESSAGE"; // Key for intents extra data
int set_state_start_one = 0;
int set_state_start_two = 0;
#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);
}
/** Called when user clicks RPM */
public void sendRPM(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayRPMActivity.class); // Created Intent to bring up new activity (RPM Screen)
startActivity(intent); // Start a new activity (window)
}
/** Called when user clicks SPEED */
public void sendSpeed(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplaySpeedActivity.class); // Created Intent to bring up new activity (RPM Screen)
startActivity(intent); // Start a new activity (window)
}
/** Called when user clicks DIAGNOSTICS */
public void sendDiag(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayDiagnosticActivity.class); // Created Intent to bring up new activity (RPM Screen)
startActivity(intent); // Start a new activity (window)
}
/** Called when user clicks THE TOGGEL BUTTON TO CONNECT */
public void startconnection(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Enable vibrate
WifiConfiguration wificonfig = new WifiConfiguration();
wificonfig.SSID = String.format("\"%s\"", "XXXXXX");
wificonfig.preSharedKey = String.format("\"%s\"", "XXXXXX");
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
//Remember ID
int netId = wifiManager.addNetwork(wificonfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
} else {
// Disable vibrate
WifiConfiguration wificonfig = new WifiConfiguration();
wificonfig.SSID = String.format("\"%s\"", "XXXXXX");
wificonfig.preSharedKey = String.format("\"%s\"", "XXXXXX");
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
//Remember ID
wifiManager.disconnect();
}
} // togglebutton final bracket
/** Called when user clicks Start */
public void sendStart(View view) {
// Do something in response to button
final Button b_start = (Button) findViewById(R.id.b_start);
b_start.setTag (1);
b_start.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
b_start.setText("Stop");
v.setTag(0);
} else {
b_start.setText("Start");
v.setTag(1);
}
}
} // Final bracket

You're missing the closing }) for setOnClickListener:
b_start.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
b_start.setText("Stop");
v.setTag(0);
} else {
b_start.setText("Start");
v.setTag(1);
}
}
});

Related

How do I save variable values across Activities in Android Studio

I'm new here and also new to programming. I'm currently working on a project and I've been stuck for bout a week now.The only thing I want to do is save two variables so that it still can be seen after the app is closed and reopened. Also for some reason when I open the Settings Activity my variables values are set back to zero.
I'm aware that others have posted similar questions like this but I just can't adapt it to my work. I don't understand a lot of things I read like SharedPreferences, onPause(), and GAME_STATE_KEY. Could anyone please explain how to do such a thing without linking the Android Documentation articles? I don't even understand what the documentation says and copy/pasting code there doesn't seem to work.
This is my MainActivity
package com.example.courtcounter;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity<format> extends AppCompatActivity {
TextView textView;
int scoreTeamA = 0;
int scoreTeamB = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy\n hh:mm aa");
String format = simpleDateFormat.format(new Date());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.team_a_score);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String shareMessage = createMessage(format, scoreTeamA, scoreTeamB);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_SUBJECT, "Match Score");
intent.setType("text/*");
intent.putExtra(Intent.EXTRA_TEXT, shareMessage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.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();
if (id == R.id.action_settings){
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private String createMessage(String date, int TeamA, int TeamB){
EditText editTeamA = findViewById(R.id.team_a_name);
String teamAName =editTeamA.getText().toString();
EditText editTeamB = findViewById(R.id.team_b_name);
String teamBName = editTeamB.getText().toString();
String shareMessage =format +"\n"+ teamAName+ " : "+ TeamA + "\n" + teamBName + " : "+ TeamB;
return shareMessage;
}
/** Resets score of boths teams to 0
*/
public void resetScore(View v){
scoreTeamA = 0;
scoreTeamB = 0;
displayForTeamA(scoreTeamA);
displayForTeamB(scoreTeamB);
}
/**
* Displays the given score for Team A.
*/
public void displayForTeamA(int scoreTeamA){
TextView scoreViewA = (TextView)findViewById(R.id.team_a_score);
String teamA = scoreViewA.getText().toString();
scoreViewA.setText(String.valueOf(scoreTeamA));
}
/**
* Displays the given score for Team B.
*/
public void displayForTeamB(int score) {
TextView scoreViewB = (TextView) findViewById(R.id.team_b_score);
String teamB = scoreViewB.getText().toString();
scoreViewB.setText(String.valueOf(score));
}
/**
* This method is called when the +3 points button is clicked.
*/
public void ThreeA(View view){
scoreTeamA = scoreTeamA +3;
displayForTeamA(scoreTeamA);
}
/**
* This method is called when the +2 points button is clicked.
*/
public void TwoA(View view){
scoreTeamA = scoreTeamA +2;
displayForTeamA(scoreTeamA);
}
/**
* This method is called when the FREE THROW button is clicked.
*/
public void OneA(View view){
scoreTeamA = scoreTeamA + 1;
displayForTeamA(scoreTeamA);
}
/**
* This method is called when the +3 points button is clicked.
*/
public void ThreeB(View view){
scoreTeamB = scoreTeamB +3;
displayForTeamB(scoreTeamB);
}
/**
* This method is called when the +2 points button is clicked.
*/
public void TwoB(View view){
scoreTeamB = scoreTeamB +2;
displayForTeamB(scoreTeamB);
}
/**
* This method is called when the FREE THROW button is clicked.
*/
public void OneB(View view){
scoreTeamB = scoreTeamB + 1;
displayForTeamB(scoreTeamB);
}
}
Do I have to change My SettingActivity and SettingsFragment to help solve this or is it not needed?
Thanks.
If you want them to persist when the app is completely closed, SharedPreferences is the one you're looking for. This is a key/value store that allows you to store data that persists even after the activity is destroyed. Basically, they have two parts:
The key is a unique identifier used to access the data
The value is the actual data that you're trying to save
So first you get a reference to your shared preferences using
SharedPreferences.Editor editor = getSharedPreferences(
MY_PREFS_NAME, MODE_PRIVATE).edit();
This MY_PREFS_NAME can be any string you like. It allows you access your "slice" of the shared preferences. Once you get this reference, now you can begin reading and writing to them.
To write:
editor.putInt("scoreViewA", 5);
editor.putInt("scoreViewB", 12);
editor.apply();
And later to read:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
int scoreViewA = prefs.getInt("scoreViewA", 0);
int scoreViewB = prefs.getInt("scoreViewB", 0);
This second parameter in getInt is a default that will be used if the given key is not found. Note that once again you must use the same MY_PREFS_NAME when retrieving a reference to the shared preferences.
Finally, note that when writing to shared preferences, we call edit() before writing any changes, and we call apply() afterwards.
You'll want to put your code to write to shared preferences in your onPause method. This fires whenever the activity is no longer in the foreground. Then do your reading in the onResume method. This method fires when the app regains focus in the foreground.
#Override
public void onPause() {
super.onPause();
// write to shared preferences
}
#Override
public void onResume() {
super.onResume();
// read from shared preferences
}
And if you're just trying to share a variable from one activity to a new one, you can use a bundle. Check out this answer for a good example.
Hope that helps, welcome to Stackoverflow!
I finally figured it out, it was very Cathartic. My main issue was figuring out where to put the methods and it looks like I didn't need the onPause() and onResume() methods.
First in the AndroidManifest.xml file I added
android:launchMode="singleTop" but it the end it wasn't needed since I managed to save the preferences.
In my display methods I added
SharedPreferences myScoreB = getSharedPreferences("teamBScore", Context.MODE_PRIVATE); SharedPreferences.Editor editor = myScoreB.edit();editor.putInt("scoreB", scoreTeamB);editor.commit();
The reading data part was confusing but in the end I managed to do it in the oncreate method SharedPreferences myScoreB = this.getSharedPreferences("teamBScore", Context.MODE_PRIVATE);scoreTeamB = myScoreB.getInt("scoreB", 0);scoreViewB.setText(String.valueOf(scoreTeamB));
It now handle screen rotations without recreating the entire layout as well as restarts.

.setChecked() isn't setting the state of radio button

I'm creating a security settings part in my app.
There are 3 radio buttons that allow the user to choose between a passcode, TouchID or nothing. All radio buttons are unchecked by default. When clicking on a radio button (e.g. to use passcode), the code checks to see if the user has set up a passcode. If the user hasn't, a dialog is shown and the radio button remains unchecked. The user then goes and sets up a passcode (setUpPasscode button).
Once set up, the passcode activity closes with the return case '2' and the radio button with the passcode option should be checked. It isn't however. When I re-launch the application, the button is checked though. It somehow isn't checked immediately after finishing the previous activity but it is technically checked. What am I doing wrong?
public class SecuritySettings extends AppCompatActivity
{
TextView goBackToSettings;
Button setUpPasscode;
Button setUpTouchID;
RadioButton usePasscodeSelection;
RadioButton useTouchIDSelection;
RadioButton useNeitherSelection;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Dialog myDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.security_settings);
goBackToSettings = (TextView) findViewById(R.id.closeSettingsButtonID);
setUpPasscode = (Button) findViewById(R.id.setUpPasscodeButtonID);
setUpTouchID = (Button) findViewById(R.id.setUpTouchIDButtonID);
usePasscodeSelection = (RadioButton) findViewById(R.id.usePasscode);
useTouchIDSelection = (RadioButton) findViewById(R.id.useTouchID);
useNeitherSelection = (RadioButton) findViewById(R.id.useNothing);
myDialog = new Dialog(this);
//load state of radio buttons
loadRadioButtons();
// go back to main settings page
goBackToSettings.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent goBackToMainSettings = new Intent(getApplicationContext(), AppSettings.class);
goBackToMainSettings.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goBackToMainSettings);
finish();
}
});
//Open new activity for setting passcode
setUpPasscode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setUpPasscodeActivity = new Intent(getApplicationContext(), SetupPasscode.class);
startActivityForResult(setUpPasscodeActivity, 2);
}
});
// Open new activity for setting up TouchID
setUpTouchID.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setupTouchIDActivity = new Intent(getApplicationContext(), SetupTouchID.class);
startActivityForResult(setupTouchIDActivity, 1);
}
});
// when clicked, all other buttons become unchecked and the state of the buttons are saved
usePasscodeSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForPasscode = doesUserHavePasscode();
// If true, user has a passcode setup
if (bCheckForPasscode)
{
usePasscodeSelection.setChecked(true);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up a passcode to enable this option.");
}
}
});
useTouchIDSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForTouchID = doesUserHaveTouchIDSetup();
// If true, user has TouchID setup
if (bCheckForTouchID)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(true);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up TouchID to enable this option.");
}
}
});
useNeitherSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(true);
saveRadioButtons();
}
});
}
// Open sharedpreferences and get the value that was saved there after setting up passcode using the same key 'string'
public boolean doesUserHavePasscode()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
String checkHashString = sharedPreferences.getString("hashed_password", null);
if (checkHashString == null)
{
return false;
}
else
{
return true;
}
}
// Open sharedpreferences and get the value that was saved there after setting up TouchID using the same key 'string'
public boolean doesUserHaveTouchIDSetup()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean bDoesUserHaveTouchIDSetup = sharedPreferences.getBoolean("doesUserHaveTouchIDSetup", false);
return bDoesUserHaveTouchIDSetup;
}
public void NoOptionSetPopup(View v, String message)
{
TextView closePopup;
TextView contents;
myDialog.setContentView(R.layout.no_option_setup_popup);
closePopup = (TextView) myDialog.findViewById(R.id.closePopupButtonID);
contents = (TextView) myDialog.findViewById(R.id.theMessageID);
contents.setText(message);
closePopup.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Close popup
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
myDialog.show();
}
// Callback method to get the boolean from SetupPasscode/SetupTouchID activity & override the method
// What is being done here is that after a passcode/TouchID has been setup, we automatically assume that the newly set-up authentication will want to be used by the user.
// The values being returned from the activities only happen when they're successfully done (passed all validation checks).
// We then automatically make the corresponding radio button selected (if passcode setup, then select the 'use passcode on startup' radio button)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
// Case for returning from SetupPasscode class
case 2:
// fetch the boolean value
boolean isDone = data.getBooleanExtra("isDone", false);
usePasscodeSelection.setChecked(isDone);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
// Case for returning from SetupTouchID class
case 1:
// fetch the boolean value
boolean isTouchIDSetup = data.getBooleanExtra("isTouchIDDone", false);
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(isTouchIDSetup);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
default:
throw new IllegalStateException("Unexpected value: " + requestCode);
}
}
public void saveRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = sharedPreferences.edit();
editor.putBoolean("usePasscodeOption", usePasscodeSelection.isChecked());
editor.putBoolean("useTouchIDOption", useTouchIDSelection.isChecked());
editor.putBoolean("useNeitherOption", useNeitherSelection.isChecked());
}
public void loadRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
usePasscodeSelection.setChecked(sharedPreferences.getBoolean("usePasscodeOption", false));
useTouchIDSelection.setChecked(sharedPreferences.getBoolean("useTouchIDOption", false));
useNeitherSelection.setChecked(sharedPreferences.getBoolean("useNeitherOption", false));
}
}
I would suggest to overload the onResume method and checking the state of your radio buttons as that will be the last control where the flow will leave your activity.

Android Studio 'Run app' dialogue doesn't appear in one project but will in another

I'm toying with Android Studio making a very simple very stupid app to learn about saving key preferences and I ran into a weird obstacle. I'll try to provide as much as I can since it may be hard to reproduce this bug but honestly both apps I'm running are super basic and there no compile errors.
Specs:
No emulator, I'm running a Samsung Galaxy Tablet. Windows 7, Android Studio 1.2, Gradle 2.2.1.
In the question title, I mean that I have a project named Kitty (pretty much hello world and a button). I click Run->'Run app'->(Dialogue box opens)->OK->Within moments the app launches on my tablet.
^^^THIS IS THE BEAUTIFUL SCREEN I WANT TO SEE ON Sharedpreferences, but it's only on kitty.
Now I started another project called SharedPreferences (gist: two checkboxes ask you "do you like chocolate" and "do you like luigi" and you check one none or both and press save. Two textviews underneath will update to say if you like those things and even later if you reopen the app the textviews will remember Chocolate Luigi preferences). It is just a main_activity.
I don't think I changed any settings or project preferences between the two and neither give me an error. MainActivity.java OUTDATED ORIGINAL SEE EDIT:
package gaga.sharedpreferences;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
public final class setup extends MainActivity {
public void setup () {
//Nothing to see here!
}
// Define the File of Prefs; created if nonexistent
public static final String PREFS_NAME = "MyPrefsFile";
// Start up
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Restore preferences on Startup
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean Chocolate = settings.getBoolean("checkChocolate", false);
boolean Luigi = settings.getBoolean("checkLuigi", false);
// Function set to Whatever
// setSilent(silent);
/* Note:
* CheckedTextView and CheckBox::isChecked()
* CheckBox::setChecked()
* */
CheckBox checkHandleChocolate = (CheckBox) findViewById(R.id.checkChocolate);
CheckBox checkHandleLuigi = (CheckBox) findViewById(R.id.checkLuigi);
// What was the preference? On Start set it to the bool it left off in
checkHandleChocolate.setChecked(Chocolate);
checkHandleLuigi.setChecked(Luigi);
// Change report text on Start
TextView buttonHandleChocolate = (TextView) findViewById(R.id.chocolate);
TextView buttonHandleLuigi = (TextView) findViewById(R.id.luigi);
if(Chocolate)
buttonHandleChocolate.setText("I do prefer Chocolate");
else
buttonHandleChocolate.setText("I do not prefer Chocolate");
if(Luigi)
buttonHandleLuigi.setText("I do prefer Luigi");
else
buttonHandleLuigi.setText("I do not prefer Luigi");
}
public void saveChocolate(Boolean c) {
// All objects from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Chocolate", c);
// Commit the edits
editor.commit();
}
public void saveLuigi(Boolean l) {
// All objects from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Chocolate", l);
// Commit the edits
editor.commit();
}
}
#Override
protected void onStop(){
super.onStop();
// Objects are from android.context.Context
//Normally I'd put the edit commits here, but that's not true
}
// Clicks on Done
public void userDone (View view) {
// View is which widget
boolean checked = ((CheckBox) view).isChecked();
// Which checkbox was clicked
switch(view.getId()) {
case R.id.checkChocolate:
setup instance1 = new setup();
instance1.saveChocolate(checked);
// No break; continue along
case R.id.checkLuigi:
setup instance2 = new setup();
instance2.saveLuigi(checked);
break;
}
}
#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.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);
}
}
Red parts of logcat:
06-02 20:49:57.245 25557-25557/? I/SDP.PUB_CRYPTOD﹕ Starting
06-02 20:49:57.245 25557-25557/? I/SDP.PUB_CRYPTOD﹕ Socket created with fd:-1
06-02 20:49:57.245 25557-25557/? E/SDP.PUB_CRYPTOD﹕ Failed to open the netlink socket with error: Protocol not supported
06-02 20:49:57.245 25557-25557/? E/SDP.PUB_CRYPTOD﹕ Exiting
06-02 20:49:59.995 2866-3012/? V/AlarmManager﹕ waitForAlarm result :8
06-02 20:50:02.280 25633-25633/? I/SDP.PUB_CRYPTOD﹕ Starting
06-02 20:50:02.280 25633-25633/? I/SDP.PUB_CRYPTOD﹕ Socket created with fd:-1
06-02 20:50:02.280 25633-25633/? E/SDP.PUB_CRYPTOD﹕ Failed to open the netlink socket with error: Protocol not supported
06-02 20:50:02.280 25633-25633/? E/SDP.PUB_CRYPTOD﹕ Exiting
Thanks for any help. I haven't seen this issue while prowling the internet so it might be excessively noob.
EDIT: Rewritten with the only onCreate in the larger MainActivity class
package gaga.sharedpreferences;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
public final class setup extends MainActivity {
public void setup () {
//Nothing to see here!
}
// Define the File of Prefs; created if nonexistent
public static final String PREFS_NAME = "MyPrefsFile";
// Start up
public void onCreateSubclass() {
// super.onCreate(state);
// Restore preferences on Startup
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean Chocolate = settings.getBoolean("checkChocolate", false);
boolean Luigi = settings.getBoolean("checkLuigi", false);
// Function set to Whatever
// setSilent(silent);
/* Note:
* CheckedTextView and CheckBox::isChecked()
* CheckBox::setChecked()
* */
CheckBox checkHandleChocolate = (CheckBox) findViewById(R.id.checkChocolate);
CheckBox checkHandleLuigi = (CheckBox) findViewById(R.id.checkLuigi);
// What was the preference? On Start set it to the bool it left off in
checkHandleChocolate.setChecked(Chocolate);
checkHandleLuigi.setChecked(Luigi);
// Change report text on Start
TextView buttonHandleChocolate = (TextView) findViewById(R.id.chocolate);
TextView buttonHandleLuigi = (TextView) findViewById(R.id.luigi);
if(Chocolate)
buttonHandleChocolate.setText("I do prefer Chocolate");
else
buttonHandleChocolate.setText("I do not prefer Chocolate");
if(Luigi)
buttonHandleLuigi.setText("I do prefer Luigi");
else
buttonHandleLuigi.setText("I do not prefer Luigi");
}
public void saveChocolate(Boolean c) {
// All objects from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Chocolate", c);
// Commit the edits
editor.commit();
}
public void saveLuigi(Boolean l) {
// All objects from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Chocolate", l);
// Commit the edits
editor.commit();
}
}
#Override
protected void onStop(){
super.onStop();
// Objects are from android.context.Context
//Normally I'd put the edit commits here, but that's not true
}
// Clicks on Done
public void userDone (View view) {
// View is which widget
boolean checked = ((CheckBox) view).isChecked();
// Which checkbox was clicked
switch(view.getId()) {
case R.id.checkChocolate:
setup instance1 = new setup();
instance1.saveChocolate(checked);
// No break; continue along
case R.id.checkLuigi:
setup instance2 = new setup();
instance2.saveLuigi(checked);
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup startInstance = new setup();
startInstance.onCreateSubclass();
}
#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);
}
}
In Android Studio you need create a Run Configuration in your project.
Go to this link to left run icon
And click on Edit Configuration, after in the windows configure like this:
And save it, for test click run icon.
It appears that you have two onCreate methods. Try removing the second one and running it again.

How to use java classes within one activity?

How can you use a java class within one activity, by that I mean is having different components of that activity spread out in a bunch of java classes. I'm a little new to android and this is what I have tried so far:
MainActivity.java
package com.example.alex.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Something(this);
}
#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);
}
}
Something.java
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
public class Something {
private Activity activity;
private Button add,subtract,multiply,devide;
private EditText editA, editB, editC;
private double doubleA,doubleB,doubleC;
public Something(Activity a){
activity=a;
click();
}
public void click(){
editA = (EditText) activity.findViewById(R.id.editText);
editB = (EditText) activity.findViewById(R.id.editText2);
editC = (EditText) activity.findViewById(R.id.editText3);
doubleA =Double.parseDouble(editA.getText().toString());
doubleB =Double.parseDouble(editB.getText().toString());
add = (Button) activity.findViewById(R.id.add);
subtract = (Button) activity.findViewById(R.id.subtract);
multiply = (Button) activity.findViewById(R.id.multiply);
devide = (Button) activity.findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA+doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA-doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA*doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA/doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
}
}
So I wasn't sure why my listeners weren't working on my buttons so I tried passing the activity to the class that has the listeners added to the buttons but that didn't work in fact now my application won't even start in the emulator. All I wanted to do was have "MainActivity" handle the "Gui" and have the "Something" class handle the listeners but no matter what I do I can't seem to make them communicate with one another to form one Activity.
LogCat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2071)
at com.example.alex.myapplication.Something.click(Something.java:32)
at com.example.alex.myapplication.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
like a before post XD with 1 java class, call it again after pressing buttons, for example, you can have a invisible buttons, radiobuttons whatever you want invisible and just with a click it turns visible and useful for you, here i go:
First the variable which controls the activity are going to do
String num ="";
then have your buttons, i use 2 of them and the others are invisible
Button bn1;
Button bn2;
Button bn3;
Button bn4;
bn3.setVisibility(View.INVISIBLE);
bn4.setVisibility(View.INVISIBLE);
then the button code, depends on how many buttons you want
Button.setOnClickListener(new Button onclickListener(){
public void onClick(){
//get a default variable in this case String num
Intent intent = new Intent(MainActivity.this, MainActivity.class); num="cero"; intent.putExtra("po", num);
CodigoPeticion=2; startActivityForResult (intent,CodigoPeticion); finish(); break;
}
}
});
this one to get the String num:
Bundle extras = getIntent().getExtras();
if (extras!= null) {
num =extras.getString("po");
}
and at last but not least this one to do someting depending the String:
if (num.matches("cero")){
//do something, enable more buttons, disable radiobuttons,
bn3.setVisibility(View.VISIBLE);
}else if(num.matches("one")){//this string is from another button
//do something else in the same activity, as you spected enable radiobuttons, show a image, etc
bn4.setVisibility(View.VISIBLE);
}else{
//some textview with a specific title
TextView.setText("Something's Wrong");
}
don't forget the bn3 and bn4 listeners!
hope that helps you, see ya!
I think that you should rearrange the code to have the onClickListener inside Something constructor:
Something.java
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
public class Something {
private Activity activity;
private Button add, subtract, multiply, devide;
private EditText editA, editB, editC;
private double doubleA, doubleB, doubleC;
public Something(Activity a) {
activity = a;
editA = (EditText) activity.findViewById(R.id.editText);
editB = (EditText) activity.findViewById(R.id.editText2);
editC = (EditText) activity.findViewById(R.id.editText3);
add = (Button) activity.findViewById(R.id.add);
subtract = (Button) activity.findViewById(R.id.subtract);
multiply = (Button) activity.findViewById(R.id.multiply);
devide = (Button) activity.findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(1);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(2);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(3);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(4);
}
});
}
public void click(int calculate) {
// assume number entered - no error
doubleA = Double.parseDouble(editA.getText().toString());
doubleB = Double.parseDouble(editB.getText().toString());
switch (calculate) {
case 1:
doubleC = doubleA + doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 2:
doubleC = doubleA - doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 3:
doubleC = doubleA * doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 4:
doubleC = doubleA / doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
default:
break;
}
}
}
I think the problem was putting 'click()' method inside the main constructor runs through the code once only. I hope this helps!
You can use your "something" class in the mainactivity.
first initialize "Something" class in the main activity by
Something s = new Something(MainActivity.this);
Than you can use every method of that class in your main Activity.Just as you wanted,like this
s.add.setonclicklistener(...
or
s.click();
//Just use like this.
As I know this will help someone else who encountered the same problem as me will benefit, the problem was that I needed to pass the activity into my Something(Activity a){} constructor and initialize everything into that. Like Something(Activity a){
aT1 = (EditText) a.findViewById(R.id.numberOne);
aT2 = (EditText) a.findViewById(R.id.numberTwo);
aT3 = (EditText) a.findViewById(R.id.result);
add = (Button) a.findViewById(R.id.add);
subtract = (Button) a.findViewById(R.id.subtract);
multiply = (Button) a.findViewById(R.id.multiply);
devide = (Button) a.findViewById(R.id.devide);
}
And all you need to do in main activity is pass the Activity when you make an instance/execute the code(ex: Something s = new Something(this);/new Something(this);) After you done that you can just call s.click(); and it should work.

ActionBarSherlock with multiple MenuItems?

I've been using ABS 4.0 with two MenuItems in one of my apps, but have discovered a little error: When pressing the second MenuItem, it does exactly the same as the first one...
I've tried just about everything I can think of, but it isn't working. I've altered onOptionItemSelected, as I thought that was the method I need to edit.
EDIT:
I've been looking at #Ollie's suggestions, but neither LogCat nor Debug is showing weird things. Maybe it's in some other part of the code, or a declaration for ABS? Here's the entire code, if you could look through it, that would be great!
The code for the whole Activity, as it's maybe in some other place?
package bas.sie.Antonius;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
public class TeacherInfo extends SherlockActivity {
String URLhome;
String Info;
String TeacherAb;
TextView mTxtvInfo;
Button mBtnTeacherStSchedule;
Button mBtnTeacherDaySchedule;
private static String mainUrl = "http://www.carmelcollegegouda.nl/site_ant/";
private static String endUrl = ".htm";
private static String[] myUrls = { "roosters/dagroosters/Doc_V1_",
"roosters/standaardroosters/Doc1_" };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactinfo);
setTitle("Over deze leraar");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
mTxtvInfo = (TextView) findViewById(R.id.TxtvTeacher);
Intent startingIntent = getIntent();
Info = startingIntent.getStringExtra("contact");
mTxtvInfo.setText(Info);
Intent startingIntent1 = getIntent();
TeacherAb = startingIntent1.getStringExtra("abbrev");
mBtnTeacherDaySchedule = (Button) findViewById(R.id.btnTeacherDaySchedule);
mBtnTeacherStSchedule = (Button) findViewById(R.id.btnTeacherStSchedule);
mBtnTeacherDaySchedule.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
URLhome = makeUrl(0);
Intent i = new Intent(TeacherInfo.this, MyWebView.class);
i.putExtra("home", URLhome);
startActivityForResult(i, 0);
}
});
mBtnTeacherStSchedule.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
URLhome = makeUrl(1);
Intent i = new Intent(TeacherInfo.this, MyWebView.class);
i.putExtra("home", URLhome);
startActivityForResult(i, 0);
}
});
}
private String makeUrl(int index) {
String s = mainUrl + myUrls[index] + TeacherAb + endUrl;
return s;
}// makeurl
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Instellingen")
.setIcon(R.drawable.ic_settings)
.setShowAsAction(
MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
menu.add("Over de app")
.setIcon(R.drawable.ic_about)
.setShowAsAction(
MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, AntoniusActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.settings:
Intent i = new Intent(this, About.class);
startActivity(i);
return true;
case R.id.about:
Intent about = new Intent(this, About.class);
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I'm thinking that the problem is in the declaration of the menu items, but I don't see any problem there...
Could you take a look at my menu.xml? Posted here:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/settings"
android:icon="#drawable/ic_settings"
android:title="Instellingen"></item>
<item android:id="#+id/about"
android:icon="#drawable/ic_about"
android:title="Over de app"></item>
</menu>
Create the menu like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
Then use a switch statement to handle selections:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Do stuff
return true;
case R.id.menu_item_2:
// Do stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
EDIT: Finally, you should do different things for each item, if you change the Intent target Activity to another, it'll do what you expect:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// ... Stuff ...
case R.id.settings: // Settings item
Intent i = new Intent(this, About.class); // Start About.java Activity, but item says "settings"
// TODO: Change About to Settings?
i = new Intent(this, Settings.class);
startActivity(i);
return true;
case R.id.about: // About item
Intent about = new Intent(this, About.class); // Start About.java Activty
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
What I find odd is the way you create your menu.
You have defined menu layout it in a menu.xml, yet you do not reference this layout in a onCreateOptionMenu() method.
It should be something like this:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
Pay attention to the getSupportMenuInflater() method which is used instead of getMenuInflater(). Why this must be so is somewhere in docemntation about android support library which in term is used by ActionBarSherlock library.
What you do is create menu in code programmatically by using a method menu.add() with a signature add(CharSequence). Nowhere it is in there that you give ItemId. I guess (and this is only a guess) android in that case assigns the same id to all items, something like zero or some other arbitrary number. You should use a method with a signature add(int, int, int,CharSequence) or add(int, int, int, int) as only those allow you to specify ItemId. So, both of your menu items have the same id. And this is (I guess again) the cause that they behave the same.
One more thing. Be careful that you use the correct substitute classes and methods from support library and ActionBarSherlock library.
Please let us know if this solved the problem as I am only running this in my head.

Categories