#java #android
#java #Android
Вопрос:
Я пытаюсь собрать входные данные из activity_main.xml используя EditText и отправив по электронной почте данные, введенные из MainActivity.java при нажатии кнопки отправки. По какой-то причине кнопка отправки ничего не делает при нажатии. Приветствуется любая помощь. Спасибо. Ниже приведены мои коды:
Это мой activity_main.xml код:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:background="@android:color/background_light">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="@ id/questions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.example.android.stool.MainActivity">
<ImageView
android:id="@ id/logo"
android:layout_width="match_parent"
android:layout_height="@dimen/height"
android:layout_gravity="center_horizontal"
android:background="#303f9f"
android:contentDescription="@string/description"
android:paddingBottom="@dimen/padding"
android:paddingTop="@dimen/padding"
android:src="@drawable/logoconf" />
<EditText
android:id="@ id/presentationName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginRight="@dimen/margin"
android:layout_marginTop="@dimen/margin"
android:hint="@string/presentation"
android:inputType="text" />
<EditText
android:id="@ id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginRight="@dimen/margin"
android:layout_marginTop="@dimen/margin"
android:hint="@string/date"
android:inputType="date" />
<TextView
android:id="@ id/speaker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginRight="@dimen/margin"
android:layout_marginStart="@dimen/margin"
android:layout_marginTop="@dimen/margin"
android:text="@string/speaker" />
<RatingBar
android:id="@ id/rating_bar1"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:isIndicator="false"
android:numStars="5"
android:rating="0"
android:stepSize="1"
tools:ignore="RtlHardcoded" />
<TextView
android:id="@ id/rating_bar1_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
/>
<TextView
android:id="@ id/visuals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginRight="@dimen/margin"
android:layout_marginTop="@dimen/margin"
android:text="@string/visuals" />
<RatingBar
android:id="@ id/rating_bar2"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:isIndicator="false"
android:numStars="5"
android:rating="0"
android:stepSize="1"
tools:ignore="RtlHardcoded" />
<TextView
android:id="@ id/rating_bar2_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
/>
<TextView
android:id="@ id/useful"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginRight="@dimen/margin"
android:layout_marginTop="@dimen/margin"
android:text="@string/useful" />
<RatingBar
android:id="@ id/rating_bar3"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginStart="@dimen/margin"
android:isIndicator="false"
android:numStars="5"
android:rating="0"
android:stepSize="1" />
<TextView
android:id="@ id/rating_bar3_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
/>
<TextView
android:id="@ id/recommend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginRight="@dimen/margin"
android:layout_marginTop="@dimen/margin"
android:text="@string/recommend" />
<RadioGroup
android:id="@ id/rg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginStart="@dimen/margin"
android:orientation="horizontal">
<RadioButton
android:id="@ id/yes_radio_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/y"
android:textAppearance="?android:textAppearanceMedium" />
<RadioButton
android:id="@ id/no_radio_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/n"
android:textAppearance="?android:textAppearanceMedium" />
</RadioGroup>
<EditText
android:id="@ id/suggestions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin"
android:layout_marginRight="@dimen/margin"
android:layout_marginTop="@dimen/margin"
android:hint="@string/suggestions"
android:inputType="textMultiLine" />
</LinearLayout>
<TextView
android:id="@ id/review_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Summary"
android:textSize="16sp"
android:textColor="@android:color/black"
android:layout_marginLeft="8dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
/>
<Button
android:id="@ id/submit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="@ id/questions"
android:layout_centerHorizontal="true"
android:layout_marginBottom="@dimen/button_margin"
android:onClick="submit"
android:text="@string/submit" />
</RelativeLayout>
</ScrollView>
Это мой MainActivity.java код:
package com.example.android.stool;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
EditText presentationName;
EditText date;
RatingBar rating_bar1;
RatingBar rating_bar2;
RatingBar rating_bar3;
RadioButton yes;
RadioButton no;
EditText suggestions;
private ImageView imageView;
private EditText editText;
private EditText dateText;
private TextView textView;
private RatingBar ratingBar1;
private TextView rating_bar1_resu<
private TextView rating_bar2_resu<
private TextView rating_bar3_resu<
private TextView visualsText;
private RatingBar ratBar;
private TextView usefulText;
private RatingBar ratiBar;
private TextView recommendText;
private RadioGroup radioGroup;
private RadioButton yesButton;
private RadioButton noButton;
private EditText suggestText;
private Button submitButton;
private String str;
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitButton = (Button) findViewById(R.id.submit_button);
coolLogo = (ImageView) findViewById(R.id.logo);
nameField = (EditText) findViewById(R.id.presentationName);
recDay = (EditText) findViewById(R.id.date);
comCat = (TextView) findViewById(R.id.speaker);
rating_bar1 = (RatingBar) findViewById(R.id.rating_bar1);
rating_bar1_result = (TextView) findViewById(R.id.rating_bar1_result);
graPhics = (TextView) findViewById(R.id.visuals);
rating_bar2 = (RatingBar) findViewById(R.id.rating_bar2);
rating_bar2_result = (TextView) findViewById(R.id.rating_bar2_result);
advAnt = (TextView) findViewById(R.id.useful);
rating_bar3 = (RatingBar) findViewById(R.id.rating_bar3);
rating_bar3_result = (TextView) findViewById(R.id.rating_bar3_result);
menDar = (TextView) findViewById(R.id.recommend);
yesButton = (RadioButton) findViewById(R.id.yes_radio_button);
noButton = (RadioButton) findViewById(R.id.no_radio_button);
sugGest = (EditText) findViewById(R.id.suggestions);
}
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v){
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto: example@gmail.com")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, "Presentation Review for: " name);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
displayMessage(priceMessage);
});
}
private String reviewOrderSummary(String cool, String name, String rec, String com, boolean rating_bar1_result, String gra, boolean rating_bar2_result, String adv, boolean rating_bar3_result, String men, boolean selectedId, String sug) {
String priceMessage = "Logo: " cool;
priceMessage = "nName of Presentation: " name;
priceMessage = "nDate: " rec;
priceMessage = "nQuestion: " com;
priceMessage = "nPerformance: " rating_bar1_resu<
priceMessage = "nQuestion: " gra;
priceMessage = "nVisual: " rating_bar2_resu<
priceMessage = "nQuestion: " adv;
priceMessage = "nUseful Information: " rating_bar3_resu<
priceMessage = "nQuestion: " men;
priceMessage = "nAnswer: " selectedId;
priceMessage = "nSuggestion: " sug;
priceMessage = "nThank you!";
return priceMessage;
}
//displays Logo
private void displayImage(View ImageView) {
ImageView coolLogo = (ImageView) findViewById(R.id.logo);
coolLogo.setImageResource(R.drawable.logoconf);
String cool = coolLogo.getRootView().toString();
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.JELLY_BEAN_MR1)
{
// ImageView.getDisplay();
coolLogo.getDisplay();
}
}
//displays Presentation Name
private void displayText(String name) {
EditText nameField = (EditText) findViewById(R.id.presentationName);
name = nameField.getText().toString();
if(name.equals(""))
{
Toast.makeText(getApplicationContext(), "Please type the Name of the Presentation!", Toast.LENGTH_SHORT).show();
}
else
{
// EditText.setText(name);
nameField.setText(name);
}
}
//displays Date
private void displayDate(String rec) {
EditText recDay = (EditText) findViewById(R.id.date);
rec = recDay.getText().toString();
if(rec.equals(""))
{
Toast.makeText(getApplicationContext(), "Please type in Today's Date!", Toast.LENGTH_SHORT).show();
} else
{
// EditText.setText(name);
recDay.setText(rec);
}
}
//displays How would you rate the speaker's TextView
private void displaySpeaker(String com) {
TextView comCat = (TextView) findViewById(R.id.speaker);
com = comCat.setText().toString();
// TextView.setText(com);
comCat.setText(com);
}
//displays the Rating Bar1 below speaker's TextView
void RatingUpdate() {
rating_bar1.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rating_bar1_result.setText("Rating: " String.valueOf(Math.round(rating)));
}
});
}
//displays how helpful were the visuals TextView
private void displayVisuals(String gra) {
TextView graPhics = (TextView) findViewById(R.id.visuals);
gra = graPhics.getText().toString();
// TextView.setText(gra);
graPhics.setText(gra);
}
//displays the Rating Bar below visuals TextView
void RatingUpdate2() {
rating_bar2.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rating_bar2_result.setText("Rating: " String.valueOf(Math.round(rating)));
}
});
}
//displays useful TextView
private void displayVisuals(String adv) {
TextView advAnt = (TextView) findViewById(R.id.useful);
adv = advAnt.getText().toString();
// TextView.setText(adv);
advAnt.setText(adv);
}
//displays the Rating Bar below useful TextView
void RatingUpdate3() {
rating_bar3.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
rating_bar3_result.setText("Rating: " String.valueOf(Math.round(rating)));
}
});
}
//displays recommend TextView
private void displayRecommend(String men) {
TextView menDar = (TextView) findViewById(R.id.recommend);
men = menDar.getText().toString();
// TextView.setText(men);
menDar.setText(men);
//checks radiobutton for recommend TextView
int selectedId = radioGroup.getCheckedRadioButtonId();
if(selectedId ==-1)
{
Toast.makeText(getApplicationContext(), "Please choose one!", Toast.LENGTH_SHORT).show();
}
else
{
yesButton = (RadioButton) findViewById(selectedId);
if (yesButton.getId() == R.id.yes_radio_button) {
}
noButton = (RadioButton) findViewById(selectedId);
if (noButton.getId() == R.id.no_radio_button) {
}
}
}
//displays additional suggestions
private void displaySuggestions(String sug) {
EditText sugGest = (EditText) findViewById(R.id.suggestions);
sug = sugGest.getText().toString();
if(sug.equals(""))
{
Toast.makeText(getApplicationContext(), "Please type in your suggestions!", Toast.LENGTH_SHORT).show();
}
else
{
// EditText.setText(name);
sugGest.setText(sug);
}
Toast.makeText(
getApplicationContext(), "Thanks for filling this survey!",Toast.LENGTH_LONG).
show();
}
/**
* This method displays the given review text on the screen.
*/
private void displayMessage(String message) {
TextView reviewSummaryTextView = (TextView) findViewById(R.id.review_summary_text_view);
reviewSummaryTextView.setText(message);
}
}
Мои коды ошибок приведены ниже:
Для приведенных ниже кодов все имена перед знаком = выделены красным цветом. Итак, coolLogo красного цвета, nameField красного цвета, recDay красного цвета, ComCat красного цвета, graPhics красного цвета, advAnt красного цвета, menDar красного цвета и sugGest красного цвета.
coolLogo = (ImageView) findViewById(R.id.logo);
nameField = (EditText) findViewById(R.id.presentationName);
recDay = (EditText) findViewById(R.id.date);
comCat = (TextView) findViewById(R.id.speaker);
graPhics = (TextView) findViewById(R.id.visuals);
advAnt = (TextView) findViewById(R.id.useful);
menDar = (TextView) findViewById(R.id.recommend);
sugGest = (EditText) findViewById(R.id.suggestions);
Для приведенного ниже кода setOnClickListener имеет красный цвет, v — красный, name — красный, priceMessage — красный, и ) перед ; имеет красный цвет.
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick (View v){
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto: example@gmail.com")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, "Presentation Review for: " name);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
displayMessage(priceMessage);
});
}
Я хотел бы иметь возможность собирать логотип, дату, вопросы и ответы и отправлять их по электронной почте на example@gmail.com.
Комментарии:
1. удалите android:onClick= «отправить» из xml в виджете button
2. На самом деле, я действительно хочу, чтобы вы скомпилировали этот код, и я предлагаю вам удалить этот вопрос после завершения. Этот вопрос полезен только для вас, а не для сообщества.
Ответ №1:
Обновление 1:
По крайней мере, таким образом вы можете отобразить свое сообщение.
- У вас есть два
displayVisuals(String gra)
метода. Удалите один из них.
=>
//displays how helpful were the visuals TextView
private void displayVisuals(String gra) {
TextView graPhics = (TextView) findViewById(R.id.visuals);
gra = graPhics.getText().toString();
// TextView.setText(gra);
graPhics.setText(gra);
}
- Измените setText() на getText() в
displaySpeaker()
методе.
=>
private void displaySpeaker(String com) {
TextView comCat = (TextView) findViewById(R.id.speaker);
com = comCat.getText().toString();
// TextView.setText(com);
comCat.setText(com);
}
- И удалите свой
onCreate()
метод иsubmitButton.setOnClickListener ~
. Добавьте это:
=>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitButton = (Button) findViewById(R.id.submit_button);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText nameField = (EditText) findViewById(R.id.presentationName);
EditText recDay = (EditText) findViewById(R.id.date);
TextView comCat = (TextView) findViewById(R.id.speaker);
TextView menDar = (TextView) findViewById(R.id.recommend);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.rg);
EditText sugGest = (EditText) findViewById(R.id.suggestions);
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto: example@gmail.com")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, "Presentation Review for: " nameField.getText().toString());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
String priceMessage = reviewOrderSummary(
"Logo", /* Logo is an image, and you printing string. Is that what you meant? */
nameField.getText().toString(),
recDay.getText().toString(),
comCat.getText().toString(),
true, /* rating_bar1_result is a TextView, and you printing boolean. Is that what you meant? */
"GRA", /* Indefinite */
true, /* rating_bar2_result is a TextView, and you printing boolean. Is that what you meant? */
"ADV", /* Indefinite */
true, /* rating_bar3_result is a TextView, and you printing boolean. Is that what you meant? */
menDar.getText().toString(),
radioGroup.getCheckedRadioButtonId() == 0,
sugGest.getText().toString()
);
displayMessage(priceMessage);
}
});
}
Можете ли вы создать этот код? Я думаю, что это не может быть скомпилировано.
Вы должны установить свое значение instance, а не сам класс!
// ImageView.getDisplay();
coolLogo.getDisplay();
// EditText.setText(name);
nameField.setText(name);
// TextView.setText(adv);
advAnt.setText(adv);
Комментарии:
1. Я изменил ImageView, EditText и TextView на формат выше… В моем коде несколько ошибок, и я не знаю почему…
2. @Gifer Итак, обновите свой вопрос. Покажите мне свой код ошибки.
3. Спасибо @Stanley Kou, я обновил его, чтобы включить текущие ошибки.
4. Спасибо @Stanley Kou, единственное, что теперь выделено красным, — это reviewOrderSummary, в нем говорится, что не удается разрешить метод ‘reviewOrderSummary’.
5. @Gifer У вас есть
reviewOrderSummary
метод в вашем MainActivity.java !