Unable to get Text out of EditText - java

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

Related

Return input information in android Studio Java

I am new to android studio and I am trying to play with simple program that takes an input from the user such as name, certification number, and role and display the user input as an output. I am using a separate java file that I have created that has all of the methods to access. Because I am new to android studio I am unsure of the syntax on how to achieve this. Could you please provide the correct way of writing the syntax so that I get the desired output?
I will be providing the xml.file, the java file associated with the .xml file and the second java file which has the class and methods to pull from. DivingDuddy.java is dependent on Divepartner.java. I added Divepartner to the android library. See code below and thank you again.
The .xml file:
<?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=".DivingBuddy">
<TextView
android:id="#+id/dive_buddypage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Welcome to the Dive Buddy section!"
android:textAlignment="center"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.051" />
<EditText
android:id="#+id/divebuddyname_input"
android:layout_width="249dp"
android:layout_height="60dp"
android:background="#drawable/edit_text_custom"
android:hint="Enter Name:"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.098"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.241" />
<EditText
android:id="#+id/certNumber_input"
android:layout_width="249dp"
android:layout_height="60dp"
android:background="#drawable/edit_text_custom"
android:hint="Enter certNumber of partner:"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.098"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.347" />
<EditText
android:id="#+id/role_input"
android:layout_width="249dp"
android:layout_height="60dp"
android:background="#drawable/edit_text_custom"
android:hint="Enter role of partner:"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.098"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.451" />
<EditText
android:id="#+id/output"
android:layout_width="410dp"
android:layout_height="63dp"
android:background="#drawable/edit_text_custom"
android:hint="Dive Section Output:"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.649" />
<Button
android:id="#+id/complete_DiveBuddySection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Complete"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.506"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.806" />
<Button
android:id="#+id/back_to_otherDetails3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.901" />
</androidx.constraintlayout.widget.ConstraintLayout>
The Java file associated with the .xml file is called DivingBuddy.java.
public class DivingBuddy extends AppCompatActivity {
EditText name, certNum, role, output;
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_diving_buddy);
name = (EditText)findViewById(R.id.divebuddyname_input);
certNum = (EditText)findViewById(R.id.certNumber_input);
role = (EditText)findViewById(R.id.role_input);
output = (EditText)findViewById(R.id.output);
findViewById(R.id.complete_DiveBuddySection).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DivePartner divePartner = new DivePartner(" "," "," ");
String inputName = name.getText().toString();
String inputCertNumber = certNum.getText().toString();
String inputRole = role.getText().toString();
String dive_buddy_info = output.getText().toString();
if(inputName.isEmpty() || inputCertNumber.isEmpty() || inputRole.isEmpty()){
Toast.makeText(DivingBuddy.this,"Please Enter the Name, CertNumber and role of the dive partner", Toast.LENGTH_LONG).show();
}else{
inputName = divePartner.getName();
inputCertNumber = divePartner.getCertNum();
inputRole = divePartner.getRole();
dive_buddy_info = divePartner.toString();
System.out.println(inputName);
System.out.println(inputCertNumber);
System.out.println(inputRole);
System.out.println(dive_buddy_info);
}
}
});
back = (Button)findViewById(R.id.back_to_otherDetails3);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),OtherDivingDetails.class);
startActivity(intent);
}
});
}
}
The third Java file is called DivePartner.java which is used to call methods or functions from.
package com.example.divepartner;
public class DivePartner {
private String name;
private String certNum;
private String role;
public DivePartner(String name, String number, String role){
setName(name);
setCertNum(number);
setRole(role);
}
public String getName() {
String temp = name;
return temp;
}
private void setName(String name) {
this.name = name;
}
public String getCertNum() {
String temp = certNum;
return temp;
}
private void setCertNum(String certNum) {
this.certNum = certNum;
}
public String getRole() {
String temp = role;
return temp;
}
private void setRole(String role) {
this.role = role;
}
#Override
public String toString() {
return "Name: " + getName() + ", CertNum: " + getCertNum() + ", Role: " + getRole();
}
}
DivePartner divePartner = new DivePartner(" "," "," ");
// ....
// ....
// ....
inputName = divePartner.getName();
inputCertNumber = divePartner.getCertNum();
inputRole = divePartner.getRole();
dive_buddy_info = divePartner.toString();
The DivePartner object is empty. So, when you call the get() methods on it, it will return a null or empty value. So, use set() instead of get().
DivePartner divePartner = new DivePartner(" "," "," ");
// ....
// ....
// ....
divePartner.setName(inputName);
divePartner.setCertNum(inputCertNumber);
divePartner.getRole(inputRole);
dive_buddy_info = divePartner.toString();
Now instead of System.out.println(), use Log.d() method to log in AndroidStudio Console.
I highly recommend you to complete a basic Java course before starting Android Development

get two or more values in an edit text and get the result from a button click

I'm building a GPA calculator with android studio
What I have:
I have an edit text for credit unit and another for grade with different ID's
I have a method for the button
the app runs fine but when i input a value for the creditunit and a value for the grade, nothing happens when i click the button.
here is my xml
edit text for credit unit
<EditText
android:id="#+id/txt_credits"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_weight="1"
android:background="#drawable/border"
android:ems="4"
android:gravity="center"
android:hint="e.g. 0, 2, 3 "
android:inputType="textPersonName|number|numberDecimal" />
edit text for grade
EditText
android:id="#+id/txt_grade"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_weight="1"
android:background="#drawable/border"
android:ems="4"
android:gravity="center"
android:hint="e.g. A, B, C "
android:inputType="textCapCharacters"
android:paddingLeft="16dp" />
button
<Button
android:id="#+id/button2"
android:layout_marginBottom="6dp"
android:textAllCaps="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:onClick="calcGpa"
android:text="get gpa"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"/>
here is my java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditCreditText = (EditText) findViewById(R.id.txt_credits);
mEditGradeText = (EditText) findViewById(R.id.txt_grade);
mButton = (Button) findViewById(R.id.button2);
mButton.setOnClickListener(onClick());
}
private View.OnClickListener onClick() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
allCredits.add(mEditCreditText);
allGrades.add(mEditGradeText);
}
};
}
public int pointPerSubj(int number,String grade) {
int point;
if (grade.equalsIgnoreCase("A"))
point = 5;
else if (grade.equalsIgnoreCase("B"))
point = 4;
else if (grade.equalsIgnoreCase("C"))
point = 3;
else if (grade.equalsIgnoreCase("D"))
point = 2;
else
point = 0;
int perSubjectPoint = number * point;
return perSubjectPoint;
}
public void calcGpa (View v) {
gpa = perSubjectPoint/totalCredits;
display(gpa);
}
// display method
private void display(int number) {
TextView gpaTextView = (TextView) findViewById(R.id.gpa_text_view);
gpaTextView.setText("" + (number));
}
}
I don't have enough reputation to comment, else I would have asked for more code in the comments.
Your onClickListener adds your EditTexts to what I'm assuming are ArrayLists of EditTexts: allCredits and allGrades
In the first place, if you meant to insert the text, then those should be ArrayLists of strings, and you should be doing:
allCredits.add(mEditCreditText.getText().toString());
allGrades.add(mEditGradeText.getText().toString());
Also, your code does not indicate where any of your methods calcGpa and pointPerSubj are called.
I believe you are simply not calling the required methods to display
anything.

Recorded file name is wrong

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

how to assign an integer value when user checked check box

i am facing this problem right now. i want to generate a receipt of food along with its price and total price (summation of all checked check box-the selected menu)
this is the code for the check box page where user need to checked on items that they would like to buy.
<RelativeLayout >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/pakejC1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Beg" />
<CheckBox
android:id="#+id/pakejC2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shoes" />
<ImageButton
android:id="#+id/gobutton"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/homebtn"
android:layout_toRightOf="#+id/homebtn"
android:background="#drawable/gobutton"
android:onClick="goReceiptC" />
this is the code for the process
public class item extends Activity
{
CheckBox beg1, shoes1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
beg1 = (CheckBox) findViewById(R.id.pakejC1);
shoes1 = (CheckBox) findViewById(R.id.pakejC2);
}
public void goReceiptC(View v)
{
Intent intent = new Intent(v.getContext(), doReceiptC.class);
intent.putExtra("beg1", beg1.isChecked());
intent.putExtra("shoes1", shoes1.isChecked());
startActivityForResult(intent,0);
}
}
this is the process for the display receipt
public class doReceipt extends Activity
{
boolean beg1, shoes1;
TextView tvOutput1,tvOutput2;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.receipt);
tvOutput1 = (TextView) findViewById(R.id.textView1);
tvOutput2 = (TextView) findViewById(R.id.textView2);
Bundle data = this.getIntent().getExtras();
beg1=data.getBoolean("beg1");
shoes1=data.getBoolean("shoes1");
if(beg2==true)
{
tvOutput1.setText("Nasi Putih RM 1.00");
tvOutput1.setVisibility(View.VISIBLE);
// this is where i would like to display the price
//eg rm 1.00
}
else
{
tvOutput1.setVisibility(View.GONE);
}
if (shoes1==true)
{
tvOutput2.setText("shoes RM 1.50");
tvOutput2.setVisibility(View.VISIBLE);
// this is where i would like to display the price
//eg rm 1.50
}
else
{
tvOutput2.setVisibility(View.GONE);
}
** i want the total price for both checked item to be display in the receipt as total
this is the page for display the receipt
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textA"
android:layout_below="#+id/textA"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:text="total price"
android:textAppearance="?android:attr/textAppearanceMedium" />
help me plz....
You are not very clear about from where are these values coming.
But what you can do is:
//global variables
float bagPrice = 1.0f, shoesPrice = 1.5f, total = 0f;
//your logic of getting values
if(beg2==true)
{
//do what you want in textviews
total += bagPrice;
}
else
{
//your code
}
if (shoes1==true)
{
//do what you want in textviews
total += shoesPrice;
}
else
{
//your code
}
Toast.makeText(getApplicationContext(), String.valueOf(total), Toast.LENGTH_SHORT).show(); //show total in TextView using String.valueOf(total)
Hope this helps.
You could also extend CheckBox and add a price float attribute and set its value in the constructor, then create a new method getPrice that return 0 or this.price depending of whether its checked or not.
Pseudo code
public class PriceCheckBox() extends CheckBox {
private float price;
public PriceCheckBox(float price) {
super():
this.price = price;
}
public float getPrice() {
if(isChecked()){
return this.price;
} else {
return 0;
}
}
//You could also add a setter here if you wish to change price later.
Then simply use PriceCheckBox instead of CheckBox and call getPrice() instead isChecked().

Learning Android Java - application fails

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.

Categories