I'm trying to make a spreadsheat, but I face a problem - I get a "reandom" result returned by the dialog box.
my XML file:
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#FFFFFF"
android:orientation="vertical">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_marginVertical="30dp"
android:background="#FFFFFF">
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#020202"
android:layout_marginHorizontal="1dp"
android:layout_marginVertical="0dp">
<TextView
android:id="#+id/titleR"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="prod price"
android:background="#android:color/white"
android:layout_marginHorizontal="1dp"
android:layout_marginVertical="1dp"/>
<TextView
android:id="#+id/titleQ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Quantité"
android:background="#android:color/white"
android:layout_marginHorizontal="0dp"
android:layout_marginVertical="1dp"/>
<TextView
android:id="#+id/titleT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Totale"
android:background="#android:color/white"
android:layout_marginHorizontal="1dp"
android:layout_marginVertical="1dp"/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginHorizontal="1dp"
android:layout_marginVertical="0dp"
android:background="#020202"
android:baselineAligned="false"
>
<TextView
android:id="#+id/r5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginHorizontal="1dp"
android:layout_weight="1"
android:background="#android:color/white"
android:gravity="center"
android:text="v 5 usd"
/>
<EditText
android:id="#+id/q5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginHorizontal="0dp"
android:layout_marginVertical="0dp"
android:layout_weight="1"
android:background="#android:color/white"
android:gravity="center"
android:inputType="numberDecimal"
android:maxLength="5"
android:maxLines="1"
android:text="0"
/>
<TextView
android:id="#+id/t5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginHorizontal="1dp"
android:layout_marginVertical="0dp"
android:layout_weight="1"
android:background="#android:color/white"
android:gravity="center"
android:text=""/>
</TableRow>
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginHorizontal="1dp"
android:layout_marginVertical="0dp"
android:background="#020202"
>
<TextView
android:layout_marginTop="1dp"
android:id="#+id/myprc"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_marginBottom="1dp"
android:layout_marginHorizontal="1dp"
android:text="Pourcentage"
android:gravity="center"
android:onClick="onClick"
></TextView>
<TextView
android:layout_marginTop="1dp"
android:id="#+id/prcc"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginHorizontal="0dp"
android:layout_marginBottom="1dp"
android:layout_weight="1"
android:autoText="false"
android:background="#android:color/white"
android:clickable="true"
android:gravity="center"
android:inputType="text"
android:maxLength="2"
android:maxLines="1"
android:text="6%"></TextView>
><TextView
android:layout_marginTop="1dp"
android:id="#+id/prcT"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_weight="1"
android:background="#android:color/white"
android:layout_marginBottom="1dp"
android:layout_marginHorizontal="1dp"
></TextView>
</TableRow>
</TableLayout>
</RelativeLayout>
my java code:
package com.example.mcalc;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
TextView myprc;
EditText q5;
TextView t5;
TextView t50;
TextView prcc;// cel
TextView prcT;
double prc1;
DecimalFormat tst = new DecimalFormat(" #,0.00 '%'");
EditText input;// dilog input
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabble);
myprc = (TextView)findViewById(R.id.myprc);
q5 = (EditText) findViewById(R.id.q5);
t5 = (TextView) findViewById(R.id.t5);
t50 = (TextView) findViewById(R.id.t50);
prcc = (TextView) findViewById(R.id.prcc) ;//cel
prcT = (TextView) findViewById(R.id.prcT);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pourcentage");
builder.setMessage("Merci d entrer le %");
input=new EditText(this);
builder.setView(input);
////
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
prc1 = Double.parseDouble(input.getText().toString());
String str;
str= String.valueOf(((Double) prc1));
prcc.setText(str+"%");
}
});
final AlertDialog ad = builder.create();
//Click listener Pourcentage %
myprc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ad.show();
}
});
q5.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
double tq5;
if ((q5.getText().length() == 0)) {
t5.setText("");
} else {
tq5 = (Double.valueOf(q5.getText().toString())*5) -
(Double.valueOf(q5.getText().toString())*5*prc1);
t5.setText(""+tq5);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
prcc.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
double prc;
if ((prcc.getText().length() == 0)) {
prcT.setText("");
} else {
prcT.setText("blabla");
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Related
I have made three activities these are:
sendOTPone
verificationOTPtwo
dashboard
When I clicked on submit button from OTP verification screen then it will not let me go in dashboard screen my app closes automatically after this. Can anyone tell me where I did the mistake?
XML code for verificationOTPtwo
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
android:overScrollMode="never"
android:scrollbars="none"
tools:context=".verificationOTPtwo">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="130dp"
android:layout_height="130dp"
android:layout_marginTop="80dp"
android:contentDescription="#string/app_name"
android:src="#drawable/recieved" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="OTP Verififcation"
android:textColor="#color/colorTextFirst"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="50dp"
android:gravity="center"
android:text="Please enter the OTP sent to you"
android:textColor="#color/colorTextSecond"
android:textSize="14sp" />
<TextView
android:id="#+id/textmobileshownumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="4dp"
android:layout_marginEnd="50dp"
android:gravity="center"
android:textColor="#color/colorTextFirst"
android:textSize="14sp"
android:textStyle="bold" />
//###############################################
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:orientation="horizontal">
<EditText
android:id="#+id/inputotp1"
android:layout_width="40dp"
android:layout_height="46dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp2"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp3"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp4"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp5"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
<EditText
android:id="#+id/inputotp6"
android:layout_width="40dp"
android:layout_height="46dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:background="#drawable/background"
android:gravity="center"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="number"
android:maxLength="1"
android:textColor="#color/colorTextFirst"
android:textSize="24sp"
android:textStyle="bold"
tools:ignore="LabelFor" />
</LinearLayout>
//################################################
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Not received OTP ?"
android:textColor="#color/colorTextSecond"
android:textSize="14sp" />
<TextView
android:id="#+id/textresendotp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="RESEND OTP AGAIN"
android:textColor="#color/colorTextFirst"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/buttonotpsubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:background="#drawable/backgroundbutton"
android:text="Submit"
android:textColor="#color/white"
android:textStyle="bold" />
<ProgressBar
android:id="#+id/progressbar_verify_otp"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
</ScrollView>
Java code for verificationOTPtwo
package com.example.animatedsplashdemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class verificationOTPtwo extends AppCompatActivity {
EditText inputnumber1, inputnumber2, inputnumber3, inputnumber4, inputnumber5, inputnumber6;
String getotpbackend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification_otptwo);
final Button verifyButtonClick = findViewById(R.id.buttonotpsubmit);
inputnumber1 = findViewById(R.id.inputotp1);
inputnumber2 = findViewById(R.id.inputotp2);
inputnumber3 = findViewById(R.id.inputotp3);
inputnumber4 = findViewById(R.id.inputotp4);
inputnumber5 = findViewById(R.id.inputotp5);
inputnumber6 = findViewById(R.id.inputotp6);
TextView textView = findViewById(R.id.textmobileshownumber);
textView.setText(String.format(
"+91-%s", getIntent().getStringExtra("mobile")
));
getotpbackend = getIntent().getStringExtra("backendotp");
final ProgressBar progressBarverifyotp = findViewById(R.id.progressbar_verify_otp);
verifyButtonClick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!inputnumber1.getText().toString().trim().isEmpty() && !inputnumber2.getText().toString().trim().isEmpty() && !inputnumber3.getText().toString().trim().isEmpty() && !inputnumber4.getText().toString().trim().isEmpty() && !inputnumber5.getText().toString().trim().isEmpty() && !inputnumber6.getText().toString().trim().isEmpty()) {
String entercodeotp = inputnumber1.getText().toString() +
inputnumber2.getText().toString() +
inputnumber3.getText().toString() +
inputnumber4.getText().toString() +
inputnumber5.getText().toString() +
inputnumber6.getText().toString();
if (getotpbackend != null) {
progressBarverifyotp.setVisibility(View.VISIBLE);
verifyButtonClick.setVisibility(View.INVISIBLE);
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(
getotpbackend, entercodeotp
);
FirebaseAuth.getInstance().signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBarverifyotp.setVisibility(View.GONE);
verifyButtonClick.setVisibility(View.VISIBLE);
if (task.isSuccessful()) {
Intent intent = new Intent(getApplicationContext(), dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(verificationOTPtwo.this, "Enter the correct OTP", Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(verificationOTPtwo.this, "Please check internet connection", Toast.LENGTH_SHORT).show();
}
// Toast.makeText(verificationOTPtwo.this, "OTP Verified", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(verificationOTPtwo.this, "Please enter the OTP", Toast.LENGTH_SHORT).show();
}
}
});
numberotpmove();
TextView resendlabel = findViewById(R.id.textresendotp);
resendlabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+91" + getIntent().getStringExtra("mobile"),
60,
TimeUnit.SECONDS,
verificationOTPtwo.this,
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(verificationOTPtwo.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCodeSent(#NonNull String newbackendotp, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
getotpbackend = newbackendotp;
Toast.makeText(verificationOTPtwo.this, "OTP sended successfully", Toast.LENGTH_SHORT).show();
}
}
);
}
});
}
private void numberotpmove() {
inputnumber1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber2.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber3.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber3.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber4.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber4.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber5.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
inputnumber5.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!s.toString().trim().isEmpty()) {
inputnumber6.requestFocus();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
dashboard.java :
package com.example.animatedsplashdemo;
import android.os.Bundle;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
public class dashboard extends AppCompatActivity {
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
drawerLayout = findViewById(R.id.drawerlayout);
navigationView = findViewById(R.id.navigationview);
toolbar = findViewById(R.id.toolbar);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_open, R.string.navigation_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
setSupportActionBar(toolbar);
}
}
Logcat:
2022-04-03 01:27:14.483 21162-21162/com.example.animatedsplashdemo
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.animatedsplashdemo, PID: 21162
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.animatedsplashdemo/com.example.animatedsplashdemo.dashboard}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3792)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1139)
Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:581)
at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:183)
at com.example.animatedsplashdemo.dashboard.onCreate(dashboard.java:32)
at android.app.Activity.performCreate(Activity.java:8198)
at android.app.Activity.performCreate(Activity.java:8182)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3765)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3968)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8506)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1139)
Set windowActionBar false in your AppTheme.
<item name="windowActionBar">false</item>
Hope this will help you.
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
I'm trying to find out how to set a string that will be read out-loud.
For example:
String text = "Hello";
You can find a very detail example that show how to convert text to speech on this site. HTH.
Your MainActivity.java should look something like this
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.Toast;
public class MainActivity extends Activity {
TextToSpeech t1;
EditText ed1;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button);
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
public void onPause(){
if(t1 !=null){
t1.stop();
t1.shutdown();
}
super.onPause();
}
}
And here is the content of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:transitionGroup="true">
<TextView android:text="Text to Speech" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="#+id/textView"
android:layout_below="#+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src="#drawable/abc"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:theme="#style/Base.TextAppearance.AppCompat" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_below="#+id/imageView"
android:layout_marginTop="46dp"
android:hint="Enter Text"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#ff7aff10"
android:textColorHint="#ffff23d1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to Speech"
android:id="#+id/button"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
</RelativeLayout>
the question I going to ask, might be kind of complicated.
Pardon me, if I can't explain it clearly.
It's my first time having touch with android coding.
I would like to do a calculation doing android .
It's about Fuel Log.
What I want to do right now is
When I keep in the price(edittext) and pump(edittext),
the output will be shown straight away in the cost(textview), that I've placed.
I would want to do that,
but I don't think I have did the right coding for it.
I've tried out myself,
but I didn't run the application, cause I think that the codes I've done is not fully completed/right.
I would love to hear the advice from you guys.
Could someone please help me out with it?
Thank you,
your help will be much appreciate.
(:
MainActivity.java
public class MainActivity extends Activity {
Button saveButton = null;
EditText dateEdit;
EditText priceEdit;
EditText pumpEdit;
TextView costView;
EditText odometerEdit;
TextView fconView;
public boolean isNumeric(String str)
{
return str.matches("-?\\d+(\\.\\d+)?");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle bundle = getIntent().getExtras();
float price = Float.parseFloat(bundle.getString("priceEdit"));
float pump = Float.parseFloat(bundle.getString("pumpEdit"));
costView = (TextView)findViewById(R.id.tcost);
dateEdit = (EditText)findViewById(R.id.date);
priceEdit = (EditText)findViewById(R.id.fuelprice);
pumpEdit = (EditText)findViewById(R.id.fuelpump);
TextWatcher mCostChangeWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!TextUtils.isEmpty(priceEdit.getText()) && !TextUtils.isEmpty(pumpEdit.getText())){
costView.setText(calculateCost(priceEdit.getText(), pumpEdit.getText()));
}
}
private float calculateCost(float price, float pump) {
final float costCal = (price * pump);
return costCal;
// TODO Auto-generated method stub
}
};
priceEdit.addTextChangedListener(mCostChangeWatcher);
pumpEdit.addTextChangedListener(mCostChangeWatcher);
saveButton = (Button) findViewById(R.id.saveBTN);
saveButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try
{
dbAdaptor.open();
String date = dateEdit.getText().toString();
String price = priceEdit.getText().toString();
String pump = pumpEdit.getText().toString();
String cost = Float.toString();
String odometer = odometerEdit.getText().toString();
String fcon = fconView.getText().toString();
dbAdaptor.insertLog(date, price, pump, cost, odometer, fcon);
}
catch(Exception e){
Log.d("Fuel Log", e.getMessage());
}
finally
{
if(dbAdaptor != null)
dbAdaptor.close();
}
}
});
}//oncreate
}//main
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/date"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpricetxtview"
android:text="#string/fuelprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpumptxtview"
android:text="#string/fuelpump"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelpump"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/totalcosttxtview"
android:text="#string/totalcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/tcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/odometertxtview"
android:text="#string/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/fcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveBTN"
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/cancelBTN"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</LinearLayout>
</LinearLayout>
add change lister to both edit text
priceEdit.addTextChangedListener(mCostChangeWatcher);
pumpEdit.addTextChangedListener(mCostChangeWatcher);
TextWatcher mCostChangeWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(!TextUtils.isEmpty(priceEdit.getText()) && !TextUtils.isEmpty(pumpEdit.getText())){
costEdit.setText(calculateCost(priceEdit.getText(), pumpEdit.getText()));
}
}
};
I have made a CustomTypeDialog class and what I want is to use EditText which is not in the active layout. I get a nullpointer exception when I try to click one of the buttons, which I think is because they are not in the active layout. Can you help me solve this? The dialog is called in an activity from another class.
package dk.droidrun.droidrunapp;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
public class CustomTypeDialog extends Dialog {
ImageButton routeType;
EditText txtType;
Button imageRun, imageBike, imageWalk;
public CustomTypeDialog(final Context context) {
super(context);
this.setContentView(R.layout.customtype_dialog);
routeType = (ImageButton)findViewById(R.id.saveRoute_activityType);
txtType = (EditText)findViewById(R.id.saveRoute_typeTxt);
imageRun = (Button)findViewById(R.id.dialog_btn1);
imageBike = (Button)findViewById(R.id.dialog_btn2);
imageWalk = (Button)findViewById(R.id.dialog_btn3);
setTitle("Select activity type");
show();
imageRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtType.setText("Run");
routeType.setBackgroundResource(R.drawable.track_run);
}
});
imageBike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtType.setText("Bike");
routeType.setBackgroundResource(R.drawable.track_bike);
}
});
imageWalk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtType.setText("Walk");
routeType.setBackgroundResource(R.drawable.track_walk);
}
});
}
}
This is my customtype_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".AutoMode"
android:background="#color/black" >
<RelativeLayout
android:id="#+id/dialog_relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:layout_above="#+id/dialog_relativeLayout2"
android:layout_centerHorizontal="true" >
<Button
android:id="#+id/dialog_btn1"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_margin="3dp"
android:background="#drawable/track_run"
android:layout_alignRight="#+id/dialog_relativeLayout1"
android:layout_alignTop="#+id/dialog_relativeLayout1"
/>
<Button
android:id="#+id/dialog_btn2"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_margin="3dp"
android:background="#drawable/track_bike"
android:layout_alignTop="#+id/dialog_relativeLayout1"
android:layout_toRightOf="#+id/dialog_btn1"
/>
<Button
android:id="#+id/dialog_btn3"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_margin="3dp"
android:layout_toRightOf="#+id/dialog_btn2"
android:background="#drawable/track_walk"
/>
</RelativeLayout>
</RelativeLayout>
saveroutes.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:background="#color/black"
tools:context=".SaveRouteActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="#string/saveRoute"
android:textColor="#color/white"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_marginTop="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7a0100"
android:text="Enter a name for the route" />
<EditText
android:id="#+id/saveRoute_nameRoute"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:hint="#string/saveRoute_name"
android:textColor="#color/white"
android:background="#4e4751"
android:inputType="textPersonName" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7a0100"
android:text="Describe your route" />
<EditText
android:id="#+id/saveRoute_desciptionTxt"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="10"
android:hint="#string/saveRoute_description"
android:textColor="#color/white"
android:background="#4e4751"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7a0100"
android:text="Activity type (e.g. running)"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal" >
<EditText
android:id="#+id/saveRoute_typeTxt"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginTop="17dip"
android:ems="10"
android:layout_marginLeft="30dp"
android:hint="#string/saveRoute_type"
android:textColor="#color/white"
android:background="#4e4751" >
<requestFocus />
</EditText>
<ImageButton
android:id="#+id/saveRoute_activityType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/track_walk" />
</LinearLayout>
<Button
android:id="#+id/saveRoute_saveBtn"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:background="#color/white"
android:text="#string/saveRoute_savebutton" />
<Button
android:id="#+id/saveRoute_cancelBtn"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:background="#color/white"
android:text="#string/saveRoute_cancel" />
</LinearLayout>
You cannot access views from another layout (your activity) using findViewById within the dialog view.
You need to add a callback listener for when the buttons on your dialog are clicked:
public interface OnDialogClickListener {
void onDialogImageRunClick();
}
public class CustomTypeDialog extends Dialog {
private final OnDialogClickListener listener;
public CustomTypeDialog(final Context context, OnDialogClickListener listener) {
this.listener = listener;
}
....
imageRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onDialogImageRunClick();
}
);
}
Then when you create your dialog in your Activity where you have access to the view:
new CustomTypeDialog(context, new CustomTypeDialog.OnDialogClickListener() {
#Override
public void onDialogImageRunClick() {
txtType.setText("Run");
routeType.setBackgroundResource(R.drawable.track_run);
}
});