Detect which button is clicked - java

i have 3 button in my page :
red, blue and green
how i can detect which button is clicked
i want use the background color for next page(red,blue or green)
this is my code in main page:
public void color(View view) {
Intent color= new Intent(this, colorPage.class);
Click(view);
String What_color = view.toString();
color .putExtra("What_color",What_color);
startActivity(colorPage);
}
private void Click(View view1) {
int id = view1.getId();
}
}
and this is my code in colorPage:
Bundle What_color = getIntent().getExtras();
if (What_color != null) {
String mycol = What_color.getString("What_color");
TextView result = (TextView) findViewById(R.id.tResult);
result.setText(mycol);
}
i see in textView this code:
android.support.v7.widget.AppCompatButton{366bb1b VFED..C. ...P.... 0,0-728,114 #7f070023 app:id/Red
or this code:
ndroid.support.v7.widget.AppCompatButton{366bb1b VFED..C. ...P.... 0,0-728,114 #7f070023 app:id/Blue
please help me

Add a listener to each button with their id.
Button buttonOne = (Button) findViewById(R.id.YOURBUTTONID);
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do change the color.
}
});
//This code changing background on your activity but You have to give color as a hexadecimal
public void setActivityBackgroundColor(int color) {
View view = this.getWindow().getDecorView();
view.setBackgroundColor(color);
}

you can create a global string like
String detectBtnStr = "";
private void Click(View view1) {
int id = view1.getId();
switch(id){
case: R.id.red_btn:
detectBtnStr = "red";
break;
case: R.id.blue_btn:
detectBtnStr = "blue";
break;
case: R.id.green_btn:
detectBtnStr = "green";
break;
}
}
and when come back then check with detectBtnStr like
if (detectBtnStr.equals("red")) {
// do your code}
else if (detectBtnStr.equals("blue")) {
// do your code
}
else if (detectBtnStr.equals("green")){
// do your code
}
hope this will help you.

Related

Change button background color based on previous color

I have a very simple problem
consider I'm retrieving a string value online using getText() Method
Now depending upon value of string I have set my button background to red and blue.
If string value is red then button background is red and if it is blue then blue.
Now if I implement onClicklistener to same button I would like to changes it's Background color. If it was Red then change it to blue and if it was blue then change it to red as long as user presses key.
mSolved = (Button) itemView.findViewById(R.id.book_solved);
mSolved.setText(g.getColorvalue());
if("Blue".equals(holder.mSolved.getText())){
mSolved.setBackgroundColor(BLUE);
}
if("Red".equals(holder.mSolved.getText())){
.mSolved.setBackgroundColor(RED);
}
mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Background color is already BLue)
{
change to Red
}
else
{
Change to Blue
}
}
Try using FLAG variables. Something similar to this.
mSolved = (Button) itemView.findViewById(R.id.book_solved);
mSolved.setText(g.getColorvalue());
boolean IS_BLUE = false;
boolean IS_RED = false;
if("Blue".equals(holder.mSolved.getText())){
mSolved.setBackgroundColor(BLUE);
IS_BLUE = true;
}
if("Red".equals(holder.mSolved.getText())){
mSolved.setBackgroundColor(RED);
IS_RED = true;
}
mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(IS_BLUE)
{
mSolved.setBackgroundColor(RED);
IS_RED = true;
IS_BLUE = false;
}
else if(IS_RED)
{
mSolved.setBackgroundColor(BLUE);
IS_BLUE = true;
IS_RED = false;
}
}
Try this code:
mSolved = (Button) findViewById(R.id.book_solved);
mSolved.setBackgroundColor(Color.parseColor("#009900"));
mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View tView) {
ColorDrawable buttonColor = (ColorDrawable) mSolved.getBackground();
int colorId = buttonColor.getColor();
// Log.i("INFO", "find color value for new color " + colorId);
if (colorId == -3407872) { // color is read
mSolved.setBackgroundColor(Color.parseColor("#009900"));
}
else {
mSolved.setBackgroundColor(Color.parseColor("#cc0000"));
}
}
});

hide button if text length is < 1 in android studio

I'm new to Android and Java and I'm busy editing an existing app. I am trying to hide a button if no text is getting pulled in from a webservice. I have made it work with another button when the text is being populated
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
but when I used:
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
nothing seems to happen.
I don't know if the code snippet is in the wrong place or something else is overwriting the code. Here is my activity code:
package com.example.dsouchon.myapplication;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
if(Local.isSet(getApplicationContext(), "LoggedIn"))
{
String loggedInUser = Local.Get(getApplicationContext(), "LoggedIn");
if(loggedInUser.length()>0)
{
buttonEventSetup.setVisibility(View.VISIBLE);
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
}
else
{
buttonEventSetup.setVisibility(View.GONE);
}
if(Local.isSet(getApplicationContext(), "EventName"))
{
String event = Local.Get(getApplicationContext(), "EventName");
TextView textEvent = (TextView) findViewById(R.id.textEventName);
textEvent.setText( event);
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(true);
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.length() > 1) {
buttonEventSetup.setVisibility(View.INVISIBLE);
}
if (textEvent.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
}
else
{
Button buttonAccessControl = (Button)findViewById(R.id.buttonAccessControl);
buttonAccessControl.setEnabled(false);
}
if(Local.isSet(getApplicationContext(), "EventImage"))
{
TextView textEvent = (TextView) findViewById(R.id.textEventName);
String result = Local.Get(getApplicationContext(), "EventImage");
ImageView imageViewEventImage = (ImageView)findViewById(R.id.imageViewEventImage);
byte[] decodedString = Base64.decode(result, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageViewEventImage.setImageBitmap(decodedByte);
}
}
#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_main2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void setupEvent(View view) {
Intent intent = new Intent(MainActivity.this, SetupEvent.class );
finish();
startActivity(intent);
}
public void accessControl(View view) {
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.GONE);
Intent intent = new Intent(MainActivity.this, MainActivity21.class );
finish();
startActivity(intent);
}
public void Logoff(View view) {
Local.Set(getApplicationContext(), "LoggedIn", "");
}
public void Login(View view) {
final AlertDialog ad=new AlertDialog.Builder(this).create();
MySOAPCallActivity cs = new MySOAPCallActivity();
try {
EditText userName = (EditText) findViewById(R.id.editUserName);
EditText password = (EditText) findViewById(R.id.editPassword);
String user = userName.getText().toString();
String pwd = password.getText().toString();
LoginParams params = new LoginParams(cs, user, pwd);
Local.Set(getApplicationContext(), "UserName", user);
Local.Set(getApplicationContext(), "Password", pwd);
new CallSoapLogin().execute(params);
// new CallSoapGetCurrentEvents().execute(params);
} catch (Exception ex) {
ad.setTitle("Error!");
ad.setMessage(ex.toString());
}
ad.show();
}
public class CallSoapLogin extends AsyncTask<LoginParams, Void, String> {
private Exception exception;
#Override
protected String doInBackground(LoginParams... params) {
return params[0].foo.Login(params[0].username, params[0].password);
}
protected void onPostExecute(String result) {
// TODO: check this.exception
// TODO: do something with the feed
try {
TextView loginResult =(TextView)findViewById(R.id.labelLoginResult);
loginResult.setVisibility(View.VISIBLE);
loginResult.setText(result);
// Button buttonUnsetEvent = (Button)findViewById(R.id.buttonUnsetEvent);
// buttonUnsetEvent.setEnabled(true);
//Spinner spinner2 = (Spinner)findViewById(R.id.spinner2);
//spinner2.setEnabled(true);
boolean LoginSuccessful = false;
if(result.toLowerCase().contains("success"))
{
LoginSuccessful = true;
}
if (LoginSuccessful)
{
String user = Local.Get(getApplicationContext(), "UserName");
Local.Set(getApplicationContext(), "LoggedIn", user);
LinearLayout layoutLoggedIn = (LinearLayout)findViewById(R.id.layoutLoggedIn);
layoutLoggedIn.setVisibility(View.VISIBLE);
Button buttonEventSetup = (Button)findViewById(R.id.buttonEventSetup);
buttonEventSetup.setVisibility(View.VISIBLE);
LinearLayout layoutLogIn = (LinearLayout)findViewById(R.id.layoutLogIn);
layoutLogIn.setVisibility(View.VISIBLE);
}
} catch (Exception ex) {
String e3 = ex.toString();
}
}
}
private static class LoginParams {
MySOAPCallActivity foo;
String username;
String password;
LoginParams(MySOAPCallActivity foo, String username, String password) {
this.foo = foo;
this.username = username;
this.password = password;
}
}
}
You are getting the length of Textview that will not work.Use the text length.This should work
String event = Local.Get(getApplicationContext(), "EventName");
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (event.length() > 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (event.length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
In your code above textEvent is not a string value. It is an Object of type TextView. length() in this case will not return the length of the text contained within that element. You will need to explicitly get the text string before you can get the length of it. This is acquired using the getText() method on the TextView.
Your code should look like the following:
//HIDES SET EVENT BUTTON WHEN EVENT IS SET
if (textEvent.getText().length() >= 1) {
buttonEventSetup.setVisibility(View.VISIBLE);
}
if (textEvent.getText().length() < 1) {
buttonAccessControl.setVisibility(View.INVISIBLE);
}
You also have INVISIBLE on both cases in your posted code example.
Note that your code also does not handle cases where the text length == 1. You could simplify the whole block with the following.
Note: any value != 0 is classed as true
buttonEventSetup.setVisibility(textEvent.getText().length() ? View.VISIBLE : View.INVISIBLE);

Change camera orientation android

Hello Before starting this i would like to tell you that there are many topics with the similar title but my problem is different i am not able to change the orientation of the camera at all i have tried many things.
Following are my codes and its a live streaming project.
public class MainActivity extends Activity implements
OnClickListener,
RtspClient.Callback,
Session.Callback,
SurfaceHolder.Callback,
OnCheckedChangeListener {
public final static String TAG = "MainActivity";
private Button mButtonSave;
private Button mButtonVideo;
private ImageButton mButtonStart;
private ImageButton mButtonFlash;
private ImageButton mButtonCamera;
private ImageButton mButtonSettings;
private RadioGroup mRadioGroup;
private FrameLayout mLayoutVideoSettings;
private FrameLayout mLayoutServerSettings;
private SurfaceView mSurfaceView;
private TextView mTextBitrate;
private EditText mEditTextURI;
private EditText mEditTextPassword;
private EditText mEditTextUsername;
private ProgressBar mProgressBar;
private Session mSession;
private RtspClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mButtonVideo = (Button) findViewById(R.id.video);
mButtonSave = (Button) findViewById(R.id.save);
mButtonStart = (ImageButton) findViewById(R.id.start);
mButtonFlash = (ImageButton) findViewById(R.id.flash);
mButtonCamera = (ImageButton) findViewById(R.id.camera);
mButtonSettings = (ImageButton) findViewById(R.id.settings);
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mEditTextURI = (EditText) findViewById(R.id.uri);
mEditTextUsername = (EditText) findViewById(R.id.username);
mEditTextPassword = (EditText) findViewById(R.id.password);
mTextBitrate = (TextView) findViewById(R.id.bitrate);
mLayoutVideoSettings = (FrameLayout) findViewById(R.id.video_layout);
mLayoutServerSettings = (FrameLayout) findViewById(R.id.server_layout);
mRadioGroup = (RadioGroup) findViewById(R.id.radio);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mRadioGroup.setOnCheckedChangeListener(this);
mRadioGroup.setOnClickListener(this);
mButtonStart.setOnClickListener(this);
mButtonSave.setOnClickListener(this);
mButtonFlash.setOnClickListener(this);
mButtonCamera.setOnClickListener(this);
mButtonVideo.setOnClickListener(this);
mButtonSettings.setOnClickListener(this);
mButtonFlash.setTag("off");
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
if (mPrefs.getString("uri", null) != null) mLayoutServerSettings.setVisibility(View.GONE);
mEditTextURI.setText(mPrefs.getString("uri", "default_stream"));
mEditTextPassword.setText(mPrefs.getString("password", ""));
mEditTextUsername.setText(mPrefs.getString("username", ""));
// Configures the SessionBuilder
mSession = SessionBuilder.getInstance()
.setContext(getApplicationContext())
.setAudioEncoder(SessionBuilder.AUDIO_AAC)
.setAudioQuality(new AudioQuality(8000,16000))
.setVideoEncoder(SessionBuilder.VIDEO_H264)
.setSurfaceView(mSurfaceView)
.setPreviewOrientation(90)//I tried changing this value but nothing happened it works even if i comment this line.
.setCallback(this)
.build();
// Configures the RTSP client
mClient = new RtspClient();
mClient.setSession(mSession);
mClient.setCallback(this);
Camera camera;
mSurfaceView.getHolder().addCallback(this);
selectQuality();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
mLayoutVideoSettings.setVisibility(View.GONE);
mLayoutServerSettings.setVisibility(View.VISIBLE);
selectQuality();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
mLayoutServerSettings.setVisibility(View.GONE);
toggleStream();
break;
case R.id.flash:
if (mButtonFlash.getTag().equals("on")) {
mButtonFlash.setTag("off");
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
} else {
mButtonFlash.setImageResource(R.drawable.ic_flash_off_holo_light);
mButtonFlash.setTag("on");
}
mSession.toggleFlash();
break;
case R.id.camera:
mSession.switchCamera();
break;
case R.id.settings:
if (mLayoutVideoSettings.getVisibility() == View.GONE &&
mLayoutServerSettings.getVisibility() == View.GONE) {
mLayoutServerSettings.setVisibility(View.VISIBLE);
} else {
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.GONE);
}
break;
case R.id.video:
mRadioGroup.clearCheck();
mLayoutServerSettings.setVisibility(View.GONE);
mLayoutVideoSettings.setVisibility(View.VISIBLE);
break;
case R.id.save:
mLayoutServerSettings.setVisibility(View.GONE);
break;
}
}
#Override
public void onDestroy(){
super.onDestroy();
mClient.release();
mSession.release();
mSurfaceView.getHolder().removeCallback(this);
}
private void selectQuality() {
int id = mRadioGroup.getCheckedRadioButtonId();
RadioButton button = (RadioButton) findViewById(id);
if (button == null) return;
String text = button.getText().toString();
Pattern pattern = Pattern.compile("(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)");
Matcher matcher = pattern.matcher(text);
matcher.find();
int width = Integer.parseInt(matcher.group(1));
int height = Integer.parseInt(matcher.group(2));
int framerate = Integer.parseInt(matcher.group(3));
int bitrate = Integer.parseInt(matcher.group(4))*1000;
mSession.setVideoQuality(new VideoQuality(width, height, framerate, bitrate));
Toast.makeText(this, ((RadioButton)findViewById(id)).getText(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "Selected resolution: "+width+"x"+height);
}
private void enableUI() {
mButtonStart.setEnabled(true);
mButtonCamera.setEnabled(true);
}
// Connects/disconnects to the RTSP server and starts/stops the stream
public void toggleStream() {
mProgressBar.setVisibility(View.VISIBLE);
if (!mClient.isStreaming()) {
String ip,port,path;
// We save the content user inputs in Shared Preferences
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Editor editor = mPrefs.edit();
editor.putString("uri", mEditTextURI.getText().toString());
editor.putString("password", mEditTextPassword.getText().toString());
editor.putString("username", mEditTextUsername.getText().toString());
editor.commit();
// We parse the URI written in the Editext
Pattern uri = Pattern.compile("rtsp://(.+):(\\d*)/(.+)");
Matcher m = uri.matcher(mEditTextURI.getText()); m.find();
ip = m.group(1);
port = m.group(2);
path = m.group(3);
// mClient.setCredentials(mEditTextUsername.getText().toString(), mEditTextPassword.getText().toString());
mClient.setCredentials("umair", "123456");
mClient.setServerAddress(ip, Integer.parseInt(port));
mClient.setStreamPath("/"+path);
mClient.startStream();
} else {
// Stops the stream and disconnects from the RTSP server
mClient.stopStream();
}
}
private void logError(final String msg) {
final String error = (msg == null) ? "Error unknown" : msg;
// Displays a popup to report the eror to the user
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(msg).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
});
AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onBitrateUpdate(long bitrate) {
mTextBitrate.setText(""+bitrate/1000+" kbps");
}
#Override
public void onPreviewStarted() {
if (mSession.getCamera() == CameraInfo.CAMERA_FACING_BACK) {
mButtonFlash.setEnabled(true);
mButtonFlash.setTag("off");
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
}
else {
mButtonFlash.setEnabled(true);
}
}
#Override
public void onSessionConfigured() {
}
#Override
public void onSessionStarted() {
enableUI();
mButtonStart.setImageResource(R.drawable.ic_switch_video_active);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onSessionStopped() {
enableUI();
mButtonStart.setImageResource(R.drawable.ic_switch_video);
mProgressBar.setVisibility(View.GONE);
}
#Override
public void onSessionError(int reason, int streamType, Exception e) {
mProgressBar.setVisibility(View.GONE);
switch (reason) {
case Session.ERROR_CAMERA_ALREADY_IN_USE:
break;
case Session.ERROR_CAMERA_HAS_NO_FLASH:
mButtonFlash.setImageResource(R.drawable.ic_flash_on_holo_light);
mButtonFlash.setTag("off");
break;
case Session.ERROR_INVALID_SURFACE:
break;
case Session.ERROR_STORAGE_NOT_READY:
break;
case Session.ERROR_CONFIGURATION_NOT_SUPPORTED:
VideoQuality quality = mSession.getVideoTrack().getVideoQuality();
logError("The following settings are not supported on this phone: "+
quality.toString()+" "+
"("+e.getMessage()+")");
e.printStackTrace();
return;
case Session.ERROR_OTHER:
break;
}
if (e != null) {
logError(e.getMessage());
e.printStackTrace();
}
}
#Override
public void onRtspUpdate(int message, Exception e) {
switch (message) {
case RtspClient.ERROR_CONNECTION_FAILED:
case RtspClient.ERROR_WRONG_CREDENTIALS:
mProgressBar.setVisibility(View.GONE);
enableUI();
logError(e.getMessage());
e.printStackTrace();
break;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
//tried adding the setPreiviewOrientation(90) here also but still nothing changed.
mSession.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mClient.stopStream();
}
}
I have tried to change setPreviewOrientation also but still no changes check the codes i have commented whatever i tried please help me. click here to see the API that i have used
Add this method and call it where camera is open
private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
rotation = getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
switch (rotation) {
case Surface.ROTATION_0:
degree = 0;
break;
case Surface.ROTATION_90:
degree = 90;
break;
case Surface.ROTATION_180:
degree = 180;
break;
case Surface.ROTATION_270:
degree = 270;
break;
default:
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// frontFacing
rotation = (info.orientation + degree) % 330;
rotation = (360 - rotation) % 360;
} else {
// Back-facing
rotation = (info.orientation - degree + 360) % 360;
}
c.setDisplayOrientation(rotation);
Parameters params = c.getParameters();
params.setRotation(rotation);
}
Add these in surfaceChanged method for image clarity and other.
Camera.Parameters parameters = camera.getParameters();
List<Camera.Size> sizes = parameters.getSupportedPictureSizes();
Camera.Size size = sizes.get(0);
for(int i=0;i<sizes.size();i++)
{
if(sizes.get(i).width > size.width)
size = sizes.get(i);
}
parameters.setPictureSize(size.width, size.height);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
parameters.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO);
parameters.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO);
parameters.setExposureCompensation(0);
parameters.setPictureFormat(ImageFormat.JPEG);
parameters.setJpegQuality(100);
try{
camera.setParameters(parameters);
camera.startPreview();
}catch (Exception e){
}

How to validate to rating bar on Button click in Android?

I want to validation on RatingBar in Android. I have 5 rating Bar and 1 Button. I don't want to submit the data without pressed the rating bar. I want to take validation on Rating bar.
Can someone help me. How to take validation on Rating bar?
Here is my Activity code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rating_baar);
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
addListenerOnRatingBar_one();
addListenerOnRatingBar_two();
addListenerOnRatingBar_three();
addListenerOnRatingBar_four();
addListenerOnRatingBar_five();
addListenerOnButton();
}
#SuppressLint("SimpleDateFormat")
public void addListenerOnButton() {
buttonSubmitRate = (Button) findViewById(R.id.button_SubmitRate);
buttonSubmitRate.setOnClickListener(new OnClickListener() {
#SuppressLint("SimpleDateFormat")
#Override
public void onClick(View v) {
if((etTaskName.getText().toString().isEmpty()))
etTaskName.setError("Field Can Not Be Empty !");
else if (!etTaskName.getText().toString().trim().matches("[a-zA-Z{ }]+"))
etTaskName.setError("Accept Alphabets Only.");
else {
strEmpName = textViewNAme.getText().toString().trim();
strTaskName = etTaskName.getText().toString().trim();
String strCurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println("strCurrentDate = " + strCurrentDate);
String strCurrentMonth = new SimpleDateFormat("MMM").format(new Date());
System.out.println("strCurrentDate = " + strCurrentMonth);
String strCurrenYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("strCurrenYear = " + strCurrenYear);
System.out.println("__________________________________________________________________________________");
databaseHelper.insertPerformance_Details(intentStr1, strEmpName,
strTaskName, rateVal_one,
rateVal_two, rateVal_three,
rateVal_four,rateVal_five,
strCurrentDate,strCurrentMonth,
strCurrenYear);
System.out.println("Data Add SuccesFully !!!!");
etTaskName.setText("");
Intent i = new Intent(RatingBaar_Class.this, Rating_Msg.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
}
}
});
}
public void addListenerOnRatingBar_one() {
ratingBar_one = (RatingBar) findViewById(R.id.ratingBar1);
ratingBar_one.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rateVal_one = String.valueOf(rating);
System.out.println(" rateVal_one = " + rateVal_one);
}
});
}
/* Exactly the same methods for four other rating bars, except for variable names */
public void addListenerOnRatingBar_two() { ... }
public void addListenerOnRatingBar_three() { ... }
public void addListenerOnRatingBar_four() { ... }
public void addListenerOnRatingBar_five() { ... }
At first set all rating bar to 0 value. Then on click to button, check if the value has altered in all of them. If so, only valid else invalid.
Also you can use listener to each rating bar and change value of some boolean variable to true
Example:
boolean flag1 = false;
boolean flag2 = false;
.... //similarly upto 5
Then in rating bar listener1
{
flag1 = true;
}
Similarly for all set flag to be true
And in button onClickListener do the following:
if(flag1 && flag2 && flag3 && flag4 && flag5){
//do your work
}else{
//display message that one of the rating bar hasn't been touched
}

How to add a wait function till a button is pressed?

I want to add a wait till, Button (Enter) is pressed function to my code But i am still new to this.
I know there are some errors in my code I was playing around with it, But what I want to do is when I press the line Button I want it to display Input X,Y,Z then wait till enter is pressed to execute the rest of my code I want to add in. How would I implement something like this in my code?
Here is my MainActivity Class:
public class MainActivity extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button enter = (Button) findViewById(R.id.enter);
Button line = (Button) findViewById(R.id.line);
Button arc = (Button) findViewById(R.id.arc);
line.setOnClickListener(this);
enter.setOnClickListener(this);
arc.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView vector = (TextView) findViewById(R.id.point);
TextView index = (TextView) findViewById(R.id.index);
TextView info = (TextView) findViewById(R.id.info);
EditText cl = (EditText) findViewById(R.id.editText1);
DrawingUtils call = new DrawingUtils();
switch (v.getId()) {
case R.id.line:
info.setText("Input X,Y,Z");
// This Is Where the Wait Function Will GO
vector.setText(call.addVertice());
index.setText("1");
break;
case R.id.enter:
String In = cl.getText().toString();
call.setInputCoords(In);
break;
case R.id.arc:
info.setText("Enter Vertice1 ");
// Code for entering Vertice1(Also has wait function)
info.setText("Enter Vertice2");
// Code for entering Vertice2(Also has wait function)
info.setText("Enter Height");
//Code for entering Height(Also has wait function)
}
}
}
Here is my DrawingUtils Class:
public class DrawingUtils {
String inputCoords;
String[] vertice;
public String getInputCoords() {
return inputCoords;
}
public void setInputCoords(String inputCoords) {
this.inputCoords = inputCoords;
}
public String addVertice() {
int i = 0;
vertice = inputCoords.split(",");
return vertice[i];
}
}
I think this is what you are after. Apologies if not!
Use a boolean flag to handle state within your app. This way you can execute different code if something has happened.
boolean enterPressed = false;
#Override
public void onClick(View v) {
TextView vector = (TextView) findViewById(R.id.point);
TextView index = (TextView) findViewById(R.id.index);
TextView info = (TextView) findViewById(R.id.info);
EditText cl = (EditText) findViewById(R.id.editText1);
DrawingUtils call = new DrawingUtils();
switch (v.getId()) {
case R.id.line:
if (enterPressed) {
vector.setText(call.addVertice());
index.setText("1");
}
else {
info.setText("Input X,Y,Z");
}
break;
case R.id.enter:
String In = cl.getText().toString();
call.setInputCoords(In);
enterPressed = true;
break;
case R.id.arc:
info.setText("Enter Vertice1 ");
// Code for entering Vertice1
info.setText("Enter Vertice2");
// Code for entering Vertice2
}
}

Categories

Resources