Switch and Case to make button visible - android

This is a source code with switch case code. But the bold part was didn't work. I try to make "next" to be visible after press buttonD, buttonO and buttonG. FYI, "next" is a button. So it use three condition to make one command. How it can be work? Am I put that code in wrong place?
package com.example.fun;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
public class DogActivity extends Activity {
Button buttonA;
Button buttonB;
Button buttonC;
Button buttonD;
Button buttonE;
Button buttonF;
Button buttonG;
Button buttonH;
Button buttonI;
Button buttonJ;
Button buttonK;
Button buttonL;
Button buttonM;
Button buttonN;
Button buttonO;
Button buttonP;
Button buttonQ;
Button buttonR;
Button buttonS;
Button buttonT;
Button buttonU;
Button buttonV;
Button buttonX;
Button buttonW;
Button buttonY;
Button buttonZ;
Button next;
Intent i;
TextView txtD;
TextView txtO;
TextView txtG;
int life=3;
TextView nyaw;
TextView nyaw2;
TextView nyaw3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dog);
buttonA = (Button)findViewById(R.id.buttonAbout);
buttonB = (Button)findViewById(R.id.buttonhelp);
buttonC = (Button)findViewById(R.id.buttonc);
buttonD = (Button)findViewById(R.id.buttond);
buttonE = (Button)findViewById(R.id.buttonE);
buttonF = (Button)findViewById(R.id.buttonf);
buttonG = (Button)findViewById(R.id.buttong);
buttonH = (Button)findViewById(R.id.buttonh);
buttonI = (Button)findViewById(R.id.buttoni);
buttonJ = (Button)findViewById(R.id.buttonj);
buttonK = (Button)findViewById(R.id.buttonk);
buttonL = (Button)findViewById(R.id.buttonl);
buttonM = (Button)findViewById(R.id.buttonm);
buttonN = (Button)findViewById(R.id.buttonn);
buttonO = (Button)findViewById(R.id.buttono);
buttonP = (Button)findViewById(R.id.buttonp);
buttonQ = (Button)findViewById(R.id.buttonq);
buttonR = (Button)findViewById(R.id.buttonr);
buttonS = (Button)findViewById(R.id.buttons);
buttonT = (Button)findViewById(R.id.buttont);
buttonU = (Button)findViewById(R.id.buttonu);
buttonV = (Button)findViewById(R.id.buttonv);
buttonW = (Button)findViewById(R.id.buttonw);
buttonX = (Button)findViewById(R.id.buttonx);
buttonY = (Button)findViewById(R.id.buttony);
buttonZ = (Button)findViewById(R.id.buttonz);
next = (Button)findViewById(R.id.buttonnext);
txtD = (TextView)findViewById(R.id.textViewD);
txtO = (TextView)findViewById(R.id.textViewO);
txtG = (TextView)findViewById(R.id.textViewG);
nyaw = (TextView)findViewById(R.id.nyawa);
nyaw2 = (TextView)findViewById(R.id.nyawa2);
nyaw3 = (TextView)findViewById(R.id.nyawa3);
buttonA.setOnClickListener(myOnlyhandler);
buttonB.setOnClickListener(myOnlyhandler);
buttonC.setOnClickListener(myOnlyhandler);
buttonD.setOnClickListener(myOnlyhandler);
buttonE.setOnClickListener(myOnlyhandler);
buttonF.setOnClickListener(myOnlyhandler);
buttonG.setOnClickListener(myOnlyhandler);
buttonH.setOnClickListener(myOnlyhandler);
buttonI.setOnClickListener(myOnlyhandler);
buttonJ.setOnClickListener(myOnlyhandler);
buttonK.setOnClickListener(myOnlyhandler);
buttonL.setOnClickListener(myOnlyhandler);
buttonM.setOnClickListener(myOnlyhandler);
buttonN.setOnClickListener(myOnlyhandler);
buttonO.setOnClickListener(myOnlyhandler);
buttonP.setOnClickListener(myOnlyhandler);
buttonQ.setOnClickListener(myOnlyhandler);
buttonR.setOnClickListener(myOnlyhandler);
buttonS.setOnClickListener(myOnlyhandler);
buttonT.setOnClickListener(myOnlyhandler);
buttonU.setOnClickListener(myOnlyhandler);
buttonV.setOnClickListener(myOnlyhandler);
buttonW.setOnClickListener(myOnlyhandler);
buttonX.setOnClickListener(myOnlyhandler);
buttonY.setOnClickListener(myOnlyhandler);
buttonZ.setOnClickListener(myOnlyhandler);
next.setOnClickListener(myOnlyhandler);
}
View.OnClickListener myOnlyhandler = new View.OnClickListener() {
public void onClick(View v) {
if( buttonD.getId() == ((Button)v).getId() ){
txtD.setVisibility(View.VISIBLE);
}
else if( buttonO.getId() == ((Button)v).getId() ){
txtO.setVisibility(View.VISIBLE);
}
else if( buttonG.getId() == ((Button)v).getId() ){
txtG.setVisibility(View.VISIBLE);
}
else if( next.getId() == ((Button)v).getId() ){
i = new Intent(DogActivity.this, HouseActivity.class);
startActivity(i);
}
else{
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.no);
mp.start();
life--;
Log.i("Current Life Value is",""+life);
switch (life) {
case 2:
nyaw.setVisibility(View.INVISIBLE);
break;
case 1:
nyaw2.setVisibility(View.INVISIBLE);
break;
case 0:
nyaw3.setVisibility(View.INVISIBLE);
i = new Intent(DogActivity.this, TamatActivity.class);
startActivity(i);
break;
}
}
}
};
**private boolean clickedBtnD;
private boolean clickedBtnO;
private boolean clickedBtnG;
public void onClick(View v) {
final int id = v.getId();
switch(id) {
case R.id.buttond:
clickedBtnD = true;
txtD.setVisibility(View.VISIBLE);
break;
case R.id.buttono:
clickedBtnO = true;
txtO.setVisibility(View.VISIBLE);
break;
case R.id.buttong:
clickedBtnG = true;
txtG.setVisibility(View.VISIBLE);
break;
case R.id.buttonnext:
if(clickedBtnD && clickedBtnO && clickedBtnG) {
next.setVisibility(View.VISIBLE);
}
break;
}
}**
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dog, menu);
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
i = new Intent(DogActivity.this, LevelActivity.class);
startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
}

you are missing to implement onClicklistenor from your Activity and #Override before your onclick method like in code only one button is here ..
Try out this code
package com.example.browsebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id=v.getId();
switch(id) {
case R.id.button1:
//CODE
break;
}
}
}

Related

How do I switch the if and if else when switching the text between buttons in android studio?

I am trying to switch the text between buttons like a puzzle game using the grid layout. I tried using an if statement but I feel I am doing it wrong. can any one give suggestions? Here is my java code
package com.example.kellito13.test;
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.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn=(Button)findViewById(R.id.btn);
final Button btnOne=(Button)findViewById(R.id.btnOne);
final Button btnTwo=(Button)findViewById(R.id.btnTwo);
final Button btnFive=(Button)findViewById(R.id.btnFive);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(v == btnOne){
Button btn = (Button) v;
btn.setText("B");
btnOne.setText("A");
}
else if (v == btnFive){
btn.setText("E");
btnFive.setText("A");
}
/* Button btn = (Button) v;
btn.setText("B");
btnOne.setText("A");*/
}
});
btnOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button btnOne = (Button) v;
btn.setText("A");
btnOne.setText("B");
}
});
}
#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);
}
}
Try this way
#Override
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.btnOne:
btn.setText("B");
btnOne.setText("A");
break;
case R.id.btnFive:
btn.setText("E");
btnFive.setText("A");
break;
default :
}
}
package com.example.kellito13.test;
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.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity Implement View.OnclickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn=(Button)findViewById(R.id.btn);
final Button btnOne=(Button)findViewById(R.id.btnOne);
final Button btnTwo=(Button)findViewById(R.id.btnTwo);
final Button btnFive=(Button)findViewById(R.id.btnFive);
//In oncreate method register the listener for all button
btn.setOnClickListener(this);
btnOne.setOnClickListener(this);
btnTwo.setOnClickListener(this);
btnFive.setOnClickListener(this);
}
//the following will be your original code....
#Override
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.btn:
//do stuff
break;
case R.id.btnOne:
//do stuff
break;
case R.id.btnTwo:
//do stuff
break;
case R.id.btnFive:
//do stuff
break;
default :
//do stuff
}
}
}

how to select an item from a list , display the selected item in the editText then from the edit text display it in a toast

i am creating a simple android application consist from 3 activities.
Main Activity
Second Activity
List Page
the first activity has a button that display the listPage using the intent
after the user select an item from the list and click ok the system will transfer him to the second Activity that contain a edit box that the selected item will be display in it.
and after the user click get back message button the system will transfer him to the MainActivity and display the selected item in a Toast .
can anyone help me to accomplish this tasks????
MainActivity.java
package com.devleb.intentmenudemoapp;
import android.R.color;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
TextView txt1, txt2;
EditText edittxt1, edittxt2;
Button btn1, btn2, btn3, btn4;
String msgStr, msgStr2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
edittxt1 = (EditText) findViewById(R.id.edit1);
edittxt2 = (EditText) findViewById(R.id.edit2);
btn1 = (Button) findViewById(R.id.btn);
btn1.setOnClickListener(this);
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(this);
btn3 = (Button) findViewById(R.id.btn3);
btn3.setOnClickListener(this);
btn4 = (Button) findViewById(R.id.btn4);
btn4.setOnClickListener(this);
registerForContextMenu(edittxt1);
registerForContextMenu(edittxt2);
}
#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) {
// TODO Auto-generated method stub
msgStr = edittxt1.getText().toString();
msgStr2 = edittxt2.getText().toString();
switch (item.getItemId()) {
case R.id.bold_item:
edittxt1.setText(beautify(msgStr, "BOLD"));
edittxt2.setText(beautify(msgStr2, "BOLD"));
break;
case R.id.italic_item:
edittxt1.setText(beautify(msgStr, "ITALIC"));
edittxt2.setText(beautify(msgStr2, "ITALIC"));
break;
case R.id.red_item:
edittxt1.setTextColor(color.background_dark | Color.RED); // red
edittxt2.setTextColor(color.background_dark | Color.RED); // red
break;
case R.id.blue_item:
edittxt1.setTextColor(color.background_dark | Color.BLUE); // blue
edittxt2.setTextColor(color.background_dark | Color.BLUE); // blue
break;
case R.id.yellow_item:
edittxt1.setTextColor(color.background_dark | Color.YELLOW); // yellow
edittxt2.setTextColor(color.background_dark | Color.YELLOW); // yellow
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
msgStr = edittxt1.getText().toString();
msgStr2 = edittxt2.getText().toString();
switch (item.getItemId()) {
case R.id.bold_item:
edittxt1.setText(beautify(msgStr, "BOLD"));
edittxt2.setText(beautify(msgStr2, "BOLD"));
break;
case R.id.italic_item:
edittxt1.setText(beautify(msgStr, "ITALIC"));
edittxt2.setText(beautify(msgStr2, "ITALIC"));
break;
case R.id.red_item:
edittxt1.setTextColor(color.background_dark | Color.RED); // red
edittxt2.setTextColor(color.background_dark | Color.RED); // red
break;
case R.id.blue_item:
edittxt1.setTextColor(color.background_dark | Color.BLUE); // blue
edittxt2.setTextColor(color.background_dark | Color.BLUE); // blue
break;
case R.id.yellow_item:
edittxt1.setTextColor(color.background_dark | Color.YELLOW); // yellow
edittxt2.setTextColor(color.background_dark | Color.YELLOW); // yellow
break;
default:
break;
}
return super.onContextItemSelected(item);
}
private CharSequence beautify(String originalText, String selectedStyle) {
// TODO Auto-generated method stub
Spanned answer = null;
if (selectedStyle.equals("BOLD"))
answer = Html.fromHtml("<b>" + originalText + "</b>");
else if (selectedStyle.equals("ITALIC"))
answer = Html.fromHtml("<i>" + originalText + "</i>");
else if (selectedStyle.equals("NORMAL"))
answer = Html.fromHtml("<normal>" + originalText + "</normal>");
return answer;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String value;
switch (v.getId()) {
case R.id.btn:
value = edittxt1.getText().toString();
txt2.setText(value);
break;
case R.id.btn2:
// value = edittxt1.getText().toString();
Intent i = new Intent(this, ListPage.class);
//i.putExtra("msgFromFirstActivity", value);
startActivity(i);
break;
case R.id.btn3:
Intent ii = new Intent();
ii.setType("image/pictures/*");
ii.setAction(Intent.ACTION_GET_CONTENT);
startActivity(ii);
break;
case R.id.btn4:
// get back message from second activity
Intent iii = new Intent(this, SecondActivity.class);
startActivityForResult(iii, 1);
default:
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if (null != data) {
String returnMSG = data.getStringExtra("MESSAGE");
Toast.makeText(this, returnMSG, Toast.LENGTH_SHORT).show();
} else
Toast.makeText(this, "Error!!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
SecondActivity.java
/*get back the result from the list page and display it in the edit
text box then after clicking show the result in the first activity as
toast
*/
package com.devleb.intentmenudemoapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SecondActivity extends Activity {
TextView txt;
EditText edittxt;
String result;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*
Intent iList = new Intent(this, SecondActivity.class);
startActivityForResult(iList, 1);
*/
edittxt = (EditText) findViewById(R.id.edit_txt);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
result = edittxt.getText().toString();
Intent i = new Intent();
i.putExtra("MESSAGE", result);
setResult(1, i);
finish();
}
});
}
/*#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if (null != data) {
String returnMSG = data
.getStringExtra("MessageFromsecondActivity");
// Toast.makeText(this, returnMSG, Toast.LENGTH_SHORT).show();
edittxt.setText(returnMSG);
} else
Toast.makeText(this, "Error!!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
ListPage.java
package com.devleb.intentmenudemoapp;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class ListPage extends ListActivity {
TextView txt;
private static final String[] items = { "item1", "item2", "item3", "item4",
"item5", "item6", "item7", "item8", "item9" };
Button btn;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
txt = (TextView) findViewById(R.id.txt_list);
btn = (Button) findViewById(R.id.btn_list);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
/*
result = txt.getText().toString();
Intent i = new Intent();
i.putExtra("MessageFromsecondActivity", result);
setResult(1, i);
finish();
*/
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
txt.setText(items[position]);
super.onListItemClick(l, v, position, id);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
}
until now this what i did from here how to continue or what i need to add and change to make my tasks
What here you can do is,
To pass data from first activity to second activity
Intent in = new Intent(Youractivity.this, secondactivity.class);
in.putExtra("value", valuetopass);
startActivity(in);
Now, get data in second activity
Intent in = getIntent();
String valuetoset = in.getStringExtra("value");
And then set this value to edittext
youredittext.setText(valuetoset);
Try this..
ListPage.java
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// TODO Auto-generated method stub
String val = ((TextView) v).getText().toString().trim();
txt.setText(items[position]);
Intent i = new Intent(ListPage.this, SecondActivity.class);
i.putExtra("value", val);
startActivity(in);
}
SecondActivity.java
Intent i = getIntent();
String val = "";
if(i.hasExtra("value"))
val = i.getStringExtra("value");
edittxt = (EditText) findViewById(R.id.edit_txt);
edittxt.setText(val);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
result = edittxt.getText().toString();
Intent i = new Intent();
i.putExtra("MESSAGE", result);
startActivity(in);
}
});
MainActivity.java
Intent i = getIntent();
String value = "";
if(i.hasExtra("MESSAGE")){
value = i.getStringExtra("MESSAGE");
Toast.makeText(getBaseContext(), value, Toast.LENGTH_SHORT).show();
}

having multiple choice game that will calculate the score of the user but the system crush out

i have a sample android application that will display flag of coutry and multiple choice using radio button and each time the user check one of the answers the system will check if true and add 25 points to its score using intent to pass from activity to another with transferring the data mean the score until the user play 4 times to get to the end where the system will display his score .
until now i did the MainActivity that pass the data to the second but the problem is that the system force to close and in the log cat this what its display:
can anyone help me to solve this problem ????
logcat
11-27 22:15:53.609: E/AndroidRuntime(4834): Caused by: java.lang.NullPointerException
11-27 22:15:53.609: E/AndroidRuntime(4834): at com.devleb.flagology.SecondActivity.onCreate(SecondActivity.java:56)
MainActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnS;
RadioGroup rdgS;
RadioButton rdS1, rdS2, rdS3, rdS4;
private int score =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rdgS = (RadioGroup) findViewById(R.id.rdg1);
rdgS.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (rdS1.isChecked() || rdS2.isChecked() || rdS3.isChecked()
|| rdS4.isChecked()) {
btnS.setVisibility(View.VISIBLE);
}
}
});
rdS1 = (RadioButton) findViewById(R.id.rd_s1);
rdS2 = (RadioButton) findViewById(R.id.rd_s2);
rdS3 = (RadioButton) findViewById(R.id.rd_s3);
rdS4 = (RadioButton) findViewById(R.id.rd_s4);
btnS = (Button) findViewById(R.id.btn_s);
btnS.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, SecondActivity.class);
switch (rdgS.getCheckedRadioButtonId()) {
case R.id.rd_s1:
i.putExtra("score", score);
break;
case R.id.rd_s2:
i.putExtra("score", score);
break;
case R.id.rd_s3:
i.putExtra("score", score + 25);
break;
case R.id.rd_s4:
i.putExtra("score", score);
break;
default:
break;
}
startActivity(i);
}
});
}
#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) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.hint_icon:
ShowAlertDialog();
break;
case R.id.about_icon:
Toast.makeText(this, "developed by Georges Matta",
Toast.LENGTH_SHORT).show();
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void ShowAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Hint")
.setMessage("The famouse sport is Bullfighting")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
SecondActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class SecondActivity extends Activity {
Button btnI;
RadioGroup rdgI;
RadioButton rdI1, rdI2, rdI3, rdI4;
// TextView txt_result;
private int score = 0;
int finalScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("score");
finalScore = score + value;
rdgI = (RadioGroup) findViewById(R.id.rdg2);
rdgI.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
if (rdI1.isChecked() || rdI2.isChecked()
|| rdI3.isChecked() || rdI4.isChecked()) {
btnI.setVisibility(View.VISIBLE);
}
}
});
rdI1 = (RadioButton) findViewById(R.id.rd_I1);
rdI2 = (RadioButton) findViewById(R.id.rd_I2);
rdI3 = (RadioButton) findViewById(R.id.rd_I3);
rdI4 = (RadioButton) findViewById(R.id.rd_I4);
btnI = (Button) findViewById(R.id.btn_s);
btnI.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(SecondActivity.this,
ThirdActivity.class);
switch (rdgI.getCheckedRadioButtonId()) {
case R.id.rd_I1:
i.putExtra("score", finalScore);
break;
case R.id.rd_I2:
i.putExtra("score", finalScore);
break;
case R.id.rd_I3:
i.putExtra("score", finalScore);
break;
case R.id.rd_I4:
i.putExtra("score", finalScore);
break;
default:
break;
}
startActivity(i);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
ThirdActivity.java
package com.devleb.flagology;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class ThirdActivity extends Activity {
TextView txt_result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
txt_result = (TextView) findViewById(R.id.txtResult);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = String.valueOf(extras.getInt("score"));
txt_result.setText(value);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.third, menu);
return true;
}
}
I would venture to guess that your problem comes from this line:
btnS = (Button) findViewById(R.id.btn_s);
Most likely you made changes to your main activity layout (R.layout.activity_main) and either renamed or removed the <Button> element from it. If my guess is correct, then this line will fail to find the view in the inflated layout, and your btnS object will be null, leading to the actual exception you see.

Anomailies when an activity calls itself

I Have an activty in my app which uses putextra(int) method to pass the value 0 first when the aactivty is started. Then on pressing a next button it passes 6,Subsequently 12 and so on. But the trouble is on pressing the next second time I found that the value of index received using getextras method is 0.Is it cause i am calling the activity from itself . This is the code snippet:
package com.movie;
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.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class movielist extends Activity implements OnClickListener{
Button bm[] = new Button[6];
Button nxt,prev;
String namesdb[]=new String[50];
databaseconnect db;
String lang;
int start,index,end;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mallu_list);
db = new databaseconnect(this);
db.open();
start=this.getIntent().getExtras().getInt("index");
lang =this.getIntent().getExtras().getString("lang");
Toast.makeText(this, start+"", Toast.LENGTH_SHORT).show();
Log.i("info",start+"");
if(!db.isdata(lang))
{
Toast.makeText(this, "No data in Database", Toast.LENGTH_SHORT).show();
finish();
return;
}
end=start+6;
bm[0] = (Button) findViewById(R.id.bm1);
bm[1] = (Button) findViewById(R.id.bm2);
bm[2] = (Button) findViewById(R.id.bm3);
bm[3] = (Button) findViewById(R.id.bm4);
bm[4] = (Button) findViewById(R.id.bm5);
bm[5] = (Button) findViewById(R.id.bm6);
nxt = (Button) findViewById(R.id.nxt);
prev = (Button) findViewById(R.id.prev);
if(start==0)
{
// prev.setBackgroundResource(0);
// prev.setText("");
}
else
prev.setOnClickListener(this);
namesdb = db.getmovie("",lang);
for (int i = 0; start+i < namesdb.length && i<6; i++) {
bm[i].setText(namesdb[start+i]);
bm[i].setOnClickListener(this);
}
int flag=0;
int i=namesdb.length;
Log.i("info",i+"");
Toast.makeText(this, i+"", Toast.LENGTH_SHORT).show();
for(int j=5;j>=i-start;j--)
{
bm[j].setBackgroundResource(0);
flag=1;
}
if(flag==1)
{
// nxt.setBackgroundResource(0);
// nxt.setText("");
}
else
nxt.setOnClickListener(this);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent myint2 = new Intent(this, list.class);
startActivity(myint2);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bm1:
call(namesdb[start],start,lang);
break;
case R.id.bm2:
call(namesdb[start+1],start,lang);
break;
case R.id.bm3:
call(namesdb[start+2],start,lang);
break;
case R.id.bm4:
call(namesdb[start+3],start,lang);
break;
case R.id.bm5:
call(namesdb[start+4],start,lang);
break;
case R.id.bm6:
call(namesdb[start+5],start,lang);
break;
case R.id.nxt:
int i=namesdb.length;
Intent myint2 = new Intent(this,movielist.class);
myint2.putExtra("index",end);
myint2.putExtra("lang",lang);
startActivity(myint2);
case R.id.prev:
if(start==0)
{
prev.setBackgroundResource(0);
}
else
{
myint2 = new Intent(this,movielist.class);
myint2.putExtra("index",start-6);
myint2.putExtra("lang",lang);
startActivity(myint2);}
break;
}
}
public void call(String name,int start2,String lang) {
Intent myint = new Intent(this, detail.class);
myint.putExtra("nameid", name);
myint.putExtra("index", start2);
myint.putExtra("lang", lang);
startActivity(myint);
}
}
Here's your problem. This part of the switch statement:
case R.id.nxt:
int i=namesdb.length;
Intent myint2 = new Intent(this,movielist.class);
myint2.putExtra("index",end);
myint2.putExtra("lang",lang);
startActivity(myint2);
is missing a break at the end. So it falls through to the next case, which starts the activity with different extras.

How to use Application class to share variables while extending Activity class

Im having problem sharing a global variable that I need to retain across multiple activities. This variable is created in TextPlay class and copied onto DailyDataEntry class. I have done some research sharing variables between two activities using Intent but Im looking to share that variable to multiple classes. I think I will have to extends Application but all my other classes are extending Activity already. How am I supposed to extend Application while extending Activity? Thanks a million
///TextPlay Class///
package com.armstrong.y.android.app;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class TextPlay extends Activity implements View.OnClickListener {
Button chkCmd;
ToggleButton passTog;
EditText input;
TextView display;
EditText etUserId;
Button btnUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
baconAndEggs();
passTog.setOnClickListener(this);
chkCmd.setOnClickListener(this);
// Share variables between classes controls
etUserId = (EditText) findViewById(R.id.etUserId);
btnUserId = (Button) findViewById(R.id.btnUserId);
}
private void baconAndEggs() {
// TODO Auto-generated method stub
chkCmd = (Button) findViewById(R.id.bResults);
passTog = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bResults:
// get the text from the command box then convert it to string
String check = input.getText().toString();
display.setText(check);
if (check.contentEquals("left")) {
display.setGravity(Gravity.LEFT);
} else if (check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
} else if (check.contentEquals("right")) {
display.setGravity(Gravity.RIGHT);
} else if (check.contentEquals("blue")) {
display.setTextColor(Color.BLUE);
display.setText("blue");
} else if (check.contains("hellow")) {
Random crazy = new Random();
display.setText("hello!!!!");
display.setTextSize(crazy.nextInt(75));
display.setTextColor(Color.rgb(crazy.nextInt(255),
crazy.nextInt(255), crazy.nextInt(255)));
switch (crazy.nextInt(3)) {
case 0:
display.setGravity(Gravity.LEFT);
break;
case 1:
display.setGravity(Gravity.CENTER);
break;
case 2:
display.setGravity(Gravity.RIGHT);
break;
}
} else {
display.setText("invalid");
display.setGravity(Gravity.CENTER);
display.setTextColor(Color.BLACK);
}
break;
case R.id.tbPassword:
// If toggle button is set to ON, password will be ***
if (passTog.isChecked()) {
input.setInputType(InputType.TYPE_CLASS_TEXT
| InputType.TYPE_TEXT_VARIATION_PASSWORD);
} else {
// if toggle is off, its going be plain text
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
break;
}
}
}
///DailyDataEntry Class///
package com.armstrong.y.android.app;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DailyDataEntry extends Activity {
String strdate;
EditText etGetDate;
Calendar calendarDateToday = Calendar.getInstance();
Calendar calendarDateNext = Calendar.getInstance();
Calendar calendarDatePrevious = Calendar.getInstance();
int counterNext = 0;
int counterPrevious = 0;
Button btnTodayDate;
Button btnPreviousDate;
Button btnGetNextDate;
EditText etDailyCaloriesIn;
EditText etDailyCaloriesOut;
EditText etDailyAnxietyLevel;
EditText etDailySleepQuality;
TextView tvUserId;
Button btnSubmit;
Button btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_data_entry);
// Toast Message Warning
Toast.makeText(getApplicationContext(),
"DO NOT LEAVE FIELD BLANK OR CRASH IS ON YOU!",
Toast.LENGTH_LONG).show();
btnTodayDate = (Button) findViewById(R.id.btnGetTodayDate);
btnPreviousDate = (Button) findViewById(R.id.btnGetPreviousDate);
btnGetNextDate = (Button) findViewById(R.id.btnGetNextDate);
etGetDate = (EditText) findViewById(R.id.etGetDate);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnReset = (Button) findViewById(R.id.btnReset);
etDailyCaloriesIn = (EditText) findViewById(R.id.etDailyCaloriesIn);
etDailyCaloriesOut = (EditText) findViewById(R.id.etDailyCaloriesOut);
etDailyAnxietyLevel = (EditText) findViewById(R.id.etDailyAnxietyLevel);
etDailySleepQuality = (EditText) findViewById(R.id.etDailySleepQuality);
tvUserId = (TextView) findViewById(R.id.tvUserId);
// When Submit Button is clicked
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Grab User Input from EditText and Convert input String to
// Integer
int check1 = Integer.parseInt(etDailyCaloriesIn.getText()
.toString());
int check2 = Integer.parseInt(etDailyCaloriesOut.getText()
.toString());
int check4 = Integer.parseInt(etDailyAnxietyLevel.getText()
.toString());
int check5 = Integer.parseInt(etDailySleepQuality.getText()
.toString());
strdate = etGetDate.getText().toString();
// Run Legal Value Integrity Check
if (strdate.length() != 8) {
etGetDate.setText("Please enter in the correct format.");
} else if (strdate.equals("")) {
etGetDate.setText("Please enter a date.");
} else if (check1 > 10 || check1 < 1) {
etDailyCaloriesIn.setText("Incorrect Value!");
} else if (check2 > 10 || check2 < 1) {
etDailyCaloriesOut.setText("Incorrect Value!");
} else if (check4 > 10 || check4 < 1) {
etDailyAnxietyLevel.setText("Incorrect Value!");
} else if (check5 > 10 || check5 < 1) {
etDailySleepQuality.setText("Incorrect Value!");
} else {
etGetDate.setText("Submited!");
etDailyCaloriesIn.setText("Submited!");
etDailyCaloriesOut.setText("Submited!");
etDailyAnxietyLevel.setText("Submited!");
etDailySleepQuality.setText("Submited!");
}
}
});
// When Reset Button is Clicked
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String empty = "";
etDailyCaloriesIn.setText(empty);
etDailyCaloriesOut.setText(empty);
etDailyAnxietyLevel.setText(empty);
etDailySleepQuality.setText(empty);
etGetDate.setText(empty);
}
});
// Capture Today's Date
btnTodayDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
strdate = sdf.format(calendarDateToday.getTime());
etGetDate.setText(strdate);
}
});
// Capture Previous's Date
btnPreviousDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
if (counterPrevious == 0) {
calendarDatePrevious.add(Calendar.DATE, -1);
}
strdate = sdf.format(calendarDatePrevious.getTime());
etGetDate.setText(strdate);
counterPrevious++;
}
});
// Capture Next's Date
btnGetNextDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
if (counterNext == 0) {
calendarDateNext.add(Calendar.DATE, +1);
}
strdate = sdf.format(calendarDateNext.getTime());
etGetDate.setText(strdate);
counterNext++;
}
});
}
}
Create class that will extends to Application and use it in the following manner whenever you need it:
MyApplication myAppHelper = (MyApplication) context.getApplication();
myAppHelper.setWhatever(whatever);
Whatever whatever = myAppHelper.getWhatever();

Categories

Resources