Android Shared Preferences resume game button not working - android

I am creating a game app, which needs to allow the player to save and resume their position.
The save works fine, storing the room position, it retrieves the room position fine when clicking the "resume" button but doesn't take the player to the saved room position, it just starts the game from the beginning.
I think it maybe to do with this code, but after 8 hours of research, I still have no idea how to alter it:-
Intent value = new Intent(MainMenu.this, MainActivity.class);
startActivity(value);
Please help, thanks!
package com.example.gameversion2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainMenu extends AppCompatActivity {
Button play;
Button resume;
Button exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
resume = (Button) findViewById(R.id.resume);
resume.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences sp = getSharedPreferences("SAVEPOS", Context.MODE_PRIVATE);
//Load the Editor NOTE: Remember to COMMIT the changes
//Retrieve the Values written to shared preferences
int Value = sp.getInt("save", -1);
Log.w("LOG_TAG", "value: " + Value);
Intent value = new Intent(MainMenu.this, MainActivity.class);
startActivity(value);
}
});
play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
});
exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});//protected void onCreate(Bundle savedInstanceState)
}
}
This is the MainActivity
package com.example.gameversion2;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.XmlResourceParser;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
static final int NO_EXIT = -1;
static final int NUM_OF_ROOMS = 21;
Room[] countries;
Button north;
Button east;
Button south;
Button west;
Button save;
Button exit;
TextView textview;
ImageView flagimg;
int playerPos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTheCountries();
readXMLFile();
displayRooms();
setupControls();
setupImage();
// startGame();
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Log.w("TAG", "width = " + width + " height = " + height);
//Toast.makeText(getApplicationContext(), "w = " + width + " height = "+ height, Toast.LENGTH_LONG).show();
textview.setText(countries[playerPos].getDescription());
setupDirectionButtons();
} // protected void onCreate(Bundle savedInstanceState) {
// private void startGame() {
// Variables
//question = S.LoadGame();
//boolean running = true;
// textview.setText("Welcome to Escape The Country!");
// }
private void setupImage() {
ImageView imagePlayer;
ImageView imageRedbull;
imagePlayer = (ImageView)findViewById(R.id.imagePlayer);
imageRedbull = (ImageView)findViewById(R.id.imageRedbull);
imagePlayer.setImageResource(R.drawable.player);
imageRedbull.setImageResource(R.drawable.redbull);
}
public void setupDirectionButtons()
{
// north
if (countries[playerPos].getNorth() == -1 )
{
north.setEnabled(false);
}
else
{
north.setEnabled(true);
}
// east
if (countries[playerPos].getEast() == -1 )
{
east.setEnabled(false);
}
else
{
east.setEnabled(true);
}
// south
if (countries[playerPos].getSouth() == -1 )
{
south.setEnabled(false);
}
else
{
south.setEnabled(true);
}
// west
if (countries[playerPos].getWest() == -1 )
{
west.setEnabled(false);
}
else
{
west.setEnabled(true);
}
} // public void setupDirectionButtons()
public void setupControls()
{
north = (Button)findViewById(R.id.north);
east = (Button)findViewById(R.id.east);
south = (Button)findViewById(R.id.south);
west = (Button)findViewById(R.id.west);
textview = (TextView)findViewById(R.id.textView);
flagimg = (ImageView)findViewById(R.id.flagimg);
save = (Button)findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
SharedPreferences sp = getSharedPreferences("SAVEPOS", Context.MODE_PRIVATE);
//Load the Editor NOTE: Remember to COMMIT the changes
SharedPreferences.Editor e = sp.edit();
e.putInt("save", playerPos);
e.commit();
//Retrieve the Values written to shared preferences
int Value = sp.getInt("save", -1);
Log.w("LOG_TAG", "value: " + Value);
//imageview.setX(imageview.getX() + 10);
}
});
north.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getNorth();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
east.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getEast();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
south.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getSouth();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
west.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getWest();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
}
public void UpdateImage()
{
switch (playerPos)
{
case 0:
flagimg.setImageResource(R.drawable.canada);
break;
case 1 :
flagimg.setImageResource(R.drawable.norway);
break;
case 2 :
flagimg.setImageResource(R.drawable.sweden);
break;
case 3 :
flagimg.setImageResource(R.drawable.switzerland);
break;
case 4:
flagimg.setImageResource(R.drawable.australia);
break;
case 5 :
flagimg.setImageResource(R.drawable.finland);
break;
case 6 :
flagimg.setImageResource(R.drawable.newzealand);
break;
case 7 :
flagimg.setImageResource(R.drawable.denmark);
break;
case 8:
flagimg.setImageResource(R.drawable.netherland);
break;
case 9 :
flagimg.setImageResource(R.drawable.belgium);
break;
case 10 :
flagimg.setImageResource(R.drawable.ireland);
break;
case 11 :
flagimg.setImageResource(R.drawable.austria);
break;
case 12:
flagimg.setImageResource(R.drawable.uk);
break;
case 13 :
flagimg.setImageResource(R.drawable.italy);
break;
case 14 :
flagimg.setImageResource(R.drawable.germany);
break;
case 15 :
flagimg.setImageResource(R.drawable.japan);
break;
case 16 :
flagimg.setImageResource(R.drawable.spain);
break;
case 17:
flagimg.setImageResource(R.drawable.portugal);
break;
case 18 :
flagimg.setImageResource(R.drawable.france);
break;
case 19 :
flagimg.setImageResource(R.drawable.canada);
break;
case 20 :
flagimg.setImageResource(R.drawable.canada);
break;
}
}
public void initTheCountries() {
countries = new Room[NUM_OF_ROOMS];
for (int pos = 0; pos < NUM_OF_ROOMS; pos++)
{
countries[pos] = new Room();
}
} // public static void initTheCountries()
public void displayRooms() {
Log.w("display ROOM", "**************** start of display rooms ********************************");
for (int pos = 0; pos < NUM_OF_ROOMS; pos++)
{
Log.w("display ROOM", "North = " + countries[pos].getNorth());
Log.w("display ROOM", "East = " + countries[pos].getEast());
Log.w("display ROOM", "West = " + countries[pos].getWest());
Log.w("display ROOM", "South = " + countries[pos].getSouth());
Log.w("display ROOM", "Description = " + countries[pos].getDescription());
}
Log.w("display ROOM", "**************** end of display rooms **********************************");
} // public void displayRooms() {
public void readXMLFile() {
int pos = 0; // May be use this variable, to keep track of what position of the array of Room Objects.
try {
XmlResourceParser xpp = getResources().getXml(R.xml.countries);
xpp.next();
int eventType = xpp.getEventType();
int room_count = 0;
String elemtext = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String elemName = xpp.getName();
if (elemName.equals("countries")) {
String titleAttr = xpp.getAttributeValue(null,"title");
String authorAttr = xpp.getAttributeValue(null,"author");
} // if (elemName.equals("countries"))
if (elemName.equals("room")) {
room_count = room_count + 1;
}
if (elemName.equals("north")) {
elemtext = "north";
}
if (elemName.equals("east")) {
elemtext = "east";
}
if (elemName.equals("south")) {
elemtext = "south";
}
if (elemName.equals("west")) {
elemtext = "west";
}
if (elemName.equals("description")) {
elemtext = "description";
}
} // if (eventType == XmlPullParser.START_TAG)
// You will need to add code in this section to read each element of the XML file
// And then store the value in the current Room Object.
// NOTE: This method initTheCountries() creates and array of Room Objects, ready to be populated!
// As you can see at the moment the data/text is displayed in the LogCat Window
// Hint: xpp.getText()
else if (eventType == XmlPullParser.TEXT) {
if (elemtext.equals("north")) {
Log.w("ROOM", "north = " + xpp.getText());
countries[room_count-1].setNorth( Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("east")) {
Log.w("ROOM", "east = " + xpp.getText());
countries[room_count-1].setEast(Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("south")) {
Log.w("ROOM", "south = " + xpp.getText());
countries[room_count-1].setSouth(Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("west")) {
Log.w("ROOM", "west = " + xpp.getText());
countries[room_count-1].setWest(Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("description")) {
Log.w("ROOM", "description = " + xpp.getText());
countries[room_count-1].setDescription( xpp.getText() );
}
} // else if (eventType == XmlPullParser.TEXT)
eventType = xpp.next();
} // while (eventType != XmlPullParser.END_DOCUMENT)
} // try
catch (XmlPullParserException e) {
}
catch (IOException e) {
}
exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
} // public void readXMLFile()
} // public class MainActivity extends AppCompatActivity {
myapp

You are not passing the value to another activity.
Set it to intent like this:
int Value = sp.getInt("save", -1);
Log.w("LOG_TAG", "value: " + Value);
Intent value = new Intent(MainMenu.this, MainActivity.class);
value.putExtra("save", Value);
startActivity(value);
And in your MainActivity take the value using getIntent().getIntExtra().
Put it in your onCreate() method, after setContentView():
playerPos = getIntent().getIntExtra("save", 0);
and then use it to set player position.

Related

while retreiving contacts again on onResume, last contact is re-added on first card in recycler view

I do not understand why last contact is added to the first card in recyclerview again when activity is resumed. I know that it is to do with cursor or content resolver.
Here is the java class with which I have problem.
while retreiving contacts again on onResume, last contact is re-added on first card in recycler view
package com.android.eventers;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberType;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.util.ArrayList;
import java.util.Locale;
public class ContactsActivity extends AppCompatActivity implements ContactsAdapter.ListItemClickListener {
private static final int CHECK_CLICK = 1;
private static final String LIST_STATE_KEY = "list_state";
FloatingActionButton mFloatingActionButton;
RecyclerView mRecyclerView;
ContactsAdapter mAdapter;
String contactName;
String mobileNumber;
String mobileNumberSelected;
Contacts contactsObject;
TextView noItem;
private ArrayList<Contacts> contactsArrayList;
ArrayList<String> tempList;
private Parcelable mListState;
private LinearLayoutManager mLayoutManager;
SharedPreferences mSharedPreferences;
SharedPreferences.Editor mEditor;
private boolean mCalledFromOncreate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mCalledFromOncreate = true;
noItem = (TextView) findViewById(R.id.no_listitem_in_contacts);
noItem.setVisibility(View.GONE);
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.add_fab_in_main);
contactsArrayList = new ArrayList<Contacts>();
mSharedPreferences = getPreferences(Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
launchConacts();
for (int i = 0; i < contactsArrayList.size(); i++) {
Log.e("name:", "" + contactsArrayList.get(i).getName());
for (int j = 0; j < contactsArrayList.get(i).getMobileNumber().size(); j++) {
Log.e("num:", contactsArrayList.get(i).getMobileNumber().get(j));
}
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = "";
int counter = 0;
for (int i = 0; i < contactsArrayList.size(); i++) {
Contacts singleContact = contactsArrayList.get(i);
if (contactsArrayList.get(i).getFlag()) {
data = data + "\n" + singleContact.getName().toString() + " " + singleContact.getSelectedMobileNumber();
counter++;
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), true);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
} else {
mEditor.putBoolean("checkbox_" + contactsArrayList.get(i).getName(), false);
mEditor.putString("selected_mobile_number_for_" + contactsArrayList.get(i).getName(), "" + singleContact.getSelectedMobileNumber());
}
}
mEditor.commit();
Toast.makeText(ContactsActivity.this, "Selected contacts: \n" + data, Toast.LENGTH_LONG).show();
Intent intent = new Intent(ContactsActivity.this, ReportActivity.class);
intent.putExtra("TOTAL_KEY", contactsArrayList.size() + "");
intent.putExtra("SELECTED_KEY", counter + "");
startActivity(intent);
}
});
}
#Override
public void onListItemClick(final int clickedItemIndex, int whichClick) {
switch (whichClick) {
case CHECK_CLICK: {
//Toast.makeText(ContactsActivity.this, "Clicked on Checkbox: "+clickedItemIndex , Toast.LENGTH_SHORT).show();
int selectedMobileNumberPosition = 0;
String selectedMobileNumber = contactsArrayList.get(clickedItemIndex).getSelectedMobileNumber();
if (contactsArrayList.get(clickedItemIndex).getMobileNumber().size() > 1) {
final String items[] = new String[contactsArrayList.get(clickedItemIndex).getMobileNumber().size()];
for (int j = 0; j < contactsArrayList.get(clickedItemIndex).getMobileNumber().size(); j++) {
items[j] = contactsArrayList.get(clickedItemIndex).getMobileNumber().get(j);
if (items[j].contains(selectedMobileNumber)) {
selectedMobileNumberPosition = j;
}
}
AlertDialog levelDialog;
// Creating and Building the Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please select the mobile number");
builder.setSingleChoiceItems(items, selectedMobileNumberPosition, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mobileNumberSelected = items[item];
contactsArrayList.get(clickedItemIndex).setSelectedMobileNumber(mobileNumberSelected);
// levelDialog.dismiss();
}
});
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// Toast.makeText(ContactsActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
}
});
levelDialog = builder.create();
levelDialog.show();
}
break;
}
}
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
// Save list state
mListState = mLayoutManager.onSaveInstanceState();
state.putParcelable(LIST_STATE_KEY, mListState);
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
// Retrieve list state and list/item positions
if (state != null)
mListState = state.getParcelable(LIST_STATE_KEY);
}
#Override
protected void onResume() {
super.onResume();
if (!mCalledFromOncreate) {
contactsArrayList.clear();
launchConacts();
mAdapter.notifyDataSetChanged();
Log.e("Inside", "onResume after clear");
}
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
void launchConacts() {
//Cursor pho = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE NOCASE ASC");
Log.i("Size is "," "+phones.getCount());
if (phones != null && (phones.getCount() > 0)) {
phones.moveToFirst();
phones.move(0);
for (int i = 0; i < phones.getCount(); i++) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumberStr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
PhoneNumber phoneNumber = phoneNumberUtil.parse(phoneNumberStr, Locale.getDefault().getCountry());
PhoneNumberUtil.PhoneNumberType phoneNumberType = phoneNumberUtil.getNumberType(phoneNumber);
if (phoneNumberType == PhoneNumberType.MOBILE) {
if (name.equals(contactName)) {
phoneNumberStr = phoneNumberStr.replaceAll(" ", "");
if (phoneNumberStr.contains(mobileNumber)) {
} else {
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
if (!tempList.contains(mobileNumber)) {
// Log.e("phone: ", " " + phoneNumber);
contactsObject.setMobileNumber(mobileNumber);
tempList.add(mobileNumber);
}
}
} else {
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added", contactsObject.getName());
}
contactsObject = new Contacts();
tempList = new ArrayList<String>();
contactName = name;
mobileNumber = String.valueOf(phoneNumber.getNationalNumber());
tempList.add(mobileNumber);
// Log.e("name: ", " " + name);
// Log.e("phone: ", " " + mobileNumber);
contactsObject.setName(name);
contactsObject.setMobileNumber(mobileNumber);
contactsObject.setFlag(mSharedPreferences.getBoolean("checkbox_" + name, false));
contactsObject.setSelectedMobileNumber(mSharedPreferences.getString("selected_mobile_number_for_" + name, mobileNumber));
}
}
} catch (Exception e) {
} finally {
}
if (phones.isLast()) {
contactsArrayList.add(contactsObject);
// Log.e("object added last>>>>>", contactsObject.getName());
}
phones.moveToNext();
}
//phones.close();
}
mRecyclerView = (RecyclerView)
findViewById(R.id.recycler_view_in_contacts);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new
LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new
ContactsAdapter(contactsArrayList, ContactsActivity.this);
mRecyclerView.setAdapter(mAdapter);
if (contactsArrayList.size() == 0)
{
noItem.setVisibility(View.VISIBLE);
}
}
#Override
protected void onPause() {
super.onPause();
mCalledFromOncreate = false;
}
}
Here is what I found which is adding one more item in your list
Try removing:
if (contactsObject != null) {
contactsArrayList.add(contactsObject);
Log.e("object added : ", contactsObject.getName);
}
Hope this helps.

Open a actvity when a if statement comes true

Hi I want to open a activity when a if statement comes true. like "if gameStatus are equal to 12, then open scoreActivity". The Code:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import java.util.Random;
import android.os.Build;
import android.os.Handler;
public class Game6x4Activity extends AppCompatActivity implements View.OnClickListener {
private int numberOfElements;
private int[] buttonGraphicLocations;
private MemoryButton selectedButton1;
private MemoryButton selectedButton2;
private boolean isBusy = false;
public int gameStatus;
public int gameScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_mode);
gameScore = 0;
gameStatus = 0;
GridLayout gridLayout = (GridLayout)findViewById(R.id.grid_layout_6x4);
int numColumns = gridLayout.getColumnCount();
int numRow = gridLayout.getRowCount();
numberOfElements = numColumns * numRow;
MemoryButton[] buttons = new MemoryButton[numberOfElements];
int[] buttonGraphics = new int[numberOfElements / 2];
buttonGraphics[0] = R.drawable.card1;
buttonGraphics[1] = R.drawable.card2;
buttonGraphics[2] = R.drawable.card3;
buttonGraphics[3] = R.drawable.card4;
buttonGraphics[4] = R.drawable.card5;
buttonGraphics[5] = R.drawable.card6;
buttonGraphics[6] = R.drawable.card7;
buttonGraphics[7] = R.drawable.card8;
buttonGraphics[8] = R.drawable.card9;
buttonGraphics[9] = R.drawable.card10;
buttonGraphics[10] = R.drawable.card11;
buttonGraphics[11] = R.drawable.card12;
buttonGraphicLocations = new int[numberOfElements];
shuffleButtonGraphics();
for(int r=0; r < numRow; r++)
{
for(int c=0; c <numColumns; c++)
{
MemoryButton tempButton = new MemoryButton(this, r, c, buttonGraphics[buttonGraphicLocations[r * numColumns + c]]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
tempButton.setId(View.generateViewId());
}
tempButton.setOnClickListener(this);
buttons[r * numColumns + c] = tempButton;
gridLayout.addView(tempButton);
}
}
}
protected void shuffleButtonGraphics(){
Random rand = new Random();
for (int i=0; i < numberOfElements; i++)
{
buttonGraphicLocations[i] = i % (numberOfElements / 2);
}
for (int i=0; i < numberOfElements; i++)
{
int temp = buttonGraphicLocations[i];
int swapIndex = rand.nextInt(16);
buttonGraphicLocations[i] = buttonGraphicLocations[swapIndex];
buttonGraphicLocations[swapIndex] = temp;
}
}
private int buttonGraphicLocations(int i) {
return 0;
}
#Override
public void onClick(View view) {
if(isBusy) {
return;
}
MemoryButton button = (MemoryButton) view;
if(button.isMatched) {
return;
}
if(selectedButton1 == null)
{
selectedButton1 = button;
selectedButton1.flip();
return;
}
if(selectedButton1.getId()== button.getId())
{
return;
}
if (selectedButton1.getFrontDrawableId()== button.getFrontDrawableId())
{
button.flip();
button.setMatched(true);
if (selectedButton1 != null) {
selectedButton1.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
if (selectedButton2 != null) {
selectedButton2.setEnabled(false);
System.out.println("not null");
}
else{
System.out.println("null");
}
gameStatus = gameStatus + 1;
gameScore = gameScore + 10;
if (gameStatus == 12){
Intent it = new Intent(Game6x4Activity.this, ActivityScore.class);
startActivity(it);
}
selectedButton1 = null;
return;
}
else
{
selectedButton2 = button;
selectedButton2.flip();
isBusy = true;
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run(){
selectedButton2.flip();
selectedButton1.flip();
selectedButton1 = null;
selectedButton2 = null;
isBusy = false;
}
},500);
return;
}
}
}
The activity that i want to open will show to the player his score. the activity is equal to all game modes, there will be some test to the app understant what path should go on. test like this one:
"
if (gameStatus == 12) {
gameScore = gameScore*55;
TextView scoreText = (TextView) findViewById(R.id.textView8);
scoreText.setText(gameScore);
}
else if (gameStatus == 15){
"
There are 4 game modes: This is the 6x4 game, where we can find 24 cards (12 images).
else if (gameStatus == 15){
Intent intent = new Intent(Game6x4Activity.this, NextActivity.class);
startActivity(intent);
}
I think, you are asking for this. You can pass value to another activity with
intent.putExtra("key",desired value);

calculator with one input edittext android

i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}

Alert Dialog not popping right. Button causing exception. Unsure why

Nearly everything works in a program I've been working on. As I make changes in the UI, everything is set correctly. For reasons I can't figure out, when I hit the enter button of my main UI the app force closes with an exception. From the log...
java.lang.IllegalStateException: Could not find a method enterMood(View) in the activity class com.loch.meaptracker.MainActivity for onClick handler on view class android.widget.Button with id 'enterButtonID'
Here's the program code. Eclipse doesn't flag anything for either errors or warnings. I'm at a bit of a loss and pretty burnt out looking at this. Any help would be greatly appreciated.
package com.loch.meaptracker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
private SeekBar happyBar, energyBar, anxietyBar, painBar;
private EditText noteField;
private DatePicker dPick;
private TimePicker tPick;
#SuppressWarnings("unused")
private Button enterButton;
private int happyValue = 4, energyValue = 4, anxietyValue = 4,
painValue = 4;
private static final String TAG = "heapApp";
private String Mood = "Blah";
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bars
happyBar = (SeekBar) findViewById(R.id.happinessBarID);
happyBar.setOnSeekBarChangeListener(this);
energyBar = (SeekBar) findViewById(R.id.energyBarID);
energyBar.setOnSeekBarChangeListener(this);
anxietyBar = (SeekBar) findViewById(R.id.anxietyBarID);
anxietyBar.setOnSeekBarChangeListener(this);
painBar = (SeekBar) findViewById(R.id.painBarID);
painBar.setOnSeekBarChangeListener(this);
// end bars
dPick = (DatePicker) findViewById(R.id.datePicker1);
tPick = (TimePicker) findViewById(R.id.timePicker1);
noteField = (EditText) findViewById(R.id.noteTextFieldID);
enterButton = (Button) findViewById(R.id.enterButtonID);
} catch (Exception onCreateException) {
Log.e(TAG, "Exception received", onCreateException);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Bar listener methods
#Override
public void onProgressChanged(SeekBar arg0, int barValue, boolean hFromUser) {
try {
switch (arg0.getId()) {
case R.id.happinessBarID:
happyValue = barValue + 1;
break;
case R.id.energyBarID:
energyValue = barValue + 1;
break;
case R.id.anxietyBarID:
anxietyValue = barValue + 1;
break;
case R.id.painBarID:
painValue = barValue + 1;
break;
}
String debugBarValue = "Happy is " + happyValue + ", Energy is "
+ energyValue + ", Anxiety is " + anxietyValue
+ ", Pain is " + painValue + ".";
System.out.println(debugBarValue);
} catch (Exception BarValueException) {
Log.e(TAG, "Exception received", BarValueException);
}
}
#Override
public void onStartTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
// end Bar listener methods
// Enter Button listener Method
public void dialogPop(View v) {
try {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set Title
alertDialogBuilder.setTitle("title");
// set dialog message
alertDialogBuilder.setMessage("You entered: " + getMood())
.setCancelable(false).setPositiveButton("Okay",
// When Okay button clicked the write mood string to file
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
try {
// This is the string that should be
// written to file
String data = getMood();
// This is the file that should be
// written to
File heapFile = new File("heapFile.csv");
// if file doesn't exists, then create
// it
if (!heapFile.exists()) {
heapFile.createNewFile();
}
// true = append file
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
BufferedWriter heapBufferWritter = new BufferedWriter(
heapFileWritter);
heapBufferWritter.write(data);
heapBufferWritter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
})
// If they press either the cancel button or the back button
// on their device (Same thing) then close the dialog and
// give the user a chance to change what they've entered
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} catch (Exception buttonListenerException) {
Log.e(TAG, "Exception received", buttonListenerException);
}
return;
}
public String getMood() {
try {
int month = dPick.getMonth();
int day = dPick.getDayOfMonth();
int year = dPick.getYear();
int minute = tPick.getCurrentMinute();
String moodAntePost = "AM";
boolean hourType = tPick.is24HourView();
int moodHour = tPick.getCurrentHour();
if (hourType == false && moodHour > 12) {
moodHour = (moodHour - 12);
moodAntePost = "PM";
} else if (hourType == false && moodHour <= 0) {
moodHour = 12;
} else {
}
String noteText = noteField.getText().toString();
Mood = "Happiness," + happyValue + ",Energy," + energyValue
+ ",Anxiety," + anxietyValue + ",Pain," + painValue
+ ",Date," + month + "/" + day + "/" + year + ",Time,"
+ moodHour + ":" + minute + "," + moodAntePost + ",Note,"
+ noteText;
System.out.println(Mood);
} catch (Exception getMoodException) {
Log.e(TAG, "Exception received", getMoodException);
}
return Mood;
}
}
Please check the XML code . i think there in tag of your XML there is one attribute you have added android:onClick="enterMood".... try removing it and running it
use
android:onClick="dialogPop" instead
Your click handler is not in the right format. It needs to include a view parameter for the XML click handler to work properly.
public void getMood(View view){
}

Activity State not saved

I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()

Categories

Resources