I Have an app in which the main activity shows a question and has true button false button and cheat button
When user press the correct option, listener will Toast Correct.. and otherwise listener will Toast Incorrect
Now when we press the cheat button new activity is launched and has a textview "Are you sure you want to cheat?", another textview which is blank and a show answer button..
When user presses the show answer button , the blank text view is set to the answer of the question (as asked in the main activity)
And when the user goes back the true and false button onClickListeners are now set to make a toast "Cheating is wrong"
i have declared a boolean value which is set to false, the boolean value is set to True and i save it in the bundle so that when the user rotates the screen , the value of the variable is not overwritten on onCreate(..) method being recalled..
I tried debugging with break points in eclipse , the value is not overridden still on main activity "Cheating is wrong" doesnt show up , it shows Correct or Incorrect..
QuizActivity : Launcher Activity
CheatActivity: Activity launched on onCreate
TrueFalse activity : creating array of objects with fields (question and answer)
Following is the code : QuizActivity.java (Launcher activity)
package com.mhrsolanki2020.geoquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton, mFalseButton, mNextButton, mCheatButton;
private TextView mQuestionTextView;
private static final String KEY_INDEX = "index";
private static final String TAG = "QuizActivity";
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true) };
private int mCurrentIndex = 0;
private boolean mIsCheater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
mIsCheater=false;
}
});
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answer = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answer);
startActivityForResult(i, 0);
}
});
if (savedInstanceState != null)
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater) {
messageResId = R.string.judgement_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
} else {
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN,
false);
Log.d(TAG, "Value of mIsCheater : " + mIsCheater);
}
}
}
The following is the code : CheatActivity.java
package com.mhrsolanki2020.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.mhrsolanki2020.geoquiz.anwer_is_true ";
public static final String EXTRA_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_shown";
public static final String EXTRA_IS_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_is_shown";
boolean mCorrectAnswer;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mIsAnswerShown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mCorrectAnswer = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE,
false);
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
if (savedInstanceState != null) {
mIsAnswerShown = savedInstanceState.getBoolean(
EXTRA_IS_ANSWER_SHOWN, false);
} else {
mIsAnswerShown = false;
}
mShowAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mCorrectAnswer) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
}
});
}
public void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
mIsAnswerShown = isAnswerShown;
data.putExtra(EXTRA_ANSWER_SHOWN, mIsAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(EXTRA_IS_ANSWER_SHOWN, mIsAnswerShown);
}
}
Following is the code : TrueFalse.java
package com.mhrsolanki2020.geoquiz;
public class TrueFalse {
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}
http://developer.android.com/guide/topics/resources/runtime-changes.html check this link
For orientation support do this in manifest.xml
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
In Class file, override the onSaveInstanceState(Bundle outState).
Related
I am following some coding tutorials from The Big Nerd Ranch book for Android, 2nd edition. I have followed all examples, but i cannot get the judgment_toast to show in my QuizActivity.java file. Also when pressing back on the the application does not go back to the main question screen.
Please see all my code from all 3 classes below.....any help is much appreciated.
package uk.co.sbworrallgmail.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final int REQUEST_CODE_CHEAT = 0;
private boolean mIsCheater;
private Button mTrueButton;
private Button mFalseButton;
private Button mCheatButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private TextView mQuestionTextView;
private int mCurrentIndex = 0;
private Question[] mQuestionsBank = new Question[]{
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionsBank.length;
mIsCheater = false;
updateQuestion();
}
});
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex -1) % mQuestionsBank.length;
updateQuestion();
}
});
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Start CheatActivity
boolean answerIsTrue = mQuestionsBank[mCurrentIndex].isAnswerTrue();
Intent intent = CheatActivity.newIntent(QuizActivity.this, answerIsTrue);
startActivityForResult(intent, REQUEST_CODE_CHEAT);
}
});
mQuestionTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionsBank.length;
updateQuestion();
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
}
private void updateQuestion() {
int question = mQuestionsBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionsBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (mIsCheater) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_CHEAT) {
if (data == null) {
return;
}
mIsCheater = CheatActivity.wasAnswerShown(data);
}
}
}
and my CheatActivity.java file
package uk.co.sbworrallgmail.geoquiz;
import android.content.Context;
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.TextView;
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE = "uk.co.sbworrallgmail.geoquiz.answer_is_true";
private static final String EXTRA_ANSWER_IS_SHOWN = "uk.co.sbworrallgmail.geoquiz.answer_is_shown";
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answer_Text_View);
mShowAnswer = (Button) findViewById(R.id.show_Answer_Button);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
}
});
}
public static Intent newIntent(Context packageContext, boolean answerIsTrue) {
Intent intent = new Intent(packageContext, CheatActivity.class);
intent.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return intent;
}
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_IS_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
public static boolean wasAnswerShown(Intent result) {
return result.getBooleanExtra(EXTRA_ANSWER_IS_SHOWN, false);
}
}
and my Question.java file
package uk.co.sbworrallgmail.geoquiz;
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
public void setTextResId(int textResId) {
mTextResId = textResId;
}
public void setAnswerTrue(boolean answerTrue) {
mAnswerTrue = answerTrue;
}
public int getTextResId() {
return mTextResId;
}
public boolean isAnswerTrue() {
return mAnswerTrue;
}
public Question(int textResId, boolean answerTrue) {
mTextResId = textResId;
mAnswerTrue = answerTrue;
}
}
and my Manifest file as requested:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="uk.co.sbworrallgmail.geoquiz">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".QuizActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CheatActivity"
android:label="#string/title_activity_cheat"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
How is your activity set up for the back button? Show your manifest.
However...
Your toast is not working, more than likely, because the Toast takes a String value for the second param, you are giving it an int....
Try this instead.
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionsBank[mCurrentIndex].isAnswerTrue();
String messageResId = "";
if (mIsCheater) {
messageResId = getResources().getString(R.string.judgment_toast);
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = getResources().getString(R.string.correct_toast);
} else {
messageResId = getResources().getString(R.string.incorrect_toast);
}
}
Toast.makeText(QuizActivity.this, messageResId, Toast.LENGTH_SHORT).show();
}
I fixed the issue with the back button not working as expected by making a change to the Manifest.xml file:
<activity
android:name=".CheatActivity"
android:label="#string/title_activity_cheat"
android:theme="#style/AppTheme">
</activity>
I changed the theme to match the theme of the parent application and now the back button works as expected.
Also the issue with the toasts is now working. It was my expectation of what the application should be doing that was incorrect.
I have a button "add" which adds input text from the editText into a listview below. However, can I make it possible to add text to the created list by simply pressing enter? If so, how can i do that in a simple manner?
Name=edittext, list =listview
#Override
public void onClick(View view) {
String name = Name.getText().toString();
if (Name.length() > 0) {
list.add(name);
adapter.notifyDataSetChanged();
}
}
Quoted from : https://www.stackoverflow.com/a/6832095
Here is what you need to do to capture Enter event on editText :
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
You need to overwrite your dispatchKeyEvent something like this
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
Toast.makeText(UITestsActivity.this,
"YOU CLICKED ENTER KEY",
Toast.LENGTH_LONG).show();
return true;
}
return super.dispatchKeyEvent(e);
};
Too long for a comment, therefore adding an answer. Building over previous answer, to achieve your function use this code:
import android.app.LauncherActivity;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.view.KeyEvent;
import java.util.ArrayList;
public class LoginPage extends AppCompatActivity {
EditText Name;
Button Add;
ListView Lv;
Button Reset;
Button Sgame;
private ImageView information;
private PopupWindow popupWindow;
private LayoutInflater layoutInflater;
private RelativeLayout relativeLayout;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
Name = (EditText) findViewById(R.id.Playername);
Add = (Button) findViewById(R.id.Addbutton);
Lv = (ListView) findViewById(R.id.list);
Reset = (Button) findViewById(R.id.Resetbutton);
Sgame = (Button) findViewById(R.id.Startgamebutton);
information = (ImageView) findViewById(R.id.info);
relativeLayout = (RelativeLayout) findViewById(R.id.constrain);
adapter = new ArrayAdapter<String>(this, R.layout.listviewlayout, R.id.list_content, list);
Lv.setAdapter(adapter);
final EditText Name = (EditText) findViewById(R.id.Playername);
class MyKeyListener implements View.OnKeyListener {
#Override
public boolean onKey (View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
String name = Name.getText().toString();
if (Name.length() > 0) {
list.add(name);
adapter.notifyDataSetChanged();
}
return true;
}
return false;
}
}
Name.setOnKeyListener(new MyKeyListener());
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = Name.getText().toString();
if (Name.length() > 0) {
list.add(name);
adapter.notifyDataSetChanged()
;
}
}
});
Reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list.clear();
}
});
Sgame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!list.isEmpty())
openActivity2();
}
});
information.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.informationpopup, null);
popupWindow = new PopupWindow(container, 1150, 2000, true);
popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY, 140, 300);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return true;
}
});
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, Gamescreen.class);
String s= list.get(0);
intent.putExtra("Name1", s);
startActivity(intent);
}}
package com.example.abdoanany.sqliteapp;
import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editSurname,editMarks ,editTextId;
Button btnAddData;
Button btnviewAll;
Button btnDelete;
Button btnviewUpdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editSurname = (EditText)findViewById(R.id.editText_surname);
editMarks = (EditText)findViewById(R.id.editText_Marks);
editTextId = (EditText)findViewById(R.id.editText_id);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
btnviewUpdate= (Button)findViewById(R.id.button_update);
btnDelete= (Button)findViewById(R.id.button_delete);
AddData();
viewAll();
UpdateData();
DeleteData();
}
public void DeleteData() {
btnDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer deletedRows = myDb.deleteData(editTextId.getText().toString());
if(deletedRows > 0)
Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Deleted", Toast.LENGTH_LONG).show();
}
}
);
}
public void UpdateData() {
btnviewUpdate.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isUpdate = myDb.updateData(editTextId.getText().toString(),
editName.getText().toString(),
editSurname.getText().toString(),editMarks.getText().toString());
if(isUpdate == true)
Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();
}
}
);
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editName.getText().toString(),
editSurname.getText().toString(),
editMarks.getText().toString() );
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Id :"+ res.getString(0)+"\n");
buffer.append("Name :"+ res.getString(1)+"\n");
buffer.append("Surname :"+ res.getString(2)+"\n");
buffer.append("Marks :"+ res.getString(3)+"\n\n");
}
// Show all data
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
#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);
}
}
If Project - Clean or/and Project - Rebuild would not help, most probable reason, that you somewhere made error in xml files.
In that case check all your xml, maybe you lost some resource or something.
So i got my firstScreen that i want to be shown just on the first app use.
and i have my mainActivity which will follow the firstScreen.
Im only starting with android and i don't want to use the solutions brought in here: How to launch activity only once when app is opened for first time? AND Can I have an android activity run only on the first time an application is opened? because i dont know SharedPreferrences yet.
So how can i achieve that using Boolean flags?
I have got:boolean firstTimeUse = false; In my firstScreenActivity
And when i start myMainActivity i set the flag to true;
firstTimeUse = true;
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
The problem is the MainActivity doesn't recognize the Boolean variable.
Am i doing it wrong? Or i can still make some modifications and do it with flags?
EDIT
FirstScreen.java:
package com.example.predesignedmails;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class FirstScreen extends AppCompatActivity
{
TextView welcomeTextTextView;
String welcomeText;
ImageButton goToMainImageButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_screen);
viewsInitialization();
welcomeText = "Welcome to Pre Designed Mails.\n"
+ "In here you will have a tons of Emails templates for about every purpose you will need.\n"
+ "Just fill the small details and click Send.\n\n"
+ "Send E-mails fast and efficient!";
welcomeTextTextView.setText(welcomeText);
welcomeTextTextView.setMovementMethod(new ScrollingMovementMethod());
goToMainImageButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume()
{
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true))
{
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
// First launch code
Log.d("FirstLaunchCheckUp","First Launch");
}
}
private void viewsInitialization()
{
welcomeTextTextView = (TextView) findViewById(R.id.welcome_text_text_view_id);
goToMainImageButton = (ImageButton) findViewById(R.id.go_to_main_button_id);
}
}
The onResume() method i added manually. It wasn't added automatically when i crated a new activity in Eclipse.
MainActivity.java:
package com.example.predesignedmails;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
Button hatefullMailButton;
Button loveMailsButton;
Button welcomeScreenButton;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().getDecorView().setBackgroundColor(getResources().getColor(R.color.main_activity_background_color)); // Setting background color
viewsInitialization();
hatefullMailButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,HatefulMailsActivity.class);
startActivity(intent);
}
});
loveMailsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,LoveMailsActivity.class);
startActivity(intent);
}
});
welcomeScreenButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,FirstScreen.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void viewsInitialization()
{
hatefullMailButton = (Button) findViewById(R.id.hateful_email_button_id);
loveMailsButton = (Button) findViewById(R.id.love_email_button_id);
welcomeScreenButton = (Button) findViewById(R.id.welcome_screen_button_id);
}
}
In your Activity
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getBoolean(this, SettingsManager.FIRST_LAUNCH, true)){
SettingsManager.saveBoolean(this, SettingsManager.FIRST_LAUNCH, false);
//your first launch code
}
}
SharedPreference helper class
public class SettingsManager
{
public static final String FIRST_LAUNCH= "first_lauch";
public static String getString(Context context, String key, String defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key, defValue);
}
public static int getInt(Context context, String key, int defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getInt(key, defValue);
}
public static boolean getBoolean(Context context, String key, boolean defValue) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(key, defValue);
}
public static void saveString(Context context, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).commit();
}
public static void saveInt(Context context, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(key, value).commit();
}
public static void saveBoolean(Context context, String key, boolean value) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(key, value).commit();
}
}
For the future you can write more simple methods on this SettingsManager, like
public static int getFirstLaunch(Context context) {
return getBoolean(context, FIRST_LAUNCH, true);
}
public static int saveFirstLaunch(Context context, boolean value) {
return saveBoolean(context, FIRST_LAUNCH, value);
}
And use it like
#Override
protected void onResume() {
super.onResume();
if (SettingsManager.getFirstLaunch(this)){
SettingsManager.saveFirstLaunch(this, false);
//your first launch code
}
}
The reason why firstScreen does not recognize boolean firstTimeUse in mainActivity is because it does not yet exist. Only after you have executed the line startActivity(intent) will there exist an object of class mainActivity. Basically, you cannot set a boolean on something that does not yet exist.
Instead, what you can do is pass extra information to an activity that is to be started. When the just-started-activity is initializing itself it can read the extra information and act on it.
So build your intent for the activity you want to start and also set extra information in the 'extras':
Intent intent = new Intent(FirstScreen.this,MainActivity.class);
intent.putExtra("firstTimeUse", true);
startActivity(intent);
Now for your MainActivity to know the value of firstTimeUse it must read the extras:
public class MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstTimeUse = getIntent().getBooleanExtra("firstTimeUse", false);
// do processing dependent on whether it's the first time or not
}
}
This should solve your problem of "the MainActivity doesn't recognize the Boolean variable".
So I just started programming, but I dont really get the method OnClickListener. I already google the error I have: "The type new View.OnClickListener(){} must implement the inherited abstract method View.OnClickListener.OnClick(View)" and I tried to change some things in my code, but it still doens't work. Can anyone tell me exactly what I need to change in my code? Thanks in advance.
MainMenuScreen.java:
package com.wouter.testjk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainMenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_menu);
//error on the line below
((Button) findViewById(R.id.one_player)).setOnClickListener(new OnClickListener() { //the error is here
public void onClick(View V) {
Log.d("DEBUG", "One Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", true);
startActivityForResult(intent, 0);
}
});
((Button) findViewById(R.id.two_player)).setOnClickListener(new OnClickListener() {
public void onClick(View V) {
Log.d("DEBUG", "Two Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", false);
startActivityForResult(intent, 0);
}
});
((Button) findViewById(R.id.exit_game)).setOnClickListener(new OnClickListener() {
public void onClick(View V) {
Log.d("DEBUG", "Exit Game Button Pressed!");
MainMenuScreen.this.finish();
}
});
}
}
MainActivity.java:
package com.wouter.testjk;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.wouter.testjk.R;
public class MainActivity extends Activity implements OnClickListener{
private TicTacToeGame mGame;
private Button mBoardButtons[];
private TextView mInfoTextView;
private TextView mPlayeroneCount;
private TextView mTieCount;
private TextView mPlayertwoCount;
private TextView mPlayeroneText;
private TextView mPlayertwoText;
private int mPlayeroneCounter = 0;
private int mTieCounter = 0;
private int mPlayertwoCounter = 0;
private boolean mPlayeroneFirst = true;
private boolean mIsSinglePlayer = false;
private boolean mIsPlayerOneTurn = true;
private boolean mGameOver = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
boolean mGameType = getIntent().getExtras().getBoolean("gametype");
mBoardButtons = new Button[mGame.getBOARD_SIZE()];
mBoardButtons[0] = (Button) findViewById(R.id.one);
mBoardButtons[1] = (Button) findViewById(R.id.two);
mBoardButtons[2] = (Button) findViewById(R.id.three);
mBoardButtons[3] = (Button) findViewById(R.id.four);
mBoardButtons[4] = (Button) findViewById(R.id.five);
mBoardButtons[5] = (Button) findViewById(R.id.six);
mBoardButtons[6] = (Button) findViewById(R.id.seven);
mBoardButtons[7] = (Button) findViewById(R.id.eight);
mBoardButtons[8] = (Button) findViewById(R.id.nine);
Button mTen = (Button) findViewById(R.id.ten);
mTen.setOnClickListener(this);
Button mEleven = (Button) findViewById(R.id.eleven);
mEleven.setOnClickListener(this);
mInfoTextView = (TextView) findViewById(R.id.information);
mPlayeroneCount = (TextView) findViewById(R.id.humancount);
mTieCount = (TextView) findViewById(R.id.tiesCount);
mPlayertwoCount = (TextView) findViewById(R.id.androidCount);
mPlayeroneText = (TextView) findViewById(R.id.human);
mPlayertwoText = (TextView) findViewById(R.id.android);
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mTieCount.setText(Integer.toString(mTieCounter));
mPlayeroneCount.setText(Integer.toString(mPlayertwoCounter));
mGame = new TicTacToeGame();
startNewGame(mGameType);
}
private void startNewGame(boolean isSingle)
{
//some code here
}
private class ButtonClickListener implements View.OnClickListener
{
int location;
public ButtonClickListener(int location)
{
this.location = location;
}
#Override
public void onClick(View view) {
if (!mGameOver)
{
if(mBoardButtons[location].isEnabled())
{
if(mIsSinglePlayer)
{
setMove(mGame.PLAYER_ONE, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
winner = mGame.checkForWinner();
}
if (winner == 0)
mInfoTextView.setText(R.string.turn_human);
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner ==2)
{
mInfoTextView.setText(R.string.result_human_wins);
mPlayeroneCounter++;
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mGameOver = true;
}
else if (winner ==3)
{
mInfoTextView.setText(R.string.result_android_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
else
{
if(mIsPlayerOneTurn)
{
setMove(mGame.PLAYER_ONE, location);
}
else
{setMove(mGame.PLAYER_TWO, location);
}
int winner = mGame.checkForWinner();
if (winner == 0)
{
if(mIsPlayerOneTurn)
{
mInfoTextView.setText(R.string.turn_player_two);
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_one);
mIsPlayerOneTurn = true;
}
}
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner ==2)
{
mInfoTextView.setText(R.string.player_one_wins);
mPlayeroneCounter++;
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mGameOver = true;
}
else if (winner ==3)
{
mInfoTextView.setText(R.string.player_two_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
}
}
}
}
private void setMove(char player, int location)
{
mGame.setMove(player,location);
mBoardButtons[location].setEnabled(false);
mBoardButtons[location].setText(String.valueOf(player));
if (player == mGame.PLAYER_ONE)
mBoardButtons[location].setTextColor(Color.GREEN);
else
{
mBoardButtons[location].setTextColor(Color.RED);
}
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.ten:
startNewGame(mIsSinglePlayer);
return;
case R.id.eleven:
MainActivity.this.finish();
return;
}
}
}
Sounds like a project error. First follow good code guidelines.
When overriding a method (e.g. onClick) add an #Override annotation before it. This will make the compiler yell, if such method doesn't exist.
Specify which class your interface belongs to by using View.OnClickListener.
Button already is a View, no need to cast it just to set a OnClickListener.
Here's what it might look like:
// No need to cast it to a button here, as it
findViewById(R.id.one_player).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("DEBUG", "One Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", true);
startActivityForResult(intent, 0);
}
});
Lastly clean/rebuild your project as this error doesn't occur to me when using your code.
OnClickListener is an interface that defines the method void onClick(View v). Adding the implements OnClickListener to you Activity class means that that class implements the interface and thus must have that onClick(View view) method. This is mainly done so that you can pass this on places an OnClickListener is needed and which you also did.
But, as you coded it, you should remove the implements OnClickListenerpart from your Activity and instead pass instances of your ButtonClickListener class as OnClickListeners to your buttons like so:
Button mTen = (Button) findViewById(R.id.ten);
mTen.setOnClickListener(new ButtonClickListener(10)); /* 10 is just a guess */
Button mEleven = (Button) findViewById(R.id.eleven);
mEleven.setOnClickListener(new ButtonClickListener(11)); /* 11 is just a guess */