How do i exit runnable and switch another activity - java

I have a textview timer, i want it stops after 10 seconds of showing on display and after 10 seconds that my current activity jumps to an other activity
Runnable runnable = new Runnable()
{
#Override
public void run()
{
while(Running)
{
try{
Thread.sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
handler.post(new Runnable()
{
#Override
public void run()
{
number+=1;
tvTimer.setText(String.valueOf(number)); //With setting value of number on textfield ITS POSSIBLE TO SEE THE TIMER
if(number==10)
{
Running = false;
handler.removeCallbacks(this);//that does not works for me to stop
Intent i = new Intent(getApplicationContext(), SonucMenu.class);
startActivity(i); //Starting my second class
}
}
});
}
}
My Second activity starts but the layout from second activity comes more than one time, what i want is that it comes only one time, and i think this problem depends on that i cant stop runnable
Here My Complete original Code
MainActivity.class
package com.marburg.leftright;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import com.marburg.leftright.R;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
static Random rnd=new Random();
static int rndN = rnd.nextInt(2);
TextView inf,tvSc, tvTimer;
Button btnL, btnR;
int ScoreRhtg = 0;
int ScoreFls = 0;
String right = "RIGHT";
String left = "LEFT";
private int number;
private Handler handler;
private boolean Running = true;
MediaPlayer mySound;
public void sendData()
{
String rData = Integer.toString(ScoreRhtg); //Score Of Right Answer Data setting
String wData = Integer.toString(ScoreFls);
Intent i = new Intent(getApplicationContext(), SonucMenu.class);
i.putExtra("DATA", rData);
i.putExtra("DATA2", wData);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lr);
Intent intent = getIntent(); //Get Intent from SonucMenu.class to turn back MainActivity.java from New Button (This Class)
inf = (TextView)findViewById(R.id.tvInfo);
btnL = (Button)findViewById(R.id.btnL);
btnR = (Button)findViewById(R.id.btnR);
tvSc = (TextView)findViewById(R.id.tvScore);
//Set text left or right according new random number
if(rndN==1){
inf.setText(right);
}
else
{
inf.setText(left);
}
//Set 0 for Left
btnL.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{ //Set 0 for Left
if(rndN==0)
{
ScoreRhtg++;
tvSc.setText(ScoreRhtg+" Right");
rndN=rnd.nextInt(2); //Renew the random number
}
else
{
ScoreFls++;
tvSc.setText(ScoreFls+" False");
rndN=rnd.nextInt(2); //Renew the random number
}
//Set text left or right according new random number
if(rndN==1){
inf.setText(right);
}
else
{
inf.setText(left);
}
}
});
//Set 1 For Right
btnR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(rndN==1)
{
ScoreRhtg++;
tvSc.setText(ScoreRhtg+" Right");
rndN=rnd.nextInt(2); //Renew the random number
}
else
{
ScoreFls++;
tvSc.setText(ScoreFls+" False");
rndN=rnd.nextInt(2); //Renew the random number
}
//Set text left or right according a new random number
if(rndN==1){
inf.setText(right);
}
else
{
inf.setText(left);
}
}
});
//FOR TIMER RESPONSIBLE PART OF CODE
tvTimer = (TextView)findViewById(R.id.tvTimer);
handler = new Handler();
Runnable runnable = new Runnable()
{
#Override
public void run()
{
while(Running)
{
try{
Thread.sleep(1000);
}catch(InterruptedException e)
{
e.printStackTrace();
}
handler.post(new Runnable()
{
#Override
public void run()
{
number+=1;
tvTimer.setText(String.valueOf(number)); //With setting value of number on textfield ITS POSSIBLE TO SEE THE TIMER
if(number==9)
{
mySound=MediaPlayer.create(MainActivity.this, R.raw.click);
mySound.start();
Running = false;
handler.removeCallbacks(this);//Doesnt works for me
sendData(); //sendData function startActivity(i) included
}
}
});
}
}
};
new Thread(runnable).start();
//END OF FOR TIMER RESPONSIBLE PART OF CODE
}
#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);
}
}
And my Second Class SonucMenu.java
package com.example.timerdeneme2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SonucMenu extends MainActivity {
public TextView tvCorr, tvWro;
public Button btnNew, btnCls;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sonuc_menu);
Intent i = getIntent();
Bundle dataBundle = i.getExtras();
String dataRString = dataBundle.getString("DATA");
String dataWString = dataBundle.getString("DATA2");
TextView tv = (TextView)findViewById(R.id.tvCorr);
TextView tvW = (TextView)findViewById(R.id.tvWro);
tv.setText(dataRString);
tvW.setText(dataWString);
btnNew = (Button)findViewById(R.id.btnNew);
btnNew.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(SonucMenu.this, MainActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
SonucMenu.this.startActivity(myIntent);
}
});
btnCls=(Button)findViewById(R.id.btnEx);
btnCls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
}
}
And XML Layouts lr.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.marburg.leftright.MainActivity" >
<TextView
android:id="#+id/tvResCorr"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/tvResCorr"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/tvResCorr" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnL"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="L"
android:textSize="70dp" />
<Button
android:id="#+id/btnR"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="50dp"
android:text="R"
android:textSize="70dp" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
<TextView
android:id="#+id/tvInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableLayout1"
android:layout_alignRight="#+id/tableLayout1"
android:layout_below="#+id/tableLayout1"
android:layout_marginLeft="10dp"
android:layout_marginTop="200dp"
android:gravity="center"
android:text="Info"
android:textSize="24dp" />
<TextView
android:id="#+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableLayout1"
android:layout_alignRight="#+id/tableLayout1"
android:layout_below="#+id/tvInfo"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Score"
android:textSize="24dp" />
<TextView
android:id="#+id/tvTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tableLayout1"
android:layout_centerHorizontal="true"
android:text="Time" />
</RelativeLayout>
And sonuc_menu.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.marburg.leftright.MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="36dp" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvResCorr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correctness:" />
<TextView
android:id="#+id/tvCorr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="X" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvResWro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Wrongness" />
<TextView
android:id="#+id/tvWro"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:text="X" />
</TableRow>
</TableLayout>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableLayout1"
android:layout_below="#+id/tableLayout1"
android:layout_marginTop="113dp" >
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnNew"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="NEW" />
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BEST SCORES" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
<Button
android:id="#+id/btnEx"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="EXIT" />
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableRow>
</TableLayout>
</RelativeLayout>

I think for this you can use following code , It worked for me.
It will start your activity after 10 seconds.
new Handler().postDelay(new Runnable() {
#Override
public void run() {
Start Your activity here.
}
}, 10000);
but one of the best solution will be (I just found it from develoer site):
new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
strat your activity here.
}
}.start();

Use View.post(Runnable) and View.postDelayed(Runnable, long), no need to create additional thread.
private TextView tvTimer;
private final Runnable mCountDownRunnable = new Runnable() {
private int mCount = 0;
#Override
public void run() {
mCount++;
if (mCount < 10) {
tvTimer.setText(Integer.toString(mCount));
tvTimer.postDelayed(this, 1000);
} else {
Intent i = new Intent(YourActivity.this, SonucMenu.class);
YourActivity.this.startActivity(i);
}
}
};
to start runnable, call tvTimer.post(mCountDownRunnable);

Related

code for image run in arraylist

i do array list with images thet i want them to run with 2 buttons thet go next pic and beck pic i dont know the code for this i thx all for the time you spend for help.
ackage com.example.hanansanag.mytourneyccreator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
/**
* Created by ssh on 25/12/2016.
*/
public class Players extends AppCompatActivity implements View.OnClickListener {
protected Button btnNext, btnBack;
protected String fname;
protected String Lname;
protected String team;
protected ImageView iv;
protected ArrayList array_image;
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.team_pic);
ArrayList<Integer> array_image = new ArrayList<Integer>();
array_image.add(R.drawable.bacelona);
array_image.add(R.drawable.athlethiko);
array_image.add(R.drawable.arsenak);
array_image.add(R.drawable.chelsea);
array_image.add(R.drawable.dortmond);
array_image.add(R.drawable.city);
array_image.add(R.drawable.bayernunchen);
array_image.add(R.drawable.intermilan);
array_image.add(R.drawable.psj);
array_image.add(R.drawable.realmadrid);
array_image.add(R.drawable.leverpool);
array_image.add(R.drawable.milan);
array_image.add(R.drawable.juventus);
array_image.add(R.drawable.ashkelon);
array_image.add(R.drawable.macabiheifa);
array_image.add(R.drawable.macabitelaviv);
array_image.add(R.drawable.beitaryeroshlaim);
array_image.add(R.drawable.apoelbersheva);
iv = (ImageView) findViewById(R.id.imageView);
btnNext = (Button) findViewById(R.id.btnNextPic);
btnBack = (Button) findViewById(R.id.btnBeckPic);
btnBack.setOnClickListener(this);
btnNext.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (i <= 0 || i >= array_image.length) {
return;
}
if (btnNext == v) {
iv.setImageResource(array_image.get(i++));
} else if (btnBack == v) {
iv.setBackgroundResource(array_image.get(i--));
}
}
}
**what can i do here in this line of code thet the pic will move : **
#Override
public void onClick(View v) {
if (i <= 0 || i >= array_image.length) {
return;
}
if (btnNext == v) {
iv.setImageResource(array_image.get(i++));
} else if (btnBack == v) {
iv.setBackgroundResource(array_image.get(i--));
}
}
this is the xml;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/teamimage">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:text="Fname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:layout_marginTop="12dp"
android:id="#+id/textView2" />
<ImageView
android:layout_height="80dp"
android:id="#+id/imageView"
android:layout_width="80dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:text="Lname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:id="#+id/Lname"
android:layout_below="#+id/textView2"
android:layout_toEndOf="#+id/imageView" />
<TextView
android:text="Fname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:layout_marginTop="12dp"
android:id="#+id/textView3" />
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true">
<Button
android:layout_width="20dp"
android:layout_height="15dp"
android:id="#+id/btnBeckPic"
android:background="#drawable/btnbeck"
android:layout_marginStart="30dp"
android:layout_alignBottom="#+id/Lname"
android:layout_toEndOf="#+id/textView2" />
<Button
android:background="#drawable/btnnext"
android:layout_width="20dp"
android:layout_height="15dp"
android:id="#+id/btnNextPic"
android:layout_below="#+id/imageView"
android:layout_toEndOf="#+id/btnBeckPic"
android:layout_marginStart="14dp" />
</GridLayout>
</RelativeLayout>
int currentImage = 0;
String[] strArr = new String[array_image.size()];
strArr = array_image.toArray(stockArr);
#Override
public void onClick(View v) {
if (btnNext == v) {
currentImage++;
currentImage = currentImage % strArr .length;
iv.setImageResource(strArr .length[currentImage]);
} else if (btnBack == v) {
currentImage--;
currentImage = (currentImage + strArr .length) % strArr .length;
iv.setImageResource(strArr[currentImage]);
}
}

Google map marking with address field

I want to mark my Address(Edit Text) with google map marking.
I have created a simple form but i want to mark it on map when i fill the address and drop a marker on the same place.
I am getting the latitude and longitude for address field then i would pin it using a marker but i have issues at the initial stage only(please consider me as a noob in android since i have started few days back)
SignUp Activity
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowCloseListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import butterknife.Bind;
import butterknife.ButterKnife;
public class SignupActivity extends FragmentActivity implements OnMarkerClickListener, OnMarkerDragListener, OnInfoWindowClickListener, OnMapReadyCallback, OnInfoWindowCloseListener, GoogleMap.OnInfoWindowLongClickListener, OnSeekBarChangeListener {
private static final String TAG = "SignupActivity";
private GoogleMap googleMap;
private static LatLng goodLatLng = new LatLng(37, -120);
LatLng addressPos;
Marker addressMarker;
#Bind(R.id.input_name)
EditText _nameText;
#Bind(R.id.input_address)
EditText _addressText;
#Bind(R.id.input_email)
EditText _emailText;
#Bind(R.id.input_mobile)
EditText _mobileText;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.input_reEnterPassword)
EditText _reEnterPasswordText;
#Bind(R.id.btn_signup)
Button _signupButton;
#Bind(R.id.link_login)
TextView _loginLink;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
String address = _addressText.getText().toString();
// Initial Map
try {
if (googleMap == null) {
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
} catch (Exception e) {
e.printStackTrace();
}
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
_loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void signup() {
Log.d(TAG, "Signup");
if (!validate()) {
onSignupFailed();
return;
}
_signupButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating Account...");
progressDialog.show();
String name = _nameText.getText().toString();
String address = _addressText.getText().toString();
String email = _emailText.getText().toString();
String mobile = _mobileText.getText().toString();
String password = _passwordText.getText().toString();
String reEnterPassword = _reEnterPasswordText.getText().toString();
// TODO: Implement your own signup logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onSignupSuccess or onSignupFailed
// depending on success
onSignupSuccess();
// onSignupFailed();
progressDialog.dismiss();
}
}, 3000);
}
public void onSignupSuccess() {
_signupButton.setEnabled(true);
setResult(RESULT_OK, null);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_signupButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = _nameText.getText().toString();
String address = _addressText.getText().toString();
String email = _emailText.getText().toString();
String mobile = _mobileText.getText().toString();
String password = _passwordText.getText().toString();
String reEnterPassword = _reEnterPasswordText.getText().toString();
if (name.isEmpty() || name.length() < 3) {
_nameText.setError("at least 3 characters");
valid = false;
} else {
_nameText.setError(null);
}
if (address.isEmpty()) {
_addressText.setError("Enter Valid Address");
valid = false;
} else {
_addressText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (mobile.isEmpty() || mobile.length()!=10) {
_mobileText.setError("Enter Valid Mobile Number");
valid = false;
} else {
_mobileText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
if (reEnterPassword.isEmpty() || reEnterPassword.length() < 4 || reEnterPassword.length() > 10 || !(reEnterPassword.equals(password))) {
_reEnterPasswordText.setError("Password Do not match");
valid = false;
} else {
_reEnterPasswordText.setError(null);
}
return valid;
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
}
#Override
public void onInfoWindowClick(Marker marker) {
}
#Override
public void onMapReady(GoogleMap Map) {
googleMap=Map;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Address"));
}
public void showAddressMarker(View view) {
String newAddress = _addressText.getText().toString();
if (newAddress != null) {
new PlaceAMarker().execute(newAddress);
}
}
class PlaceAMarker extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String startAddress = params[0];
startAddress = startAddress.replaceAll(" ", "%20");
getLatLng(startAddress, false);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
addressMarker = googleMap.addMarker(new MarkerOptions()
.position(addressPos).title("Address"));
}
}
protected void getLatLng(String address, boolean setDestination) {
String uri = "http://maps.google.com/maps/api/geocode/json?address="
+ address + "&sensor=false";
HttpGet httpGet = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int byteData;
while ((byteData = stream.read()) != -1) {
stringBuilder.append((char) byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
double lat = 0.0, lng = 0.0;
JSONObject jsonObject;
try {
jsonObject = new JSONObject(stringBuilder.toString());
lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}
addressPos = new LatLng(lat, lng);
}
#Override
public void onInfoWindowClose(Marker marker) {
}
#Override
public void onInfoWindowLongClick(Marker marker) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
Main Activity file
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.maps.GoogleMap;
public class MainActivity extends ActionBarActivity {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
}
#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);
}
}
signup xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal" />
<!-- Name Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_name"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name" />
</android.support.design.widget.TextInputLayout>
<!-- Address Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<fragment
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment" />
<EditText android:id="#+id/input_address"
style="#style/TextLabel"
android:layout_marginTop="23dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:ems="10"
android:layout_below="#+id/map"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:hint="Address" />
</android.support.design.widget.TextInputLayout>
<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_email"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Email" />
</android.support.design.widget.TextInputLayout>
<!-- mobile number -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_mobile"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Mobile Number" />
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_password"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Password Re-enter Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_reEnterPassword"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Re-enter Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Signup Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Create Account"/>
<TextView android:id="#+id/link_login"
style="#style/TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="Already a member? Login"
android:gravity="center"
android:textSize="16dip"/>
</LinearLayout>
</ScrollView>
AndroidRuntime: FATAL EXCEPTION: main
Process: package, PID: 6547
java.lang.RuntimeException: Unable to start activity ComponentInfo{package.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2519)
at android.app.ActivityThread.access$800(ActivityThread.java:162)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5532)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class fragment
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
addMarker(latLng);
}
});
private void addMarker(LatLng latLng){
String text=editText.getText().toString();
Marker marker = mGoogleMap.addMarker(new MarkerOptions()
.position(latLng)
.title(text));
}
Simple method . do your customization
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView android:src="#drawable/logo"
android:layout_width="wrap_content"
android:layout_height="72dp"
android:layout_marginBottom="24dp"
android:layout_gravity="center_horizontal" />
<!-- Name Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_name"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name" />
</android.support.design.widget.TextInputLayout>
<fragment
android:layout_width="match_parent"
android:layout_height="400dp"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment" />
<!-- Address Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_address"
style="#style/TextLabel"
android:layout_marginTop="23dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:ems="10"
android:layout_below="#+id/map"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPostalAddress"
android:hint="Address" />
</android.support.design.widget.TextInputLayout>
<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_email"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="Email" />
</android.support.design.widget.TextInputLayout>
<!-- mobile number -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_mobile"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:hint="Mobile Number" />
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_password"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Password Re-enter Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/input_reEnterPassword"
style="#style/TextLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Re-enter Password"/>
</android.support.design.widget.TextInputLayout>
<!-- Signup Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Create Account"/>
<TextView android:id="#+id/link_login"
style="#style/TextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:text="Already a member? Login"
android:gravity="center"
android:textSize="16dip"/>
</LinearLayout>
</ScrollView>
please change the xml code and try

My Application won't start up?

I'm not really sure why my application won't start up, I get no errors and I have no idea what's going on? I'm pretty new to android and this is just a basic calculator, but it keeps crashing every time I start it up.
***************Main Activity.java**********************
package com.example.alex.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Something(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
*******************Something.java******************
package com.example.alex.myapplication;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
public class Something extends Activity {
private Button add,subtract,multiply,devide;
private EditText editA, editB, editC;
private double doubleA,doubleB,doubleC;
public Something(Activity a) {
click();
}
public void click(){
editA = (EditText) findViewById(R.id.editText);
editB = (EditText) findViewById(R.id.editText2);
editC = (EditText) findViewById(R.id.editText3);
doubleA =Double.parseDouble(editA.getText().toString());
doubleB =Double.parseDouble(editB.getText().toString());
add = (Button) findViewById(R.id.add);
subtract = (Button) findViewById(R.id.subtract);
multiply = (Button) findViewById(R.id.multiply);
devide = (Button) findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA+doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA-doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA*doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA/doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
}
}
******************activity_main.xml****************
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/idk"
android:textSize="17sp"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="5"
android:id="#+id/editText"
android:hint="First number"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="5"
android:id="#+id/editText2"
android:hint="Second number"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/textView"
android:layout_alignEnd="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/add"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText"
android:layout_marginBottom="166dp" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Subtract"
android:id="#+id/subtract"
android:layout_alignTop="#+id/multiply"
android:layout_alignLeft="#+id/add"
android:layout_alignStart="#+id/add" />
<Button
android:layout_width="100dp"
android:layout_height="50dp"
android:text="Multiply"
android:id="#+id/multiply"
android:layout_marginTop="58dp"
android:layout_below="#+id/devide"
android:layout_alignRight="#+id/devide"
android:layout_alignEnd="#+id/devide" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Devide"
android:id="#+id/devide"
android:layout_below="#+id/editText"
android:layout_alignLeft="#+id/editText2"
android:layout_alignStart="#+id/editText2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="20"
android:id="#+id/editText3"
android:layout_below="#+id/textView"
android:hint="Results"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp" />
</RelativeLayout>
The fact that you have created a constructor for the Something class
public Something(Activity a) {
click();
}
instead of using onCreate() is probably the source of the error.
Something is derived from Activity, in which you have to override onCreate() at the very least, and set the View of your Activity in it. You haven't done that, and instead you have created a constructor for Something which is also not allowed.
The solution to your problem is to replace the constructor with onCreate() and set the View of that Activity using setContentView(). Also, you cannot create an Activity object using
new Something(this);

making toast for validate edit text when i push a button

im tired to try this thing,can help me find out my solution.
I try to validate Edittext if edittext filed empty when i push a button will show a toast message.
this my layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MyActivity"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Panjang"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="right|left" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextPanjang"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:maxLength="10"
android:hint="Panjang"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lebar"
android:id="#+id/textView2"
android:layout_below="#+id/editTextPanjang"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_gravity="right|left"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextLebar"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:maxLength="10"
android:hint="Lebar"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hitung Luas"
android:id="#+id/buttonHitungLuas"
android:layout_below="#+id/editTextLebar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="hitugLuas"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Luas"
android:id="#+id/textView3"
android:layout_below="#id/buttonHitungLuas"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="20"
android:id="#+id/editTextLuas"
android:layout_below="#id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextLuas"
android:id="#+id/buttonClear"
android:text="#string/btn_clear"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/buttonClear"
android:layout_below="#+id/editTextLuas"
android:id="#+id/buttonExit"
android:text="Exit"
/>
</RelativeLayout>
this my java
package com.example.aan.myfirstapp;
import android.content.Context;
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.EditText;
import android.widget.Toast;
public class MyActivity extends ActionBarActivity {
private EditText edtPanjang;
private EditText edtLebar;
private EditText edtLuas;
private Button btnHitungLuas;
private Button btnClear;
private Button btnExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
initUI();
initEvent();
}
private void initUI(){
edtPanjang = (EditText) findViewById(R.id.editTextPanjang);
edtLebar = (EditText) findViewById(R.id.editTextLebar);
edtLuas = (EditText) findViewById(R.id.editTextLuas);
btnHitungLuas = (Button) findViewById(R.id.buttonHitungLuas);
btnClear = (Button) findViewById(R.id.buttonClear);
btnExit = (Button) findViewById(R.id.buttonExit);
}
private void initEvent() {
btnHitungLuas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hitungLuas();
}
}
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clearData();
}
});
btnExit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View paramView) {
MyActivity.this.finish();
}
});
}
private void hitungLuas(){
int panjang = Integer.parseInt(edtPanjang.getText().toString());
int lebar = Integer.parseInt(edtLebar.getText().toString());
int luas = panjang*lebar;
edtLuas.setText(luas+"");
}
private void clearData(){
edtLuas.setText("");
edtLebar.setText("");
edtPanjang.setText("");
}
#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_my, 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);
}
}
Sory for my bad english
log chat when i run the emulator
03-12 09:29:21.784 1710-2323/com.google.process.gapps E/Backupīš• [LegacyBackupAccountManager] Fail to get legacy transport context.
android.content.pm.PackageManager$NameNotFoundException: Application package com.google.android.backup not found
at android.app.ContextImpl.createPackageContextAsUser(ContextImpl.java:2139)
at android.app.ContextImpl.createPackageContext(ContextImpl.java:2115)
at android.content.ContextWrapper.createPackageContext(ContextWrapper.java:658)
at com.google.android.gms.backup.am.<init>(SourceFile:47)
at com.google.android.gms.backup.a.a(SourceFile:65)
at com.google.android.gms.backup.c.a(SourceFile:39)
at com.google.android.gms.backup.b.a(SourceFile:67)
at com.google.android.gms.backup.b.a(SourceFile:39)
at com.google.android.gms.backup.BackupAccountNotifierService.onHandleIntent(SourceFile:76)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
You need to handle onClick of the button in this manner and show a toast if the edittext is empty
if(editText.getText().toString().trim().length()==0){
Toast.makeText(getApplicationContext(), "field is empty",
Toast.LENGTH_LONG).show();
}else{
//your code here
}
If you want to check for empty EditText.. try TextUtils for it.
Example
if (TextUtils.isEmpty(edtText.getText().toString().trim())) {
Toast.makeText(getBaseContext(),
"Empty", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getBaseContext(),
"Not Empty", Toast.LENGTH_SHORT)
.show();
}

How would i make a button to switch where points go in a counter?

I am currently a high school student who decided to try and take up Android dev for fun, but I am stumped. I have an image button for blue team and for red team. The score goes up automatically for blue team. What i dont know how to do is when you hit the red button, the image buttons make the red teams score go up and vice versa.
Here is my java code
package com.example.puremmacompetitionjiujitsuscorer;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
class MainActivity extends Activity {
private int blueScore = 0;
private int redScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton sweep = (ImageButton) findViewById(R.id.imageButton5);
final ImageButton pass = (ImageButton) findViewById(R.id.imageButton8);
final ImageButton mount = (ImageButton) findViewById(R.id.imageButton4);
final ImageButton backMount = (ImageButton) findViewById(R.id.imageButton3);
final ImageButton kneeOnBelly = (ImageButton) findViewById(R.id.imageButton7);
final ImageButton takeDown = (ImageButton) findViewById(R.id.imageButton6);
final TextView blueScoreCount = (TextView) findViewById(R.id.blueScore1);
takeDown.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
blueScore += 2;
blueScoreCount.setText("" + blueScore);
}
});
sweep.setOnClickListener(new View.OnClickListener(){
public void onClick(View w) {
blueScore += 2;
blueScoreCount.setText("" + blueScore);
}
});
pass.setOnClickListener(new View.OnClickListener(){
public void onClick(View q){
blueScore += 3;
blueScoreCount.setText("" + blueScore);
}
});
mount.setOnClickListener(new View.OnClickListener(){
public void onClick(View t){
blueScore += 4;
blueScoreCount.setText("" + blueScore);
}
});
backMount.setOnClickListener(new View.OnClickListener(){
public void onClick(View s){
blueScore += 4;
blueScoreCount.setText("" + blueScore);
}
});
kneeOnBelly.setOnClickListener(new View.OnClickListener(){
public void onClick(View g){
blueScore += 2;
blueScoreCount.setText("" + blueScore);
}
});
};
#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;
}
Here is my XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/purebig" >
<TextView
android:id="#+id/redScore1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint"
android:maxLength="2"
android:textIsSelectable="false" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:src="#drawable/stop" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/play"/>
<ImageButton
android:id="#+id/imageButton7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageButton2"
android:layout_alignParentLeft="true"
android:src="#drawable/kneeonbelly"
android:onClick="addTwo" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/imageButton7"
android:src="#drawable/backmount"
android:onClick="addFour" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageButton3"
android:layout_alignParentRight="true"
android:src="#drawable/mount"
android:onClick="addFour" />
<ImageButton
android:id="#+id/imageButton8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageButton7"
android:layout_centerHorizontal="true"
android:src="#drawable/pass"
android:onClick="addThree" />
<ImageButton
android:id="#+id/imageButton6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/imageButton8"
android:src="#drawable/takedown"
android:onClick="addTwo" />
<ImageButton
android:id="#+id/imageButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageButton8"
android:layout_below="#+id/imageButton8"
android:src="#drawable/sweep"
android:onClick="addTwo" />
<ImageButton
android:id="#+id/imageButton10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/imageButton9"
android:src="#drawable/red" />
<ImageButton
android:id="#+id/imageButton9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/imageButton1"
android:src="#drawable/blue" />
<TextView
android:id="#+id/blueScore1"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="#string/hint"
android:maxLength="2"
android:textIsSelectable="false"/>
<requestFocus />
</RelativeLayout>
I think I possibly understand you. If I do, you can use a flag to see which Button was pressed. So the flow would be like
Red button pressed -> flag = red -> Score Button pressed -> red score += score
In code it would be like
String flag = "";
public void onRedBtnClick(View v)
{
flag = "red";
}
public void scoreBtnClick(View v)
{
if (!flag.equals(""));
{
if ("red".equals(flag))
{
redScore += score;
}
if ("blue".equals(flag))
{
blueScore += score;
}
}
This is obviously done really quick and you will have to adjust your variables to your needs. But if I understand what you want then this would give you the basic logic

Categories