Using my onEditTextchanger. It works fine when the user inputs 100000, in the EditText box it shows $100,000.00 as the user types. Which is correct.
The problem is however if I try to display a numeric keyboard rather than a Qwerty keyboard. By adding in the XML I add android: inputType=”numberDecimal” I lose the formatting of $ and the, and the EditText displays like 100000.00. I have noticed this happens if I change the InputType to Number or Decimal as well. I have attached the code.
Any ideas? Again Thanks in advance for your help.
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/txta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="0" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number2" />
<EditText
android:id="#+id/txtb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="0" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number3" />
<TextView
android:id="#+id/txtc"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Answer is"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtd"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate" />
Java
public class CalcTestActivity extends Activity {
private EditText txta;
private EditText txtb;
private TextView txtc;
private TextView txtd;
private double a = 0;
private double b = 0;
private double c = 0;
private double d = 0;
private Button buttonCalc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
txta.addTextChangedListener(new CurrencyTextWatcher());
txtb.addTextChangedListener(new CurrencyTextWatcher());
}
private void initControls() {
txta = (EditText)findViewById(R.id.txta);
txtb = (EditText)findViewById(R.id.txtb);
txtc = (TextView)findViewById(R.id.txtc);
txtd = (TextView)findViewById(R.id.txtd);
buttonCalc = (Button)findViewById(R.id.buttonCalc);
buttonCalc.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {calculate(); }});}
private void calculate() {
a=Double.parseDouble(txta.getText().toString().replace("$", "").replace(",", ""));
b=Double.parseDouble(txtb.getText().toString().replace("$", "").replace(",", ""));
c=Math.round(a*.88);
txtc.setText(GlobalMoney.FormatValue(c));
d=Math.round((a*.87)+(b*.61)*(c*.25));
txtd.setText(GlobalMoney.FormatValue(d));
}
}
TextWatcher
import java.text.NumberFormat;
import android.text.Editable;
import android.text.TextWatcher;
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
public CurrencyTextWatcher() {
mEditing = false;
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
try{
String formatted = nf.format(Double.parseDouble(digits)/100);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
By default, inputType=”numberDecimal” doesn't accept any special characters except .(dot). May be you need to do some hack to make this work. There is an interesting SO discussion to hack in special character ','. You may try that to have $ symbol. Here is link.
Related
So I want to read the input of an EditText field. It is not working. I debugged it and I saw, that the EditText view was listed there. But when I printed it to the console, it was empty. I don't know why, because I did put a text in it. Also, the ID is right, and I really don't know what's wrong
Here is the View where the EditText is:
<?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=".counters.AddCounter">
<TextView
android:id="#+id/txtNewCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/allerta"
android:text="#string/addNewCounter"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnSaveCounter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/allerta"
android:text="#string/save"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/txtCounterName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/allerta"
android:text='#string/newCounterName'
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtNewCounter" />
<EditText
android:id="#+id/inpuTextNewCounterName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:contentDescription="#string/name"
android:ems="10"
android:hint="#string/name"
android:inputType="textPersonName"
android:singleLine="true"
android:text="Cookies don't"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtCounterName" />
<TextView
android:id="#+id/txtCounterEntryValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/allerta"
android:text="#string/entryNum"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/inpuTextNewCounterName" />
<EditText
android:id="#+id/numEntryNum"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:ems="10"
android:hint="#string/number"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtCounterEntryValue" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my code to evaluate the form:
public class AddCounter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_counter);
//Setting save button action listener
findViewById(R.id.btnSaveCounter).setOnClickListener(new ActionListeners().getSaveCounter());
}
public static void evaluateCounter(View view) throws NoNameException, NumberOutOfBoundException {
//Getting context
Context context = view.getContext();
//Counter Name
View viewEdit = View.inflate(context, R.layout.activity_add_counter, null);
EditText counterName = viewEdit.findViewById(R.id.inpuTextNewCounterName);
System.out.println("Cookies fly like:" + counterName.getText().toString() + "!");
//Input to string
String name = counterName.getText().toString();
//If no name was specified exception thrown
if (name.equals("")) {
throw new NoNameException(context.getString(R.string.noNameSpecified));
}
//get entry number
EditText numberView = View.inflate(context, R.layout.activity_add_counter, null).findViewById(R.id.numEntryNum);
//Number
int number = 0;
//If nothing specified
if (!(numberView.getText().toString().equals(""))) {
if (Integer.parseInt(numberView.getText().toString()) > 1000 || Integer.parseInt(numberView.getText().toString()) < -1000) {
throw new NumberOutOfBoundException(context.getString(R.string.numOutOfBound));
}
}
//New Counter Object
Counter counter = new Counter(number, name);
//storing counter
ToJson toJson = new ToJson();
toJson.storeCounter(counter, context);
}
}
As you can see here, this if-statement is always true.
To look, what the text looks like, I printed out a text:
System.out.println("Cookies fly like:" + counterName.getText().toString() + "!");
I did put a word in the input and the output is empty, as you can see here:
I/System.out: Cookies fly like:!
Here is my ActionListener:¨
public class ActionListeners {
private OnClickListener saveCounter = v -> {
try {
//Evaluate Counter
AddCounter.evaluateCounter(v);
} catch (NoNameException e) {
//If no name was specified
CounterMethods.makeSnackbar(v, Snackbar.LENGTH_SHORT, HapticFeedbackConstants.REJECT, v.getContext().getString(R.string.noNameSpecified));
e.printStackTrace();
} catch (NumberOutOfBoundException e) {
//If entry is higher or lower than available
CounterMethods.makeSnackbar(v, Snackbar.LENGTH_SHORT, HapticFeedbackConstants.REJECT, v.getContext().getString(R.string.numOutOfBound));
}
};
public OnClickListener getSaveCounter() {
return this.saveCounter;
}
}
As you can see, I did set the text to "Cookies can't fly" in the xml file, however, if I change the text to something different in the app, the output is the text I did set in the XML.
I/System.out: Cookies fly like:Cookies can't fly!
What is the problem?
try this
public class AddCounter extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_counter);
//declare Counter Name EditText
EditText counterName = findViewById(R.id.inpuTextNewCounterName);
//declare btnSaveCounter Button
Button btnSaveCounter = findViewById(R.id.btnSaveCounter);
//declare get entry number EditText
EditText numberView = findViewById(R.id.numEntryNum);
//btnSaveCounter setOnClickListener
btnSaveCounter.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//Input to string
String name = counterName.getText().toString();
System.out.println("Cookies fly like:" + name + "!");
//If no name was specified
if (name.equals("")){
System.out.println( "getString(R.string.noNameSpecified)" );//todo
}
//If nothing specified
String numbrv = numberView.getText().toString();
if (!(numbrv.equals(""))){
if (Integer.parseInt(numbrv) > 1000 || Integer.parseInt(numbrv) < -1000) {
System.out.println( "getString(R.string.numOutOfBound)" );//todo
}
}
//Number
int number = 0;
//New Counter Object
Counter counter = new Counter(number, name);
//storing counter
ToJson toJson = new ToJson();
toJson.storeCounter(counter, context);
} });
}
}
I don't know why I confuse with simple if/ else condition? In my app, phone verification part, Bydefault I set sendVerification button disable, and when I enter text then it should enable. but it is not enabling? What is wrong with my condition? even if I try with else part, same problem!
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=".PhoneAuthActivity">
<include
android:id="#+id/PhoneToolbar"
layout="#layout/app_bar">
</include>
<LinearLayout
android:id="#+id/DialLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/PhoneToolbar"
android:orientation="horizontal"
android:weightSum="10">
<ImageView
android:id="#+id/dial"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="#drawable/dial"
android:layout_weight="1"/>
<EditText
android:id="#+id/PhoneNumber"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:layout_weight="8"
android:ems="10"
android:inputType="phone"/>
<ProgressBar
android:id="#+id/PhoneProgress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/LockLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/DialLayout"
android:orientation="horizontal"
android:weightSum="10">
<ImageView
android:id="#+id/lock"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:padding="10dp"
android:src="#drawable/lock"
android:layout_weight="1"/>
<EditText
android:id="#+id/code"
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Verification Code"
android:layout_weight="8"/>
<ProgressBar
android:id="#+id/CodeProgress"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<TextView
android:id="#+id/VerificationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="91dp"
android:text="A verification code will be sent to your phone number" />
<Button
android:id="#+id/sendVerification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="23dp"
android:backgroundTint="#FF0000"
android:text="Send Verification" />
</RelativeLayout>
And this is Activity
package com.jimmytrivedi.lapitchat;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class PhoneAuthActivity extends AppCompatActivity {
private LinearLayout DialLayout, LockLayout;
private EditText PhoneNumber, code;
private ProgressBar PhoneProgress, CodeProgress;
private Button sendVerification;
private Toolbar PhoneToolbar;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_auth);
DialLayout = findViewById(R.id.DialLayout);
LockLayout = findViewById(R.id.LockLayout);
PhoneNumber = findViewById(R.id.PhoneNumber);
code = findViewById(R.id.code);
PhoneProgress = findViewById(R.id.PhoneProgress);
CodeProgress = findViewById(R.id.CodeProgress);
sendVerification = findViewById(R.id.sendVerification);
PhoneToolbar = findViewById(R.id.PhoneToolbar);
PhoneProgress.setVisibility(View.INVISIBLE);
CodeProgress.setVisibility(View.INVISIBLE);
sendVerification.setEnabled(false);
setSupportActionBar(PhoneToolbar);
getSupportActionBar().setTitle("Welcome to Phone Verification");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
number = PhoneNumber.getText().toString();
if (!number.isEmpty()) {
sendVerification.setEnabled(true);
}
sendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PhoneNumber.setEnabled(false);
PhoneProgress.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
PhoneAuthActivity.this,
mCallbacks
);
}
});
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
}
#Override
public void onVerificationFailed(FirebaseException e) {
}
};
}
}
number = PhoneNumber.getText().toString();
if (!number.isEmpty()) {
sendVerification.setEnabled(true);
}
This is all executed in onCreate before you get the chance to start typing. Once you start typing this code is not executed again. It is only executed once, when the activity is being created.
Solution: set up a TextWatcher on the phone number editText and enable/disable sendVerification in the TextWatcher#afterTextChanged method. See here for instructions on how to do it.
In your code
number = PhoneNumber.getText().toString();
if (!number.isEmpty()) {
sendVerification.setEnabled(true);
}
is executed only once at onCreate. You'll have to add a text change listener and enable/disable the button accordingly
like,
PhoneNumber.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {}
#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.length() > 0)
{
sendVerification.setEnabled(true);
}
}
});
You need a TextWatcher to do what you wish to do, so add a TextWatcher to your EditText/TextView like below:
PhoneNumber.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.length()>0) {
sendVerification.setEnabled(true);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
The reason your code wasn't working is because the onCreate() method does not get called after you start typing, meaning the condition for enabling your view is checked only once so any changes are not checked again.
first of all, I'll explain the expected behavior of the App.
What does the App do?
When I run the App I see this view:
Now if you hit the "+" button you'll see this Dialog:
By clicking Add this entry will be added to a ListView. I added two items. This looks like this:
Expected Result
Now when I touch and hold the mic icon of the list items it should start recording audio through the device microphone and then save this recording with the name of the bold entry, that means e.g. the first recording will get the name A.3gp, the second one B.3gp and so on..
Actual Result (UPDATE 07.12.2017)
The current state is:
Every item in the list gets his "own" recording. That means if I touch and hold the microphone icon of the first item in the list, it is doing what it should do. The same goes for all other items on the list.
When I add the first item A, then touch its record icon, a file will be created with the name A.3gp (which is correct behavior).
When I add the second item B then do nothing and then add a third item C and touch the record icon for B, a file will be created with the name C.3gp (which is not a correct behavior, it should be B.3gp).
Now to the fun part.
Code (UPDATE 07.12.2017)
1. The Model
public class Word {
private String mForeignTranslation;
private String mDefaultTranslation;
private ImageView mRecordIconImageResourceId;
private MediaRecorder mMediaRecorder;
public Word(String foreignTranslation, String defaultTranslation, ImageView recordIconImageResourceId) {
this.mForeignTranslation = foreignTranslation;
this.mDefaultTranslation = defaultTranslation;
this.mRecordIconImageResourceId = recordIconImageResourceId;
}
public Word(String foreignTranslation, String defaultTranslation) {
this.mForeignTranslation = foreignTranslation;
this.mDefaultTranslation = defaultTranslation;
}
public String getDefaultTranslation() {
return mDefaultTranslation;
}
public String getForeignTranslation() {
return mForeignTranslation;
}
public ImageView getRecordIconImageResourceId() {
return mRecordIconImageResourceId;
}
public MediaRecorder getMediaRecorder() {
return mMediaRecorder;
}
public void setDefaultTranslation(String mDefaultTranslation) {
this.mDefaultTranslation = mDefaultTranslation;
}
public void setForeignTranslation(String mForeignTranslation) {
this.mForeignTranslation = mForeignTranslation;
}
public void setRecordIconImageResourceId(ImageView recordIconImageResourceId) {
this.mRecordIconImageResourceId = recordIconImageResourceId;
}
public void setMediaRecorder(MediaRecorder mMediaRecorder) {
this.mMediaRecorder = mMediaRecorder;
}
}
2. The Adapter
public class WordAdapter extends ArrayAdapter<Word> {
private ArrayList<Word> wordsArrayList = new ArrayList<>();
private MediaRecorder mediaRecorder = new MediaRecorder();
public WordAdapter(#NonNull Context context, ArrayList<Word> words) {
super(context, 0, words);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.my_word_list_items,parent,false);
}
Word currentWord = getItem(position);
TextView foreignWord = listItemView.findViewById(R.id.myForeignWord);
foreignWord.setText(currentWord.getForeignTranslation());
TextView defaultWord = listItemView.findViewById(R.id.myDefaultWord);
defaultWord.setText(currentWord.getDefaultTranslation());
final ImageView recordIconImageView = listItemView.findViewById(R.id.recordIconImageView);
wordsArrayList = MyWordsActivity.getWordsArrayList();
recordIconImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN: {
recordIconImageView.setImageResource(R.drawable.mic_red);
startAudioRecording();
break;
}
case MotionEvent.ACTION_UP: {
recordIconImageView.setImageResource(R.drawable.mic_black);
stopAudioRecording();
break;
}
}
return true;
}
});
return listItemView;
}
private ArrayList<Word> getWordsArrayList() {
return wordsArrayList;
}
private void startAudioRecording() {
if (wordsArrayList != null) {
Log.i("ArrayListe", wordsArrayList.toArray().toString());
getMediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
Toast.makeText(this.getContext(), "Recording started", Toast.LENGTH_SHORT).show();
}
}
private void stopAudioRecording() {
try {
mediaRecorder.stop();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this.getContext(), "Recording stopped", Toast.LENGTH_SHORT).show();
}
private void getMediaRecorderReady() {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"speakmylanguage"+"/"+MyWordsActivity.getForeignWord()+".3gp");
}
}
3. The Activity
public class MyWordsActivity extends AppCompatActivity {
private static String defaultWord, foreignWord;
private static ArrayList<Word> wordsArrayList = new ArrayList<>();
WordAdapter wordAdapter;
// Main Activity Views
TextView hintTextView;
ListView myWordsListView;
FloatingActionButton floatingButtonAddNewWord;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_words);
// Init Main Activity Views
hintTextView = findViewById(R.id.hintTextView);
myWordsListView = findViewById(R.id.myWordsList);
floatingButtonAddNewWord = findViewById(R.id.fabAddNewWord);
floatingButtonAddNewWord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog addNewWordsDialog = new Dialog(MyWordsActivity.this);
addNewWordsDialog.setContentView(R.layout.activity_add_new_words);
final EditText addForeignWordEditText = addNewWordsDialog.findViewById(R.id.addForeignWordEditText);
final EditText addDefaultWordEditText = addNewWordsDialog.findViewById(R.id.addDefaultWordEditText);
final Button addNewWordButton = addNewWordsDialog.findViewById(R.id.addNewWordButton);
addNewWordsDialog.show();
addNewWordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!addDefaultWordEditText.getText().toString().equals("") &&
!addForeignWordEditText.getText().toString().equals("")) {
foreignWord = addForeignWordEditText.getText().toString();
defaultWord = addDefaultWordEditText.getText().toString();
wordsArrayList.add(new Word(foreignWord, defaultWord));
hintTextView.setVisibility(View.GONE);
addNewWordsDialog.dismiss();
} else {
Toast.makeText(MyWordsActivity.this, "Please enter two words", Toast.LENGTH_SHORT).show();
}
}
});
wordAdapter = new WordAdapter(MyWordsActivity.this, getWordsArrayList());
myWordsListView.setAdapter(wordAdapter);
}
});
}
public static String getDefaultWord() {
return defaultWord;
}
public static void setDefaultWord(String defaultWord) {
MyWordsActivity.defaultWord = defaultWord;
}
public static String getForeignWord() {
return foreignWord;
}
public static void setForeignWord(String foreignWord) {
MyWordsActivity.foreignWord = foreignWord;
}
public static ArrayList<Word> getWordsArrayList() {
return wordsArrayList;
}
}
4. The Layouts
<?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:id="#+id/myRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/myWordsListItems"
android:layout_width="match_parent"
android:layout_height="88dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginStart="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/myForeignWord"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="bottom"
android:textAppearance="?android:textAppearanceMedium"
android:textSize="24sp"
android:textStyle="bold"
tools:text="foreign word" />
<TextView
android:id="#+id/myDefaultWord"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:textAppearance="?android:textAppearanceMedium"
android:textSize="24sp"
tools:text="default word" />
</LinearLayout>
<ImageView
android:id="#+id/playIconImageView"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="16dp"
android:clickable="true"
android:src="#drawable/play_icon" />
<ImageView
android:id="#+id/recordIconImageView"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="72dp"
android:clickable="true"
android:src="#drawable/mic_black" />
</RelativeLayout>
activity_my_words.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.yousef.mustafa.speakmylanguage.View.MyWordsActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:title="#string/app_name"
app:titleTextColor="#color/colorWhite" />
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myWordsList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
android:drawSelectorOnTop="true"
android:orientation="vertical"
tools:context=".View.MyWordsActivity" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabAddNewWord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="bottom|center"
android:layout_marginBottom="32dp"
android:tint="#color/colorWhite"
app:backgroundTint="#color/colorGrey"
app:srcCompat="#drawable/icon_add" />
<TextView
android:id="#+id/hintTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="155dp"
android:gravity="center"
android:text="#string/hint"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
activity_add_new_words.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorDialogBackground">
<LinearLayout
android:id="#+id/addNewWordLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="8dp"
android:layout_marginTop="12dp"
android:text="#string/add_word_title"
android:textColor="#color/colorBlack"
android:textSize="24sp"
android:textStyle="bold" />
<EditText
android:id="#+id/addForeignWordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="4dp"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:layout_weight="5"
android:gravity="center_horizontal"
android:hint="#string/enter_foreign_word"
android:inputType="textPersonName|textCapWords"
android:textSize="24sp" />
<EditText
android:id="#+id/addDefaultWordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginEnd="12dp"
android:layout_marginStart="12dp"
android:layout_marginTop="4dp"
android:layout_weight="5"
android:gravity="center_horizontal"
android:hint="#string/enter_default_word"
android:inputType="textPersonName|textCapWords"
android:textSize="24sp" />
<Button
android:id="#+id/addNewWordButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="#string/button_add"
android:textAllCaps="false"
android:textSize="18sp" />
</LinearLayout>
</RelativeLayout>
I would appreciate any help. Thanks in advance.
In the startAudioRecording() method of the Activity, you set the output filename from the foreignWord field. The problem is that the foreignWord field is set to the most recently added foreign word each time the user submits a word pair in the Add Word dialog. Thus each time the user starts a recording, the name of the output file will be set to the last foreign word added.
Instead of using fields for recordingImageView, foreignWord, defaultWord, foreignWord, audioSavePath, and mediaRecorder, you should make them local variables, and pass them as parameters to your record(), startAudioRecording(), stopAudioRecording() methods with the following steps:
Just delete those fields from the beginning of the class so that you see some compilation errors where the fields were used.
Where you see an undefined variable on the left side of an assignment, make the variable local (Ctrl+V in Android Studio).
Where you see an undefined variable elsewhere, make the variable a parameter of the method (Ctrl+P).
It should work after those changes.
`
Kindly move this snippet :
recordingImageView.setOnTouchListener(new View.OnTouchListener()
{
#Override public boolean onTouch(View view, MotionEvent motionEvent)
{
switch (motionEvent.getAction())
{
case MotionEvent.ACTION_DOWN:
{ recordingImageView.setImageResource(g startAudioRecording(position);
break;
}
case MotionEvent.ACTION_UP:
{
recordingImageView.setImageResource(R.drawable.mic_black);
stopAudioRecording();
break;
}
}
return true;
}
});
In Adapter , getView(...) Below accessing recordImageView.
And put startAudioRecording() , stopAudioRecording() in same adapter or all relevant method for recording is to be in Adapter.
So by this you will get click on in each individual image view. Previously when you are fetching it will only take instance of any one image view.
Now update code on "startAudioRecording()" as:
private void startAudioRecording()
{
if (checkPermission())
{
if (wordsArrayList != null)
{
audioSavePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + wordsArrayList.get(position) + ".3gp";
getMediaRecorderReady();
}
}
}
Now your second point, saving its name by any name. Will cover by above code.
Thanks and happy coding
I have created the start of an item/amount list with EditText fields but would like it so the total sits directly under the amount and for every new item/amount I add, they would sit just underneath the item/amount above them and the total would then jump down to sit under the newest amount field.
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.paulk.homebillcalc.HomeBills" >
<TextView
android:id="#+id/monthNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="86dp"
android:layout_marginStart="86dp"
android:layout_marginTop="31dp"
android:text="#string/month" />
<Spinner
android:id="#+id/monthchooser"
android:entries="#array/months_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="23dp"
android:layout_toEndOf="#+id/monthNameTextView"
android:layout_toRightOf="#+id/monthNameTextView"
android:prompt="#string/months" />
<TextView
android:id="#+id/PoundSign"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/itemAmountText"
android:layout_alignBottom="#+id/itemAmountText"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_toLeftOf="#+id/itemAmountText"
android:layout_toStartOf="#+id/itemAmountText"
android:text="#string/pound_sign"
android:textSize="20sp" />
<Button
android:id="#+id/addItemButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp"
android:text="#string/add_item" />
<EditText
android:id="#+id/itemAmountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/monthchooser"
android:layout_marginTop="26dp"
android:layout_toEndOf="#+id/addItemButton"
android:layout_toRightOf="#+id/addItemButton"
android:ems="5"
android:hint="#string/item_amount"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/PoundSign1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/totalAmountText"
android:layout_alignBottom="#+id/totalAmountText"
android:layout_toLeftOf="#+id/totalAmountText"
android:layout_toStartOf="#+id/totalAmountText"
android:text="#string/pound_sign"
android:textSize="20sp" />
<EditText
android:id="#+id/itemNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/PoundSign"
android:layout_alignBottom="#+id/PoundSign"
android:layout_toLeftOf="#+id/addItemButton"
android:layout_toStartOf="#+id/itemAmountText"
android:ems="8"
android:hint="#string/item_name"
android:inputType="text" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/totalAmountText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/itemAmountText"
android:layout_alignEnd="#+id/itemAmountText"
android:layout_alignLeft="#+id/itemAmountText"
android:layout_below="#+id/itemAmountText"
android:layout_marginTop="18dp"
android:ems="5"
android:hint="#string/total_amount"
android:inputType="numberDecimal" />
</RelativeLayout>
Code
package com.paulk.homebillcalc;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class HomeBills extends ActionBarActivity implements OnClickListener{
private final static String MONTH_OF_YEAR = "MONTH_OF_YEAR";
private final static String NAME_OF_ITEM = "NAME_OF_ITEM";
private final static String ITEM_AMOUNT = "ITEM_AMOUNT";
private final static String TOTAL = "TOTAL";
private Spinner monthChooser;
private String itemName;
private double itemAmount;
private double total;
EditText itemNameEdit;
EditText itemAmountEdit;
EditText totalEdit;
Button addField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_bills);
addListenerToMonthSelector();
addListenerOnButton();
//if new session
if(savedInstanceState ==null){
itemName = "";
itemAmount = 0;
total = 0;
}else{
//if its a saved session
itemName = savedInstanceState.getString(NAME_OF_ITEM);
itemAmount = savedInstanceState.getDouble(ITEM_AMOUNT);
total = savedInstanceState.getDouble(TOTAL);
}
itemNameEdit = (EditText) findViewById(R.id.itemNameText);
itemAmountEdit = (EditText) findViewById(R.id.itemAmountText);
totalEdit = (EditText) findViewById(R.id.totalAmountText);
addField = (Button) findViewById(R.id.addItemButton);
addField.setOnClickListener(this);
itemAmountEdit.addTextChangedListener(itemAmountListener);
}
private TextWatcher itemAmountListener = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try{
itemAmount = Double.parseDouble(s.toString());
}catch(Exception e){
itemAmount = 0;
}
updateTotalAmount();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
private void updateTotalAmount() {
//the pulls out the characters from the field, and converts the double value to a string
double itemAmount = Double.parseDouble(itemAmountEdit.getText().toString());
double total = itemAmount;
totalEdit.setText(String.format("%.02f", total));
}
private void addListenerOnButton() {
monthChooser = (Spinner) findViewById(R.id.monthchooser);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_bills, menu);
return true;
}
public void addListenerToMonthSelector(){
monthChooser = (Spinner) findViewById(R.id.monthchooser);
}
#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);
}
#Override
public void onClick(View v) {
if(v == addField){
itemNameEdit = (EditText) findViewById(R.id.itemNameText);
itemAmountEdit = (EditText) findViewById(R.id.itemAmountText);
itemAmountEdit.setVisibility(View.VISIBLE);
}
}
}
I have been trying to learn Java for Android development, so I decided to try to make a simple converter application to learn from. At the moment i have a simple UI and I am trying to convert from Celsius to Fahrenheit. the converter will, when working, convert betweem Celsius, Fahrenheit and Kelvin.
When I click the button that is supposed to run the calculation method, i get the error "Unfortunately, Converter has stopped."
Below is my code, I have also included the XML for the view as well.
package com.michaelmurphy.converter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Spinner;
public class Temperature extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.temperature_view);
// TODO Auto-generated method stub
}
public void tempCalc()
{
//define variables
float value = 0;
String from = "";//for spinner
String to = "";//for spinner
//get entered value
EditText input = (EditText) findViewById(R.id.editText1);
//convert to string
String enteredValue = input.getText().toString();
//convert string into float
float num = Float.valueOf(enteredValue);
//retrieve the from spinner value
final Spinner fromSpinner = (Spinner) findViewById(R.id.spinner1);
from = fromSpinner.getSelectedItem().toString();
//retrieve the to spinner value
final Spinner toSpinner = (Spinner) findViewById(R.id.spinner1);
to = toSpinner.getSelectedItem().toString();
EditText output = (EditText) findViewById(R.id.textView2);
/*if(from.equals(to)) //the same conversion type
{
//error
}*/
if(from.equals("Celcius"))
{
if(to.equals("Fahrenheit"))
{
value = celToFar(num);
}
else
{
//value = celToKel(num);
}
}
else if(from.equals("Fahrenheit"))
{
if(to.equals("Celcius"))
{
//value = fahToCel(num);
}
else
{
//value = fahToKel(num);
}
}
else //kelvin
{
if(to.equals("Celcius"))
{
//value = kelToCel(num);
}
else
{
//value = kelToFah(num);
}
}
//set the label to variable value
String valueStr = Float.toString(value);//cast float to string
output.setText(valueStr);
}
public float celToFar(float cel)
{
float fah = cel * 9/5 + 32;
return fah;
}
}
View XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/temp_arr" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/temp_arr" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convertBtn"
android:onClick="tempCalc" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Is anyone able to point out where I am going wrong, I have no idea. Thanks
Change:
public void tempCalc()
To
public void tempCalc(View v)
Any onClick method expects a View parameter. As you don't pass one, the method signatures don't match, and your app throws an exception.