Hot questions for Using Android EditText in android intent

Question:

In my app, I have around 5 editText boxes in every screen.I want to check if they are empty or not and if all the text boxes are not empty, then there is an intent which takes you to the next screen. I want to know what code to write.


Answer:

Just add this code in your java file when you want to call the intent.

EditText editTextBox1 = (EditText) findViewById(R.id.your_editTextBox1_id);
EditText editTextBox2 = (EditText) findViewById(R.id.your_editTextBox2_id);
EditText editTextBox3 = (EditText) findViewById(R.id.your_editTextBox3_id);
EditText editTextBox4 = (EditText) findViewById(R.id.your_editTextBox4_id);
EditText editTextBox5 = (EditText) findViewById(R.id.your_editTextBox5_id);

if((editTextBox1.getText().length() != 0) && (editTextBox2.getText().length() != 0) && (editTextBox3.getText().length() != 0) && (editTextBox4.getText().length() != 0) && (editTextBox5.getText().length() != 0)){
    //Start Activity
}
else{
    //else show an error or anything you want
}

Here, just replace the your_editTextBox1_id with the ID you set in your xml file.

If you want to check it when a Button is clicked, just add this code in the OnClick method of the button.

Question:

I am able to generate multiple editText dynamically, but don't understand how to intent its text on Next activity by using intent

public void onAddField(View v) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rowView = inflater.inflate(R.layout.field, null);
        parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);

    }
public void onDelete(View v) {
        parentLinearLayout.removeView((View) v.getParent());
    }

Answer:

add all editexts to on list..

List<EditText> edt_all = new ArrayList<EditText>();

and then you will getdata

for(int i=0; i < edt_all.size(); i++){
    string[i] = edt_all.get(i).getText().toString();
    Log.e("##edittext ", string[i])
} 

Question:

I'm developing a simple to do list application, where on the welcome page, you enter your name and when you click to goto your tasks (on tasks page) your username which you just entered should appear at the top of the screen (For example: "App: Username") but when I tried this it appeared as "App: null" on the welcome page and "null: null" on the tasks page. Can anyone see why? Thank you.

Welcome.java

package winfield.joe.assignment.two; 

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.app.ProgressDialog;
import android.widget.CheckBox;

public class Welcome extends Activity {

    //global vars
    private CheckBox check;
    private ProgressDialog progress;
    private ToggleButton toggleButton;
    private RatingBar ratingBar;

    private String givenTitle;
    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        givenTitle = (String) this.getTitle();

        progress = new ProgressDialog(this);

        addListenerOnCheck();
        addListenerOnButton();
        addListenerOnRatingBar();

    }

    //on click CheckBox displays a toast message - CLICK!
    public void addListenerOnCheck() {

        check = (CheckBox) findViewById(R.id.check);
        check.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               StringBuffer result = new StringBuffer();
               result.append("CLICK!");
               Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();
            }

        });

    }

    //on click toggle button displays on/off
    public void addListenerOnButton() {

        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
        toggleButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               StringBuffer result = new StringBuffer();
               result.append("Toggle = ").append(toggleButton.getText());          
               Toast.makeText(Welcome.this, result.toString(), Toast.LENGTH_SHORT).show();   
            }

        });

    }

    //Give a rating - Toast appears of star rating
    public void addListenerOnRatingBar() {

        ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        //if rating value has changed, display the current rating on a toast
        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {  
                Toast.makeText(Welcome.this, String.valueOf(ratingBar.getRating()), Toast.LENGTH_SHORT).show();
            }

        });

    }

    //Onclick - go to About
    public void aboutMe(View view) {

        Intent intent = new Intent(Welcome.this, About.class);

        startActivity(intent);

    }

    //Onclick - go to Tasks
    public void doStuff(View view) {

        this.setTitle(givenTitle + ": " + username);

        Intent intent = new Intent(Welcome.this, Tasks.class);
        startActivity(intent);

        //ProgressBarDialog appears saying its finding yours tasks and loads to 100 and changes activity
        progress.setMessage("Finding tasks...");
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progress.setIndeterminate(true);
        progress.show();

        //Goes to 100
        final int totalProgressTime = 100;

        final Thread t = new Thread(){

           @Override
           public void run(){

              //Goes from 0 to 100 in jumps of 5 until the total amount of jumps reaches 100/total progress time
              int jumpTime = 0;
              while(jumpTime < totalProgressTime){
                 try {
                    Thread.sleep(200);
                    jumpTime += 5;
                    progress.setProgress(jumpTime);
                 } catch (InterruptedException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                 }
              }

           }

       }; t.start();

    }

}

Tasks.java

package winfield.joe.assignment.two;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import winfield.joe.assignment.two.database.TaskContract;
import winfield.joe.assignment.two.database.TaskDBHelper;

public class Tasks extends ListActivity {

    //add required global variables
    private ListAdapter listAdapter;
    private TaskDBHelper helper;

    private String givenTitle;
    private String username;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tasks);
        updateUI();

        this.setTitle(givenTitle + ": " + username);

    }

    //add in the menu (refers to menu.xml file)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu,menu);
        return true;
    }

    //to get selected tasks from menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_task:
                //create new alert dialog which asks you if you want to make a new task entry
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Add a new task");
                builder.setMessage("What do you need to do?");
                final EditText inputField = new EditText(this);
                builder.setView(inputField);
                //if 'add' then place it into the db, update it
                builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //Clicking add - stores data in the database
                        String task = inputField.getText().toString();
                        helper = new TaskDBHelper(Tasks.this);
                        SQLiteDatabase db = helper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        values.clear();
                        values.put(TaskContract.Columns.TASK,task);
                        db.insertWithOnConflict(TaskContract.TABLE,null,values,SQLiteDatabase.CONFLICT_IGNORE);
                        updateUI();
                    }
                });

                //quits out of alert dialog and goes back to the task list if 'cancel'
                builder.setNegativeButton("Cancel",null);

                builder.create().show();
                return true;

            default:
                return false;
        }
    }

    //Show database entries on the tasks page
    private void updateUI() {
        helper = new TaskDBHelper(Tasks.this);
        SQLiteDatabase sqlDB = helper.getReadableDatabase();
        Cursor cursor = sqlDB.query(TaskContract.TABLE, new String[]{
                TaskContract.Columns._ID, TaskContract.Columns.TASK
        },
                null, null, null, null, null);
        listAdapter = new SimpleCursorAdapter(
                this,
                R.layout.task_view,
                cursor,
                new String[]{TaskContract.Columns.TASK},
                new int[]{R.id.taskTextView},
                0
        );
        this.setListAdapter(listAdapter);
    }

    //Deletes tasks (clicking done next to them)
    public void onDoneButtonClick(View view) {
        View v = (View) view.getParent();
        TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
        String task = taskTextView.getText().toString();
        //This query deletes the entry associated with the id/button pressed
        String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
                        TaskContract.TABLE,
                        TaskContract.Columns.TASK,
                        task);

        helper = new TaskDBHelper(Tasks.this);
        SQLiteDatabase sqlDB = helper.getWritableDatabase();
        sqlDB.execSQL(sql);
        updateUI();
    }

    //onClick finished method assigned to the 'Finished' button
    public void finished(View view) {

            //Make alert dialog box appear and give it it's title
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.alert));

                // set dialog message
                builder.setCancelable(false)

                        //Positive response = return to list (tasks page)
                        .setPositiveButton(getString(R.string.positive),new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                //You return to the Tasks 
                                dialog.cancel();
                            }
                        })

                        //Neutral response = go to about (about page)
                        .setNeutralButton(getString(R.string.neutral),new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                //You go to About Activity  
                                Intent intent = new Intent(Tasks.this, About.class);
                                startActivity(intent);
                            }
                        })

                        //Negative response = exit app (homescreen)
                        .setNegativeButton(getString(R.string.negative),new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // if this button is clicked, exit app to homescreen
                                Intent intent = new Intent(Intent.ACTION_MAIN);
                                intent.addCategory(Intent.CATEGORY_HOME);
                                startActivity(intent);
                            }
                        });

            //create it and show it
            AlertDialog alert = builder.create();
            alert.show();

        }

}

Username within activity_welcome.xml

<EditText
    android:ems="10"
    android:hint="@+string/username"
    android:id="@+id/username"
    android:inputType="text"
    android:layout_height="wrap_content"
    android:layout_marginEnd="30dp"
    android:layout_marginStart="30dp"
    android:layout_marginTop="30dp"
    android:layout_width="match_parent">

    <requestFocus/>
</EditText>

Relevant strings from strings.xml

<string name="app_name">ForYouToDo</string>
<string name="username">Username</string>

Answer:

Go to Android - Pass Data Between Two Activities get NullPointerException

A complete guide(How to pass data between two activity?)

and do in your Tasks Activity

this.setTitle(getResources().getString(R.string.app_name)+ ": " + username);

Question:

I am attempting to have have a edittext box appear when a certain radiobutton in a group is checked. I am getting the error with setVisibility, and when running the error that it says is int cannot be dereferenced.

JAVA

public class MainActivity extends AppCompatActivity {

//Declared some variables here. One for each field in the form

ShareActionProvider mShareActionProvider;
String feedbackType;
String feedback;
String email;
String fName;
String lName;
String fAnswer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RadioGroup radiochoice=(RadioGroup) findViewById(R.id.radiochoice);
    radiochoice.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.RejectRadio) {
                R.id.RejectResponse.setVisibility(View.VISIBLE);}
            else if (checkedId == R.id.AcceptRadio) {
                R.id.RejectResponse.setVisibility(View.INVISIBLE);}
        }
    });

}

XML (This works okay just for reference/review)

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical">
<RelativeLayout
    android:layout_width="fill_parent"
    android:orientation="vertical"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/TextViewTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/feedbacktitle"
        android:textSize="10pt">
    </TextView>

    <!--First Name-->
    <EditText
        android:id="@+id/EditTextFirstName"
        android:layout_height="wrap_content"
        android:hint="@string/feedbackfirst"
        android:inputType="textPersonName"
        android:layout_width="fill_parent"
        android:layout_below="@+id/TextViewTitle">
    </EditText>

    <!--Last Name-->
    <EditText
        android:id="@+id/EditTextLastName"
        android:layout_height="wrap_content"
        android:hint="@string/feedbacklast"
        android:inputType="textPersonName"
        android:layout_width="fill_parent"
        android:layout_below="@id/EditTextFirstName">
    </EditText>

    <!-- Email -->
    <EditText
        android:id="@+id/EditTextEmail"
        android:layout_height="wrap_content"
        android:hint="@string/feedbackemail"
        android:inputType="textEmailAddress"
        android:layout_width="fill_parent"
        android:layout_below="@id/EditTextLastName">
    </EditText>

    <Spinner
        android:id="@+id/SpinnerFeedbackType"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:entries="@array/Types_of_Errors"
        android:layout_below="@+id/EditTextEmail">
    </Spinner>

    <EditText
        android:id="@+id/EditTextFeedbackBody"
        android:layout_height="wrap_content"
        android:hint="@string/feedbackbody"
        android:inputType="textMultiLine"
        android:lines="5"
        android:layout_width="fill_parent"
        android:layout_below="@+id/SpinnerFeedbackType">

    </EditText>

    <RadioGroup
        android:id="@+id/radiochoice"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/EditTextFeedbackBody"
        android:orientation="horizontal">

        <RadioButton
        android:id="@+id/AcceptRadio"
        android:layout_width="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_height="wrap_content"
        android:text="@string/acceptbutton" />

        <RadioButton
            android:id="@+id/RejectRadio"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/rejectbutton"
            android:layout_marginStart="115dp" />
    </RadioGroup>

    <EditText
        android:id="@+id/RejectResponse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="@string/rejectreason"
        android:layout_marginTop="410dp"
        android:layout_alignParentEnd="true"
        android:layout_marginRight="20dp"
        android:inputType="text"/>

    <Button
        android:id="@+id/ButtonSend"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/sendform"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="590dp"
        android:onClick="submit"/>

</RelativeLayout>


Answer:

You have to do this:

//Reference rejectResponse
EditText rejectResponse = (EditText) findViewById(R.id.RejectResponse);
//Change visibility
rejectResponse.setVisibility(View.INVISIBLE);

This might be useful: Android View