Google map marking with address field - java

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

Related

EditText not focusing, and not showing keyboard after keyboard is hidden after one input

I am implementing an OTP Verification system and have 3 EditText fields in my layout, and one of them is hidden until the user clicks a button.
Here is the layout file:
registration_acivity_xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RegistrationActivity">
<ImageView
/>
<TextView
/>
<TextView
/>
<TextView
/>
<EditText
android:id="#+id/mobile"
android:layout_width="wrap_content"
android:layout_height="70dp"
android:layout_below="#+id/regText"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:clickable="true"
android:focusable="true"
android:hint="Enter Mobile Number"
android:inputType="phone"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/regText" />
<EditText
android:id="#+id/pin_code"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_below="#+id/mobile"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:autofillHints="Enter Area Pin Code"
android:clickable="true"
android:focusable="true"
android:hint="Enter Area Pin Code"
android:inputType="number"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mobile" />
<TextView
android:id="#+id/verify_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pin_code"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="Verify mobile number with OTP"
android:textAlignment="center"
android:textColor="#696969"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/pin_code" />
<Button
android:id="#+id/get_otp_button"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/verify_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:alpha="1"
android:backgroundTint="#00FA9A"
android:text="Get OTP"
android:textAlignment="center"
android:textColor="#696969"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/verify_text" />
<EditText
android:id="#+id/gen_otp"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_below="#+id/verify_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:alpha="0"
android:clickable="true"
android:focusable="true"
android:hint="Enter OTP"
android:inputType="number"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="15sp"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/verify_text" />
<Button
android:id="#+id/verify_otp_button"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/get_otp_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:alpha="0"
android:backgroundTint="#00FA9A"
android:text="Verify OTP"
android:textAlignment="center"
android:textColor="#696969"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/gen_otp" />
</androidx.constraintlayout.widget.ConstraintLayout>
The problem I am having is that when the third otp EditText is shown it doesn't show the virtual keyboard or gets focused when clicked. Instead I have to first click one of the previous two EditTexts for it to show the virtual keyboard.
What can I do to make the virtual keyboard show on clicking the OTP field at once?
Here is the java file.
RegistrationActivity.java:
package com.example.covislot;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.FirebaseException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class RegistrationActivity extends AppCompatActivity {
EditText mobileField, pinField,otpField;
Button getOTP, verifyOTP;
String mobileNumber, pinCode, OTP;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallback;
FirebaseAuth auth;
private String verificationCode;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_activity);
sp = getSharedPreferences("login",MODE_PRIVATE);
StartFirebaseLogin();
mobileField = findViewById(R.id.mobile);
pinField = findViewById(R.id.pin_code);
otpField = findViewById(R.id.gen_otp);
getOTP = findViewById(R.id.get_otp_button);
verifyOTP = findViewById(R.id.verify_otp_button);
getOTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (TextUtils.isEmpty(mobileField.getText().toString())) {
// when mobile number field is empty
// displaying a toast message.
Toast.makeText(RegistrationActivity.this, "Please enter a valid phone number.", Toast.LENGTH_SHORT).show();
} else {
mobileNumber = "+91" + mobileField.getText().toString();
}
if (TextUtils.isEmpty(pinField.getText().toString())) {
// when pin number field is empty
// displaying a toast message.
Toast.makeText(RegistrationActivity.this, "Please enter a valid Pin code.", Toast.LENGTH_SHORT).show();
} else {
pinCode = pinField.getText().toString();
}
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(mobileNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(RegistrationActivity.this) // Activity (for callback binding)
.setCallbacks(mCallback) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
});
verifyOTP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(otpField.getText().toString())) {
// when otp field is empty
// displaying a toast message.
Toast.makeText(RegistrationActivity.this, "Please enter a valid OTP.", Toast.LENGTH_SHORT).show();
} else {
OTP = otpField.getText().toString();
}
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCode, OTP);
SigninWithPhone(credential);
}
});
}
private void SigninWithPhone(PhoneAuthCredential credential) {
auth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
sp.edit().putBoolean("logged", true).apply();
sp.edit().putString("phone", mobileNumber).apply();
sp.edit().putString("pinCode", pinCode).apply();
startActivity(new Intent(RegistrationActivity.this,SignedInActivity.class));
finish();
} else {
Toast.makeText(RegistrationActivity.this,"Incorrect OTP",Toast.LENGTH_SHORT).show();
}
}
});
}
private void StartFirebaseLogin() {
auth = FirebaseAuth.getInstance();
mCallback = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Toast.makeText(RegistrationActivity.this,"verification completed",Toast.LENGTH_SHORT).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(RegistrationActivity.this,"verification failed",Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCode = s;
Toast.makeText(RegistrationActivity.this,"Code sent",Toast.LENGTH_SHORT).show();
getOTP.animate().alpha(0f).setDuration(500);
otpField.setVisibility(View.VISIBLE);
otpField.animate().alpha(1f).setDuration(500);
verifyOTP.setVisibility(View.VISIBLE);
verifyOTP.animate().alpha(1f).setDuration(600);
}
};
}
}
Put this line when you want to give it focus:
otpField.requestFocus();
Also, to show the soft keyboard explicitly, you can do like below:
otpField.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager im = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(otpField, InputMethodManager.SHOW_IMPLICIT);
}
},200);

onclick listener not working in surfaceview of swipe layout

I am trying to call constructor on onClick listener of getSurfaceView for swipe layout but it is not happening.
RideAdapter.java
#Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == RIDE_ITEM_TYPE) {
view = inflater.inflate(R.layout.item_upcoming_share_ride, parent, false);
swipeLayout = (SwipeLayout) view.findViewById(R.id.sample2);
swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
swipeLayout.addDrag(SwipeLayout.DragEdge.Right, swipeLayout.findViewWithTag("Bottom2"));
// sample2.setShowMode(SwipeLayout.ShowMode.PullOut);
swipeLayout.findViewById(R.id.edit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Star", Toast.LENGTH_SHORT).show();
}
});`
swipeLayout.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Magnifier", Toast.LENGTH_SHORT).show();
}
});
swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v = inflater.inflate(R.layout.item_upcoming_share_ride, parent, false);
new OfferedRideCardViewHolder(v);
}
});
return new OfferedRideCardViewHolder(view);
and OfferedRideCardViewHolder class:
class OfferedRideCardViewHolder extends BaseRideViewHolder {
#BindView(R.id.imgVechicleImage) ImageView imgVechicle;
#BindView(R.id.imgRideIcon) ImageView imgRideIcon;
#BindView(R.id.fromTextView) TextView txtFromLocation;
#BindView(R.id.toTextView) TextView txtToLocation;
#BindView(R.id.txtVichecleModel) TextView txtVichecleModel;
#BindView(R.id.txtRegisterationNo) TextView txtRegisterationNo;
#BindView(R.id.txtDateTime) TextView txtDateTime;
#BindView(R.id.buttonStartEnd) Button startEndRideButton;
#BindView(R.id.matchCountTextView) TextView matchCountTextView;
#BindView(R.id.matchesTextView) TextView matchesTextView;
#BindView(R.id.vehicleContainer) LinearLayout vehicleContainer;
OfferedRideCardViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
item_upcoming_share_ride.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
app:cardCornerRadius="4dp">
<com.daimajia.swipe.SwipeLayout
android:id="#+id/sample2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:tag="Bottom2"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/edit"
android:src="#drawable/edit"
android:layout_width="70dp"
android:background="#00FF00"
android:paddingLeft="25dp"
android:paddingRight="25dp"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/delete"
android:src="#drawable/delete_grey"
android:layout_width="70dp"
android:background="#FF0000"
android:paddingLeft="25dp"
android:paddingRight="25dp"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/llMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
>
<View
android:id="#+id/view"
android:layout_width="16dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:background="#drawable/vetical_rounded_corner_orange_background"
app:layout_constraintBottom_toBottomOf="#+id/toTextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/fromTextView"
/>
<TextView
android:id="#+id/fromTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="12dp"
android:layout_marginTop="16dp"
android:ellipsize="end"
android:fontFamily="#font/lato_regular"
android:maxLines="1"
android:text="Sector 39A, Sector 32, Sector 39, Noida, Uttar Pradesh 201303"
android:textColor="#color/secondary_text"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/view"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="#+id/toTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ellipsize="end"
android:fontFamily="#font/lato_regular"
android:maxLines="1"
android:text="Sector 39A, Sector 32, Sector 39, Noida, Uttar Pradesh 201303"
android:textColor="#color/secondary_text"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="#+id/fromTextView"
app:layout_constraintStart_toStartOf="#+id/fromTextView"
app:layout_constraintTop_toBottomOf="#+id/fromTextView"
/>
<ImageView
android:id="#+id/from_dot_view"
android:layout_width="8dp"
android:layout_height="8dp"
android:src="#drawable/current_location"
android:tint="#color/white"
app:layout_constraintBottom_toBottomOf="#+id/fromTextView"
app:layout_constraintEnd_toEndOf="#+id/view"
app:layout_constraintStart_toStartOf="#+id/view"
app:layout_constraintTop_toTopOf="#+id/fromTextView"
/>
<ImageView
android:id="#+id/to_dot_view"
android:layout_width="8dp"
android:layout_height="wrap_content"
android:src="#drawable/pin_red"
android:tint="#color/white"
app:layout_constraintBottom_toBottomOf="#+id/toTextView"
app:layout_constraintEnd_toEndOf="#+id/view"
app:layout_constraintStart_toStartOf="#+id/view"
app:layout_constraintTop_toTopOf="#+id/toTextView"
/>
<TextView
android:id="#+id/txtDateTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/montserrat_regular"
android:gravity="center_vertical"
android:text="23rd jan,2016 2.30 pm"
android:textColor="#color/secondary_text"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/toTextView"
app:layout_constraintStart_toStartOf="#+id/toTextView"
app:layout_constraintTop_toBottomOf="#+id/view"
/>
<ImageView
android:id="#+id/imageView11"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginTop="8dp"
android:adjustViewBounds="true"
android:tint="#color/colorPrimaryLight"
app:layout_constraintBottom_toBottomOf="#+id/txtDateTime"
app:layout_constraintEnd_toEndOf="#+id/view"
app:layout_constraintStart_toStartOf="#+id/view"
app:layout_constraintTop_toBottomOf="#+id/view"
app:srcCompat="#drawable/ic_clock_white_24dp"
/>
</android.support.constraint.ConstraintLayout>
<LinearLayout
android:id="#+id/vehicleContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dp_10"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="#dimen/dp_5"
android:paddingLeft="#dimen/dp_10"
android:paddingRight="#dimen/sp_10"
android:paddingTop="#dimen/dp_5"
>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imgVechicleImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="#drawable/imgcar_fullsize"
tools:layout_editor_absoluteX="18dp"
tools:layout_editor_absoluteY="38dp"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="vertical"
>
<TextView
android:id="#+id/txtVichecleModel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginStart="8dp"
android:fontFamily="#font/montserrat_regular"
android:text="Camaro 45"
android:textColor="#color/secondary_text"
android:textSize="12sp"
/>
<TextView
android:id="#+id/txtRegisterationNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="2dp"
android:fontFamily="#font/lato_regular"
android:text="Reg no. 1234"
android:textColor="#color/secondary_text"
android:textSize="12sp"
/>
</LinearLayout>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:padding="#dimen/dp_5"
>
<ImageView
android:id="#+id/imgRideIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="0dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="0dp"
android:padding="#dimen/dp_5"
android:src="#drawable/driver"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="#+id/matchCountTextView"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginBottom="4dp"
android:layout_marginTop="8dp"
android:background="#drawable/fill_circle_red"
android:fontFamily="#font/lato_regular"
android:gravity="center"
android:text="5"
android:textColor="#color/white"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="#+id/guideline3"
app:layout_constraintRight_toRightOf="#+id/imgRideIcon"
app:layout_constraintTop_toTopOf="parent"
/>
<android.support.constraint.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"
/>
</android.support.constraint.ConstraintLayout>
</LinearLayout>
<TextView
android:id="#+id/matchesTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/montserrat_regular"
android:padding="4dp"
android:text="You have 12 matches available"
android:textColor="#color/colorAccent"
android:textSize="14sp"
android:visibility="visible"
/>
<!--<Button
android:id="#+id/button_invite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Invite"
app:font="MontserratRegular"
android:textColor="#color/white"
android:background="#color/colorAccent"
android:layout_marginTop="8dp"
/>-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttonStartEnd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginTop="8dp"
android:background="#FF8A65"
android:fontFamily="#font/montserrat_regular"
android:text="Start Ride"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="16sp"
android:visibility="visible"
/>
</LinearLayout>
</com.daimajia.swipe.SwipeLayout>
</android.support.v7.widget.CardView>
DisplayMyRideFragmentViewHolder
package com.techugo.buno.fragments;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SwipeLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.techugo.buno.ActivityNavigator;
import com.techugo.buno.R;
import com.techugo.buno.activities.NewRideActivity;
import com.techugo.buno.activities.RatePassengersActivity;
import com.techugo.buno.app.MyApplication;
import com.techugo.buno.callbacks.RetrofitCallback;
import com.techugo.buno.common.BaseViewHolder;
import com.techugo.buno.common.events.HideLoadingEvent;
import com.techugo.buno.common.events.RefreshDependenciesEvent;
import com.techugo.buno.common.events.ShowLoadingEvent;
import com.techugo.buno.constant.AppConstant;
import com.techugo.buno.constant.ServerConstants;
import com.techugo.buno.dialog.RateDriverDialog;
import com.techugo.buno.helpers.AppUtilis;
import com.techugo.buno.home.events.ShowAddNameDialogEvent;
import com.techugo.buno.home.searchrides.SearchRideFragmentViewHolder;
import com.techugo.buno.home.sharerides.RidesAdapter;
import com.techugo.buno.loginsignup.models.User;
import com.techugo.buno.modals.NotificationResponseModel;
import com.techugo.buno.modals.UpcomingPromoModel;
import com.techugo.buno.modals.UpcomingResultModel;
import com.techugo.buno.networkInterFace.RetrofitApiService;
import com.techugo.buno.offers.OffersActivity;
import com.techugo.buno.ridedetail.Ride;
import com.techugo.buno.ridedetail.events.RideDetailEvents;
import com.techugo.framework.helper.TUGPrefs;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.OnClick;
public class DisplayMyRideFragmentViewHolder extends BaseViewHolder<List<Ride>> {
#Inject
RetrofitApiService retrofitApiService;
#Inject #Named("currentLoggedInUser")
User user;
#Inject
ActivityNavigator activityNavigator;
#BindView(R.id.upcomingRidesRecyclerView)
RecyclerView recyclerView;
#BindView(R.id.emptyLayout)
LinearLayout emptyLayout;
#BindView(R.id.text_no_internet_connection)
TextView noInternetTextView;
#BindView(R.id.loading_layout) LinearLayout progressBar;
#BindView(R.id.promo_card_view)
CardView promoCard;
#BindView(R.id.promo_title) TextView promoTitle;
private RidesAdapter ridesAdapter;
private List<Ride> myRidesModels;
private UpcomingPromoModel myPromoModel;
public DisplayMyRideFragmentViewHolder(View view, List<Ride> data, Context context) {
super(view,data,context);
this.myRidesModels = data;
this.context = context;
setUpRecyclerView();
setData(myRidesModels);
}
private void getUpComingRides() {
HashMap<String, Object> params = new HashMap<>();
params.put("method", ServerConstants.ALL_UPCOMING_RIDES);
params.put("user_id", user.getUser_id());
params.put("offset", "0");
params.put("limit", "20");
emptyLayout.setVisibility(View.GONE);
//progressBar.setVisibility(View.VISIBLE);
EventBus.getDefault().post(new ShowLoadingEvent(DisplayMyRideFragmentViewHolder.this.getClass().getSimpleName()));
//DisplayUtils.disableUserInteraction((Activity)context);
retrofitApiService.getUpComingRides(params)
.enqueue(new RetrofitCallback<UpcomingResultModel>() {
#Override protected void onSuccess(UpcomingResultModel upcomingResultModel) {
//progressBar.setVisibility(View.GONE);
EventBus.getDefault()
.post(new HideLoadingEvent(
DisplayMyRideFragmentViewHolder.this.getClass().getSimpleName()));
//DisplayUtils.enableUserInteraction((Activity)context);
myRidesModels.clear();
myRidesModels.addAll(upcomingResultModel.getData());
if(upcomingResultModel.getOffers() != null && upcomingResultModel.getOffers().size() > 0) {
myPromoModel = upcomingResultModel.getOffers().get(0);
promoCard.setVisibility(View.VISIBLE);
promoTitle.setText(myPromoModel.getPromo_title());
} else {
promoCard.setVisibility(View.GONE);
}
TUGPrefs.putString(AppConstant.IS_ANY_ACTIVE,
upcomingResultModel.getActive_ride_status());
initializeView(myRidesModels);
}
#Override protected void onError(String errorMessage) {
//progressBar.setVisibility(View.GONE);
//DisplayUtils.enableUserInteraction((Activity)context);
EventBus.getDefault()
.post(new HideLoadingEvent(
DisplayMyRideFragmentViewHolder.this.getClass().getSimpleName()));
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
if (!AppUtilis.isNetworkAvailable(context)) {
emptyLayout.setVisibility(View.GONE);
noInternetTextView.setVisibility(View.VISIBLE);
}
}
});
}
private void setUpRecyclerView() {
ridesAdapter = new RidesAdapter(myRidesModels, context);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(ridesAdapter);
// ridesAdapter.notifyDataSetChanged();
}
#Override
protected void attachListeners(List<Ride> data) {
}
#Override
protected void initializeView(#NonNull List<Ride> data) {
if (ridesAdapter != null && data.size() != 0) {
emptyLayout.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
ridesAdapter.setData(data);
} else {
recyclerView.setVisibility(View.GONE);
emptyLayout.setVisibility(View.VISIBLE);
}
noInternetTextView.setVisibility(View.GONE);
}
public void refreshView() {
MyApplication.getInstance().getNetComponent().inject(this);
getUpComingRides();
}
#OnClick(R.id.fab_search_ride) void onShareRideFabClick() {
//Intent intent = new Intent(context, FindRideActivity.class);
//context.startActivity(intent);
//if (user.getSignin_type().equals("1") && user.getReg_process().equals("0")) {
// AppUtilis.goToActivity(context, PhoneVerifyActivity.class);
// TUGPrefs.putString("ISFINDRIDE", "yes");
//} else {
//
//}
if (user.getFull_name() == null || user.getFull_name().isEmpty()) {
EventBus.getDefault().post(new ShowAddNameDialogEvent());
return;
}
activityNavigator.startActivity(context, NewRideActivity.class);
}
#OnClick(R.id.promo_card_view) void onPromoCardClick() {
activityNavigator.startActivity(context, OffersActivity.class);
}
#Override public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
refreshView();
}
#Override public void onResume() {
super.onResume();
}
#Override public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onReloadComponents(RefreshDependenciesEvent event) {
MyApplication.getInstance().getNetComponent().inject(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onRideRefresh(RideDetailEvents.RefreshRideDetailEvent event) {
refreshView();
String noty_retrieve = TUGPrefs.getString(AppConstant.IS_RATE_HAS_VALUE, "");
if (noty_retrieve.length() > 0) {
Gson gson = new Gson();
Type type = new TypeToken<NotificationResponseModel>() {
}.getType();
NotificationResponseModel notificationResponseModel = gson.fromJson(noty_retrieve, type);
if (notificationResponseModel != null) {
if (notificationResponseModel.getUser_type() != null
&& notificationResponseModel.getUser_type().equalsIgnoreCase("Driver")) {
Intent intent =
activityNavigator.getIntent(context, RatePassengersActivity.class);
intent.putExtra(AppConstant.NOTY_PASSANGER_DATA, noty_retrieve);
context.startActivity(intent);
} else {
new RateDriverDialog(context, notificationResponseModel).show();
}
}
}
}
}
Toast is working but constructor is not doing anything

is not abstract and does not override abstract method onClick(View) in OnClickListener

I'm trying to create a favourite button for a recipe application that I'm doing
I'm using an image button and have ran into the error message
Error:(19, 65) error: anonymous jbscookbook.example.com.fyp.FavouriteBtn$1 is not abstract and does not override abstract method onClick(View) in OnClickListener
here's my code
recipe.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/jbsbackground2"
android:orientation="vertical" >
<ImageView
android:id="#+id/iv_detail"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:scaleType="centerCrop"
android:src="#drawable/barbecuedporkribs" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="10dp"
android:layout_below="#+id/iv_detail"
android:background="#3D3C3A" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/iv_detail"
android:layout_marginTop="5dp"
android:text="Recipe"
android:layout_toLeftOf="#id/favourites"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="2dp"
android:text="TextView"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="italic" />
<TextView
android:id="#+id/tvFavourite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add To Favourites (click star)"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold"
android:layout_above="#+id/tvName"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageButton
android:id="#+id/favbtn"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/staroff"
android:background="#00ffffff"
android:onClick="onClickFavBtn"
android:clickable="true"/>
<TextView
android:id="#+id/tvTD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ingredients"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/tvIngredients"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvTD"
android:layout_marginTop="2dp"
android:text="TextView"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="italic" />
<TextView
android:id="#+id/tvK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvIngredients"
android:layout_marginTop="5dp"
android:text="Preparation"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="#+id/tvPreparation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/tvK"
android:layout_marginTop="2dp"
android:text="TextView"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="italic" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
FavouriteBtn.java
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class FavouriteBtn extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe);
final ImageButton imgButton = (ImageButton) findViewById(R.id.favbtn);
imgButton.setOnClickListener(new View.OnClickListener() {
public void onClickFavBtn(View v) {
boolean isFavourite = readState();
if (isFavourite) {
imgButton.setBackgroundResource(R.drawable.staroff);
isFavourite = false;
saveState(isFavourite);
} else {
imgButton.setBackgroundResource(R.drawable.staron);
isFavourite = true;
saveState(isFavourite);
}
}
});
}
private void saveState(boolean isFavourite) {
SharedPreferences aSharedPreferences = this.getSharedPreferences(
"Favourite", Context.MODE_PRIVATE);
SharedPreferences.Editor aSharedPreferencesEdit = aSharedPreferences
.edit();
aSharedPreferencesEdit.putBoolean("State", isFavourite);
aSharedPreferencesEdit.commit();
}
private boolean readState() {
SharedPreferences aSharedPreferences = this.getSharedPreferences(
"Favourite", Context.MODE_PRIVATE);
return aSharedPreferences.getBoolean("State", true);
}
}
I've tried a lot of different things that I found on the internet but nothing works.
Could someone help me in how to fix this problem and show me where I've gone wrong?
You have added the click functionality in xml. In that case you don't have to attach the click listener to the button. Listener implementation is required only if you haven't added the click functionality in xml. Use either of the approach, not both together.
Solution 1
Change
imgButton.setOnClickListener(new View.OnClickListener() {
public void onClickFavBtn(View v) {
boolean isFavourite = readState();
if (isFavourite) {
imgButton.setBackgroundResource(R.drawable.staroff);
isFavourite = false;
saveState(isFavourite);
} else {
imgButton.setBackgroundResource(R.drawable.staron);
isFavourite = true;
saveState(isFavourite);
}
}
});
to (just remove the listener attaching part)
public void onClickFavBtn(View v) {
boolean isFavourite = readState();
if (isFavourite) {
imgButton.setBackgroundResource(R.drawable.staroff);
isFavourite = false;
saveState(isFavourite);
} else {
imgButton.setBackgroundResource(R.drawable.staron);
isFavourite = true;
saveState(isFavourite);
}
}
Solution 2
Remove android:onClick="onClickFavBtn" from xml and
Change
public void onClickFavBtn(View v) {
to
public void onClick(View v) {
EDIT:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class FavouriteBtn extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe);
final ImageButton imgButton = (ImageButton) findViewById(R.id.favbtn);
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isFavourite = readState();
if (isFavourite) {
imgButton.setImageResource(R.drawable.staroff);
saveState(false);
} else {
imgButton.setImageResource(R.drawable.staron);
saveState(true);
}
}
});
}
private void saveState(boolean isFavourite) {
SharedPreferences aSharedPreferences = this.getSharedPreferences(
"Favourite", Context.MODE_PRIVATE);
SharedPreferences.Editor aSharedPreferencesEdit = aSharedPreferences
.edit();
aSharedPreferencesEdit.putBoolean("State", isFavourite);
aSharedPreferencesEdit.commit();
}
private boolean readState() {
SharedPreferences aSharedPreferences = this.getSharedPreferences(
"Favourite", Context.MODE_PRIVATE);
return aSharedPreferences.getBoolean("State", true);
}
}
Simply remove:
android:onClick="onClickFavBtn"
from your XML ImageButton
and change onClickFavBtn to onClick in listener.

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 do i exit runnable and switch another activity

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);

Categories