Hot questions for Using Android EditText in dialog

Question:

I have a alert dialog and i will get text with TextView but When I call it a second time, the app crashes with error:

04-15 19:37:48.433: E/AndroidRuntime(907): java.lang.IllegalStateException: 
    The specified child already has a parent. You must call removeView() on 
    the child's parent first.

My Java source:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
        Button btn1 = (Button) findViewById(R.id.button1);
        final AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
        build.setTitle("Ders Adı Giriniz");
        final EditText dersAdiGir = new  EditText(MainActivity.this);
        build.setView(dersAdiGir);
        final LinearLayout layoutDers = (LinearLayout) findViewById(R.id.layoutDers);

        build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                Editable girilenDers = dersAdiGir.getText();
                TextView tv1 = new TextView(MainActivity.this);
                tv1.setText(girilenDers);
                layoutDers.addView(tv1);
                dialog.dismiss();
                build.create();

            }
        });

        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                AlertDialog alert = build.create();
                alert.show();
            }
        });




    }
}

Please help me, thanks all


Answer:

You're creating a new instance of the AlertDialog every button click. Create a final AlertDialog outside of the OnClickListener inner class.

Here's the fix:

final AlertDialog alert = build.create();
btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        alert.show();
    }
});

Question:

I'm kinda new to Android app development, and don't know how to debug this. So I'm trying to do EditText.setText on a DialogFragment. It prints out the right string on the log, but still showing the old string based on .xml file("Enter item here."). Is there any way to update it?

public class MyAlertDialogFragment extends DialogFragment{
public MyAlertDialogFragment() {}

public static MyAlertDialogFragment newInstance(String desc) {
    MyAlertDialogFragment frag = new MyAlertDialogFragment();
    Bundle args = new Bundle();
    args.putString("desc", desc);
    frag.setArguments(args);
    return frag;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setView(R.layout.custom_dialog);
    alertDialogBuilder.setTitle("Edit to-do list");

    final View layout = View.inflate(MainActivity.getAppContext(), R.layout.custom_dialog, null);
    final EditText mEditText = (EditText) layout.findViewById(R.id.EditDesc);
    String desc = getArguments().getString("desc");
    mEditText.setText(desc);
    System.out.println("EditText is " + mEditText.getText().toString());

    alertDialogBuilder.setPositiveButton("OK",  new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // on success
            EditTodoFragment.EditTodoFragmentListener listener = (EditTodoFragment.EditTodoFragmentListener)getActivity();
            listener.onFinishEditDialog(mEditText.getText().toString());
        }
    });
    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    return alertDialogBuilder.create();
}

}

The log file

07-06 21:04:20.738 4115-4115/com.example.light.todolist I/System.out: EditText is Doing grocery

The xml file is:

<TextView
    android:layout_width="238dp"
    android:layout_height="wrap_content"
    android:text="Edit Item Below:"
    android:id="@+id/EditTitle"
    android:layout_weight="0.04" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/EditDesc"
    android:text="Enter item here.">
<requestFocus />
</EditText>


Answer:

You don't use layout view for Dialog so that you can't see text on EditText. Please change as here:

 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    alertDialogBuilder.setTitle("Edit to-do list");

    final View layout = View.inflate(MainActivity.getAppContext(), R.layout.custom_dialog, null);
    alertDialogBuilder.setView(layout );

Question:

I'm developing an app for users to share their books. To achieve this, I'm getting different data about the book from the user. The problem is, horizontal autoscrolling of all EditTexts are working until Dialog has been shown and dismissed. Once a dialog has been dismissed on the fragment, horizontal autoscrolling of the EditText's on this layout won't work.

I added:

android:focusable="true"
android:focusableInTouchMode="true"

to parent layout of the edittext but doesn't work.

Also to make sure that autoscrolling is enabled I've added:

android:scrollHorizontally="true"

But none of above helped.

Here is XML code of the fragment layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="@color/white"
    android:orientation="vertical"
    android:paddingStart="@dimen/dp25"
    android:paddingEnd="@dimen/dp25"
    tools:context=".UI.Fragments.SharePostFragments.Fragment1.OverViewFragment">

    <LinearLayout
        android:id="@+id/root_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:orientation="vertical">

        <EditText
            android:id="@+id/edit_text_name_of_book"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:fontFamily="@font/segoe_ui_semi_bold"
            android:hint="@string/name_of_book"
            android:inputType="text"
            android:maxLength="50"
            android:maxLines="1"
            android:scrollHorizontally="true"
            android:textAlignment="textStart"
            android:textColor="@color/colorPrimaryDark"
            android:textColorHint="@color/colorPrimaryDark"
            android:textSize="@dimen/font22" />

        <TextView
            android:id="@+id/text_view_number_of_characters"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            android:layout_marginEnd="@dimen/dp10"
            android:fontFamily="@font/segoe_ui_light"
            android:text="@string/_0_50"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/font16"
            tools:ignore="RtlSymmetry" />

        <EditText
            android:id="@+id/edit_text_name_of_author"
            android:layout_width="match_parent"
            android:layout_height="@dimen/textBoxHeight"
            android:layout_marginTop="@dimen/dp30"
            android:background="@drawable/round_text_box_gray"
            android:fontFamily="@font/segoe_ui_regular"
            android:hint="@string/name_of_writer"
            android:inputType="text"
            android:paddingStart="20dp"
            android:paddingEnd="20dp"
            android:textColor="@color/colorPrimaryDark"
            android:textColorHint="@color/colorPrimaryDark"
            android:textSize="@dimen/font16" />

        <RelativeLayout
            android:id="@+id/constraint_layout_1"
            android:layout_width="match_parent"
            android:layout_height="@dimen/textBoxHeight"
            android:layout_marginTop="@dimen/dp20"
            android:background="@drawable/round_text_box_border_gray"
            android:gravity="center_vertical"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_marginTop="3dp"
                android:fontFamily="@font/segoe_ui_regular"
                android:paddingStart="@dimen/dp20"
                android:paddingEnd="@dimen/dp20"
                android:text="@string/price_of_book"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="@dimen/font16" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:paddingStart="@dimen/dp20"
                android:paddingEnd="@dimen/dp20"
                android:text="@string/azn_sign"
                android:textColor="@color/colorPrimaryDark"
                android:textSize="@dimen/font16" />

            <EditText
                android:id="@+id/edit_text_price_of_book"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toStartOf="@+id/textView2"
                android:background="@color/white"
                android:clickable="false"
                android:hint="@string/_0_0"
                android:inputType="text|numberDecimal"
                android:maxLength="6"
                android:singleLine="true"
                android:textColorHint="@android:color/black" />

        </RelativeLayout>

        <LinearLayout
            android:id="@+id/constraint_layout_conditions_root"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp20"
            android:background="@drawable/round_text_box_border_gray"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/linear_layout_1"
                android:layout_width="match_parent"
                android:layout_height="@dimen/textBoxHeight"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="9"
                    android:gravity="center_vertical"
                    android:paddingStart="@dimen/dp20"
                    android:paddingEnd="@dimen/dp20"
                    android:text="@string/book_condition_placeholder"
                    android:textColor="@color/colorPrimaryDark" />

                <ImageButton
                    android:id="@+id/image_button_conditions"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginEnd="@dimen/dp10"
                    android:layout_weight="1"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:src="@drawable/ic_spinner" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/linear_layout_conditions"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <TextView
                    android:id="@+id/text_view_new"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingStart="@dimen/dp20"
                    android:paddingTop="@dimen/dp10"
                    android:paddingEnd="@dimen/dp20"
                    android:paddingBottom="@dimen/dp10"
                    android:text="@string/_new"
                    android:textColor="@color/dark_gray_text_color" />

                <TextView
                    android:id="@+id/text_view_normal"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingStart="@dimen/dp20"
                    android:paddingTop="@dimen/dp10"
                    android:paddingEnd="@dimen/dp20"
                    android:paddingBottom="@dimen/dp10"
                    android:text="@string/normal"
                    android:textColor="@color/dark_gray_text_color" />

                <TextView
                    android:id="@+id/text_view_old"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingStart="@dimen/dp20"
                    android:paddingTop="@dimen/dp10"
                    android:paddingEnd="@dimen/dp20"
                    android:paddingBottom="@dimen/dp10"
                    android:text="@string/old"
                    android:textColor="@color/dark_gray_text_color" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/constraint_layout_languages_root"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp20"
            android:background="@drawable/round_text_box_border_gray"
            android:orientation="horizontal">

            <LinearLayout
                android:id="@+id/linear_layout_2"
                android:layout_width="match_parent"
                android:layout_height="@dimen/textBoxHeight"
                android:orientation="horizontal">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="9"
                    android:gravity="center_vertical"
                    android:paddingStart="@dimen/dp20"
                    android:paddingEnd="@dimen/dp20"
                    android:text="@string/language"
                    android:textColor="@color/colorPrimaryDark" />

                <ImageButton
                    android:id="@+id/image_button_languages"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_marginEnd="@dimen/dp10"
                    android:layout_weight="1"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:src="@drawable/ic_spinner" />

            </LinearLayout>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/recycler_view_languages"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingStart="@dimen/dp20"
                android:paddingEnd="@dimen/dp20"
                android:paddingBottom="@dimen/dp10"
                android:visibility="gone" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

Fragment Java code:

package org.kitapp.UI.Fragments.SharePostFragments.Fragment1;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import org.kitapp.R;
import org.kitapp.UI.Dialogs.ConditionDialog.ConditionOfBookDialog;
import org.kitapp.UI.Dialogs.LanguageDialog.LanguageDialog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class OverViewFragment extends Fragment implements OverViewContractor.View {

    private final String TAG = OverViewFragment.class.getSimpleName();

    private Context mContext;
    private OverViewCallback mListener;

    private OverViewPresenter mPresenter;

    @BindView(R.id.constraint_layout_conditions_root)
    LinearLayout conditionRoot;

    @BindView(R.id.constraint_layout_languages_root)
    LinearLayout languagesRoot;

    @BindView(R.id.linear_layout_conditions)
    LinearLayout conditions;

    @BindView(R.id.root_layout)
    LinearLayout rootLayout;

    @BindView(R.id.text_view_number_of_characters)
    TextView numberOfChars;

    @BindView(R.id.edit_text_name_of_book)
    EditText nameOfBook;

    public interface OverViewCallback {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_over_view, container, false);
        ButterKnife.bind(this, view);

        new OverViewPresenter(this);

        //rootLayout.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING);

        return view;
    }

    ////// CONTRACTOR METHODS //////

    @Override
    public void setPresenter(OverViewPresenter presenter) {
        this.mPresenter = presenter;
    }

    ////// LISTENERS //////

    @Override
    @OnClick(R.id.image_button_conditions)
    public void showConds() {
        ConditionOfBookDialog conditionOfBookDialog = new ConditionOfBookDialog(mContext);
        conditionOfBookDialog.show();
    }

    @Override
    @OnClick(R.id.image_button_languages)
    public void showLangs() {
        LanguageDialog languageDialog = new LanguageDialog(mContext);
        languageDialog.show();
    }

    @Override
    @SuppressLint("SetTextI18n")
    @OnTextChanged(R.id.edit_text_name_of_book)
    public void onNameOfBookChange() {
        int len = nameOfBook.getText().toString().trim().length();
        numberOfChars.setText(len + "/50");
        if (len > 50) {
            nameOfBook.setText(nameOfBook.getText().toString().substring(0, 50));
            nameOfBook.setSelection(nameOfBook.getText().length());
        }
    }

    ////// FRAGMENT METHODS //////

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        this.mContext = context;

        if (context instanceof OverViewCallback) {
            mListener = (OverViewCallback) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OverViewCallback");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

}

UI Design and Dialog

In the image above, there are EditTexts Name Of Book and Name of Author. Before showing a dialog, both of them work like a charm. When writing something, the cursor automatically scrolls to the end. Once Dialog has been shown and dismissed, none of them works properly, and the cursor stays at the end of the EditText but still the characters are being written continues in the hidden part.

In this UI it cannot be seen because of the issue, but I've written. Roses are red, violets are blue, Stackoverflow I love u

But only Roses are red, violets are blue, Stac can be seen.

Weird buggy layout UI image

Please, help me to solve this problem. Thanks in advance.


Answer:

As a solution, I don't know the underlying reason, but the problem solved once I removed Butterknife library from my project.

Question:

Would highly appreciate any help with this as I am doing this for a project that's due soon.

I have my EditText and TextViews in a dialog box, being created in java, and I'm curious as to why nothing seems to be displaying properly...

It displays fine in android studio's rendering preview: Android Studio Screenshot

However, In the actual emulator this is what displays: Emulator Screenshot

Here is my name_entry.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Player 1 Name:"
    android:id="@+id/textView3" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/player1_name" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Player 2 Name:"
    android:id="@+id/textView4" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:enabled="true"
    android:id="@+id/player2_name" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Player 3 Name:"
    android:id="@+id/textView5" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/player3_name" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Player 4 Name:"
    android:id="@+id/textView6" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/player4_name" />

And here is my MainActivity.java:

package me.isaac.historyquiz;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    changeNames();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

public void changeNames() {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    LayoutInflater li = LayoutInflater.from(getApplicationContext());
    View promptsView = li.inflate(R.layout.name_entry, null);
    builder.setView(promptsView);

    final EditText p1_edit = (EditText) promptsView.findViewById(R.id.player1_name);
    final EditText p2_edit = (EditText) promptsView.findViewById(R.id.player2_name);
    final EditText p3_edit = (EditText) promptsView.findViewById(R.id.player3_name);
    final EditText p4_edit = (EditText) promptsView.findViewById(R.id.player4_name);

    builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            String player1 = "Player 1";
            String player2 = "Player 2";
            String player3 = "Player 3";
            String player4 = "Player 4";
            String player1_name = p1_edit.getText().toString();
            String player2_name = p2_edit.getText().toString();
            String player3_name = p3_edit.getText().toString();
            String player4_name = p4_edit.getText().toString();

            if(player1_name != "") {
                player1 = player1_name;
            }
            if(player2_name != "") {
                player2 = player2_name;
            }
            if(player3_name != "") {
                player3 = player3_name;
            }
            if(player4_name != "") {
                player4 = player4_name;
            }
            startGame(player1, player2, player3, player4);
        }
    });
    builder.setTitle("Player Names");
    builder.setCancelable(false);

    AlertDialog dialog = builder.create();
    dialog.show();
}

public void startGame(String player1, String player2, String player3, String player4) {
    Toast gameStarting = Toast.makeText(getApplicationContext(), "Game Starting...", Toast.LENGTH_LONG);
    gameStarting.setGravity(Gravity.BOTTOM|Gravity.RIGHT, 4, 4);
    gameStarting.getView().setBackgroundResource(R.drawable.toast_square);
    gameStarting.show();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}


@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.reset_game) {
        //Restart the app
        Context context = getApplicationContext();
        Intent mStartActivity = new Intent(context, MainActivity.class);
        int mPendingIntentId = 10108401;
        PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId,    mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
        System.exit(0);
    } else if(id == R.id.change_points) {
        //TODO: Change Points
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
  }
}

Answer:

Use this to get layout inflater from the current Activity

LayoutInflater li = this.getLayoutInflater();

instead of using LayoutInflater li = LayoutInflater.from(getApplicationContext());

Question:

To summarize, I made a custom layout for my dialog box, and there is an EditText inside it, from which I want to capture entered information. But I am not sure how to both:

1) instantiate a "new" EditText (to prevent null exception), AND

2) associate this new EditText with its ID in the layout (R.id.edit_name) so android knows to get info from the EditText INSIDE the dialogbox

The 4 lines of COMMENTED code is where I'm not sure which ones to use...

Any help is appreciated, thanks!

public class MainActivity extends AppCompatActivity {
     private Button button;
     private Context context = this;

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

}

public void onClickAddItem(View view) {
    final Dialog dialog = new Dialog(this);

    dialog.setContentView(R.layout.dialog_layout);
    // final EditText nameInput = new EditText(this);
    // nameInput.findViewById(R.id.edit_name);
    // EditText nameInput = new EditText(context);
    // final EditText nameInput = (EditText)findViewById(R.id.edit_name);


    final LinearLayout wholelist = (LinearLayout) findViewById (R.id.wholelist);

    button = (Button) findViewById(R.id.Adder);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Button OKbutton = (Button) dialog.findViewById(R.id.OK);
            OKbutton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                                         wholelist.addView(createNewTextView(nameInput.getText().toString()));



                    dialog.dismiss();
                }
            });

            dialog.show();
        }
    });
}

    private TextView createNewTextView(String text) {
        final TextView textView = new TextView(this);
        textView.setText(text);
        return textView;
    }

}


Answer:

Define your edit text as a global variable (out side your functions), so that you can use it where ever you want. Then initialize (introduce) it inside the onCreate function.

EditText nameInput; // define your edit text

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_inventory);

    nameInput = (EditText) findViewById(R.id.edit_name); // initialize your edit text
.
.
.

nameInput.getText().toString() // get data inside your edit text

When ever you need to read the information inside it just use this: nameInput.getText().toString() to read the data in it.

Question:

I got a NullPointerException using an EditText in a DialogAlert. My code looks like this:

        public class MainActivity extends ActionBarActivity {

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


        WelcomeDialog();
        }

            public Dialog WelcomeDialog() {

                AlertDialog.Builder builder = new AlertDialog.Builder(this);

                builder.setTitle("Server");
                builder.setMessage("Enter ADDRESS and PORT:");
                // Get the layout inflater
                LayoutInflater inflater = this.getLayoutInflater();
                // Pass null as the parent view because its going in the dialog layout
                View v = inflater.inflate(R.layout.dialog_welcome, null);
                builder.setView(v);
                // Use an EditText view to get user input.
                final EditText input1 = new EditText(this);
                input1.setId(address);
                builder.setView(input1);
                final EditText ETaddress = (EditText) v.findViewById(address);

                final EditText input2 = new EditText(this);
                input2.setId(port);
                builder.setView(input2);
                final EditText ETport = (EditText) v.findViewById(port);
                builder.setView(v)
                // Inflate and set the layout for the dialog
                        // Add action buttons
                        .setPositiveButton("connect", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                // The NULLPOINTER is in this line:
                                String str1 = ETaddress.getText().toString();
                                ((VariableHolder) getApplication()).setADDRESS(str1);
                                int str2 = Integer.parseInt(ETport.getText().toString());
                                ((VariableHolder) getApplication()).setPORT(str2);
                                set = true;

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

I suspect that the problem is here (wrong declaration or something like that):

            final EditText input1 = new EditText(this);
            input1.setId(address);
            builder.setView(input1);
            final EditText ETaddress = (EditText) v.findViewById(address);

...but I can't figure it out whats wrong. Any idea?

EDIT:

Here is the logcat Output:

> 01-06 19:40:28.241    4694-4694/com.example.console2
> E/AndroidRuntime﹕ FATAL EXCEPTION: main
>     java.lang.NullPointerException
>             at com.example.MainActivity$2.onClick(MainActivity.java:88)
>             at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
>             at android.os.Handler.dispatchMessage(Handler.java:99)
>             at android.os.Looper.loop(Looper.java:137)
>             at android.app.ActivityThread.main(ActivityThread.java:4611)
>             at java.lang.reflect.Method.invokeNative(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:511)
>             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
>             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
>             at dalvik.system.NativeStart.main(Native Method)

Answer:

Alright, that was a stupid mistake. Only forgot R.id before address respectively port:

final EditText ETaddress = (EditText)v.findViewById(R.id.address); // R.id. !!!

Question:

I have three editTexts in my dialog view. At first, I disable positive button and every thing is ok("ok" means that when the dialog is showed, the positive button is disable and this is what I want ). Now,I want to enable it if the length of my three editTexts be larger than zero. I have found some answers only for one editText. Can anyone help me?


Answer:

You could use the TextWatcher for each EditText to monitor the string length.

    boolean et1HasText, et2HasText, et3HasText; // Global variables
et1.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if(s.length > 0){ 
            et1HasText = true;
        }else{
            et1HasText = false;
        }
        validateButton();
}
// Other callbacks
...
...
});

et2.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if(s.length > 0){ 
            et2HasText = true;
        }else{
            et2HasText = false;
        }
        validateButton();
}
//Other callbacks
...
...
});

et3.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if(s.length > 0){ 
            et3HasText = true;
        }else{
            et3HasText = false;
        }
        validateButton();
}
//Other callbacks
...
...

});

private void validateButton(){
    if(et1HasText && et2HasText && et3HasText){
    //Enable the button only when all the 3 edit texts have text
        button.setEnabled(true);
    }else{
    //Disable otherwise (user clicks backspace and clears the edit text etc)
        button.setEnabled(false);
    }
}

Question:

Here is the method where I need to get the text from the EditText of AlertDialog

public void checkButton() {
    leggspillere = (Button) findViewById(R.id.leggspillere);       
    final LayoutInflater inflater = this.getLayoutInflater();       
    AlertDialog.Builder builder = new AlertDialog.Builder(this);   
    builder.setView(inflater.inflate(R.layout.create_user,null));              
    builder.setMessage("Lag en spiller");
    builder.setCancelable(true);
    builder.setPositiveButton("Ok",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {                
                // trying to get the EditText-string inside alertdialogbox input here.
                final String Name = UserName.                       
                Person person = new Person(Name, 0);                       
                dialog.dismiss();
                spillere.setText(person.getName() + " " + person.getScore());
            }
        }
    );
    //sette andre knappen "cancel"
    builder.setNegativeButton("no",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        }
    );
    AlertDialog alert = builder.create();
    alert.show();
}

XML:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:scaleType="center"
        android:background="#FFFFBB33"
        android:contentDescription="@string/app_name" />

    <EditText
        android:id="@+id/UserName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:inputType="textEmailAddress" />
</LinearLayout>

Trying to get the input/string from EditText.xml to make a person object. Always referencing to a null object. I can't find any solution, point me somewhere.


Answer:

How are you trying to access the editText inside DialogInterface.OnClickListener?

Try getting the inflated view in a View object and do findViewById on that View object variable. This code below should work fine:

LayoutInflater inflater = this.getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final View dialogView = inflater.inflate(R.layout.dialog_alert, null);
builder.setView(dialogView);
builder.setMessage("Lag en spiller");
builder.setCancelable(true);
builder.setPositiveButton("Ok",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                EditText editText = (EditText) dialogView.findViewById(R.id.d_alert_et);
                Log.v("tag", "Edit text value: " + editText.getText());
            }
        });
builder.setNegativeButton("no",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
AlertDialog alert = builder.create();
alert.show();

Basically get the inflated view in a View Object:

final View dialogView = inflater.inflate(R.layout.dialog_alert, null);

And then do findViewById on that View Object:

EditText editText = (EditText) dialogView.findViewById(R.id.d_alert_et);

editText.getText()

Question:

dialogBuilder.setMessage shows nothing! As if it is showing a null string. But, newUserPassword is updated with a newer input from the user via the EditText newPassword

public class OKActivity extends Activity {

EditText newPassword;
String newUserPassword;

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

    newPassword = (EditText) findViewById(R.id.new_password);
    newUserPassword = newPassword.getText().toString();
    getpasswordSharedPreferences();

    Button changePassword = (Button) findViewById(R.id.button_change);

    changePassword.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            setSharedPreferences();

        }
    });

}


private String getpasswordSharedPreferences() {

    SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
    String password = userPassword.getString("THE_PASSWORD", "123");
    return password;

}

private void setSharedPreferences() {
    SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
    SharedPreferences.Editor password_edior = userPassword.edit();
    password_edior.putString("THE_PASSWORD", newUserPassword);
    password_edior.commit();
    Toast.makeText(OKActivity.this, "Password Change Succesful", Toast.LENGTH_SHORT).show();
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(OKActivity.this);
        dialogBuilder.setIcon(R.drawable.ic_launcher);
        dialogBuilder.setTitle("Done!");
        dialogBuilder.setMessage(newUserPassword);
        dialogBuilder.setPositiveButton("OK", null);
        dialogBuilder.show();
}


Answer:

Try this:

public class OKActivity extends Activity {

EditText newPassword;
String newUserPassword;

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

    newPassword = (EditText) findViewById(R.id.new_password);
    //do not retrieve password here
    Button changePassword = (Button) findViewById(R.id.button_change);

    changePassword.setOnClickListener(new OnClickListener() {

        @Override 
        public void onClick(View arg0) {
            //retrieve password here. Assuming user has entered some string before clicking on changePassword button
            newUserPassword = newPassword.getText().toString();
            getpasswordSharedPreferences(); 
            setSharedPreferences(); 

        } 
    }); 

} 
private String getpasswordSharedPreferences() {

    SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
    String password = userPassword.getString("THE_PASSWORD", "123");
    return password;

} 

private void setSharedPreferences() { 
    SharedPreferences userPassword = getSharedPreferences("USER_PASSWORD", MODE_PRIVATE);
    SharedPreferences.Editor password_edior = userPassword.edit();
    password_edior.putString("THE_PASSWORD", newUserPassword);
    password_edior.commit();
    Toast.makeText(OKActivity.this, "Password Change Succesful", Toast.LENGTH_SHORT).show();
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(OKActivity.this);
        dialogBuilder.setIcon(R.drawable.ic_launcher);
        dialogBuilder.setTitle("Done!");
        dialogBuilder.setMessage(newUserPassword);
        dialogBuilder.setPositiveButton("OK", null);
        dialogBuilder.show();
} 

Question:

I want to give the output, which was entered by the user in EditText, in a detailed manner in a separate dialog box, by using the values of those entered values in the edittext. Any help will be appreciated.

Here is the code:

EditText editText1,editText2,editText3;
Button btn,btn2;

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

    btn = (Button) findViewById(R.id.btn);
    btn2 = (Button) findViewById(R.id.btn2);

    editText1 = (EditText) findViewById(R.id.editText2);
    editText2 = (EditText) findViewById(R.id.editText3);
    editText3 = (EditText) findViewById(R.id.editText4);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            calculate();
        }
    });

    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

            String s = " (Result) ";
            alertDialogBuilder.setTitle("Detailed Output is");
            alertDialogBuilder.setCancelable(false);
            alertDialogBuilder.setMessage("(The code should be like as follows)\n\n"+"sum of entered number is:"+s+"\n"+"multiply of entered number is:"+s+"\n"+"subtraction of entered number is:"+s)

                    .setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();

        }
    });
}
    public void calculate() {

        String a = editText1.getText().toString();
        String b = editText2.getText().toString();
        editText3.setText(String.valueOf(Integer.parseInt(a)+ Integer.parseInt(b))+"\n"+String.valueOf(Integer.parseInt(a)* Integer.parseInt(b))+"\n"+String.valueOf(Integer.parseInt(a)-Integer.parseInt(b)));
    }
}

Answer:

you can user String.Format to format your string with input parameters.

alertDialogBuilder.setMessage(String.format("(The code should be like as follows)\n\n"+"sum of entered number is:%s\n multiply of entered number is:%s \n subtraction of entered number is:%s"),editText1.getText().toString(), editText2.getText().toString(), editText3.getText().toString())

Question:

I have a timeIn editText in my app. When it is clicked, it will pop up TimePicker dialog.

    timeIn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) { //shows timePick
                    isEdited=true;
                    Fragment fragDialog = getSupportFragmentManager().findFragmentByTag("TimePicker");
                    if (fragDialog == null) { // Fragment not added
                        tp.setFlag(TimePick.FLAG_START_DATE);
                        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                        tp.show(ft, "TimePicker");
                    } else {

                        // already active
                    }
                }
            });


  public static class TimePick extends android.support.v4.app.DialogFragment implements TimePickerDialog.OnTimeSetListener {

        public static final int FLAG_START_DATE = 00;
        public static final int FLAG_END_DATE = 01;
        private int flag = 00;

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {

            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }

        public void setFlag(int i) {
            flag = i;
        }


        @Override
        public void onTimeSet(TimePicker view, int hourofDay, int minute) {

            if (flag == FLAG_START_DATE) {
                timeIn.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
                TimeIn = timeIn.getText().toString();
            }
            if (flag == FLAG_END_DATE) {
                timeOut.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
                TimeOut = timeOut.getText().toString();
            }



        }

    }

The time selected can be setText in timeIn. But when I click the timeIn editText again, the timePicker dialog popup with the current time . Is it possible to make it display the selected time instead of current time ? If it is first time click, then only show current time.


Answer:

Isn't that what you are doing here

final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));

You are passing the current time to the dialog, that's why its showing the current time.

Solution:

Save the selected time and pass that to the class while creating the dialog and use that time in this code. If you don't have any selected time then use the current time. A little if-else block and some variables will do the trick.

Define these variable in outer class.

public static int inHour = -1;
public static int inMin = -1;
public static int outHour = -1;
public static int outMin = -1;

update onTimeSet method like this

if (flag == FLAG_START_DATE) {
    inHour = hourofDay;
    inMin = minute;
    timeIn.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
    TimeIn = timeIn.getText().toString();
}
else if (flag == FLAG_END_DATE) {
    outHour = hourofDay;
    outMin = minute;
    timeOut.setText(Integer.toString(hourofDay) + ":" + Integer.toString(minute));
    TimeOut = timeOut.getText().toString();
}

Replace your current code in onCreateDialog with

final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
if((flag == FLAG_START_DATE) && inHour != -1 && inMin != -1) 
{
     hour = inHour;
     min = inMin;
}
else if((flag == FLAG_END_DATE) && outHour != -1 && outMin != -1) 
{
     hour = outHour;
     min = outMin;
}

return new TimePickerDialog(getActivity(), this, hour, min, DateFormat.is24HourFormat(getActivity()));

Question:

I have created two different editText, previous Inspection Date and current inspection date. I'm using fragment and DatePickerDialog to get the dates. Each editText will have their own dates. How do I passed the dates in datePickerDialog?

P.s I'm using onFocusChange so that the dialog popup when user click on editText. Using setOnClickListener will require user to double click to show the datePickerDialog.

FormFragment.java

public class FormFragment extends Fragment {

....

    //TODO : Fixed datepicker & time picker

    //get Date func
    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }

    //get time func
    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");
    }


    public void onViewCreated(final View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //get CaseDetailActivity
        final Activity activity = this.getActivity();

        /*
        Use onFocusChangeListener - the dialog automatically popped when clicked on edittext
        */

        //inspection date
        final View editText_date = activity.findViewById(R.id.input_inspecDateNew);
        editText_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    //get current text
                    showDatePickerDialog(v);
                }
            }
        });

        //previous inspection date
        View editText_prevDate = activity.findViewById(R.id.input_lastInspecDate);
        editText_prevDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    //get current text
                    showDatePickerDialog(v);
                }
            }
        });
    }
}

DatePickerFragment.java

public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    public static EditText editText;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);

    }

    public void getCurrentDate () {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = df.format(c.getTime());

        editText.setText(formattedDate);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, day);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(c.getTime());

        editText.setText(formattedDate);
    }
}

Answer:

You can use setTargetFragment and onActivityResult to achieve this,

You can try like this

FormFragment.java

public class FormFragment extends Fragment {

    private static final String TAG = FormFragment.class.getSimpleName();

    private static final int REQUEST_CODE_INSPECDATENEW = 200;
    private static final int REQUEST_CODE_LASTINSPECDATE = 201;

    private EditText editText_date;
    private EditText editText_prevDate;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank2, container, false);
    }

    //get Date func
    public void showDatePickerDialog(View v, int requestCode) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.setTargetFragment(this, requestCode);
        newFragment.show(getFragmentManager(), "datePicker");
    }

    public void onViewCreated(final View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //inspection date
        editText_date = view.findViewById(R.id.input_inspecDateNew);
        editText_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    //get current text
                    showDatePickerDialog(v, REQUEST_CODE_INSPECDATENEW);
                }
            }
        });

        //previous inspection date
        editText_prevDate = view.findViewById(R.id.input_lastInspecDate);
        editText_prevDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    //get current text
                    showDatePickerDialog(v, REQUEST_CODE_LASTINSPECDATE);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d(TAG, "onActivityResult: ");

        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                return;
            }

            String dataValue = data.getStringExtra("value");

            if (requestCode == REQUEST_CODE_INSPECDATENEW) {
                editText_date.setText(dataValue);
            } else if (requestCode == REQUEST_CODE_LASTINSPECDATE) {
                editText_prevDate.setText(dataValue);
            }
        }
    }
}

fragment_blank2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
              android:orientation="vertical"
             android:layout_height="match_parent">

    <EditText
        android:id="@+id/input_inspecDateNew"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_blank_fragment"/>

    <EditText
        android:id="@+id/input_lastInspecDate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_blank_fragment"/>

</LinearLayout>

DatePickerFragment.java

public class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

//    public static EditText editText;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);

    }

    public void getCurrentDate() {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = df.format(c.getTime());


//        editText.setText(formattedDate);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, day);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(c.getTime());

        Intent intent = new Intent();
        intent.putExtra("value", formattedDate);

        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
//        editText.setText(formattedDate);
    }
}

Question:

Like the title said how can I get text out of EditText which is found inside a custom dialog?

This is the onCreateDialog method from my dialogfragment:

public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedPref.edit();

    builder.setView(inflater.inflate(R.layout.name_dialog, null))
           .setPositiveButton(R.string.name_ok, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   EditText nameEditText = (EditText) getActivity().findViewById(R.id.name_text_view);
                   editor.putString(getString(R.string.name_key), nameEditText.getText().toString());
                   editor.commit();
               }
           })
           .setNegativeButton(R.string.name_cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   NameDialogFragment.this.getDialog().cancel();
               }
           });      
    return builder.create();
}

I can't get it to work.. I write something in the edittext then i press OK and it just crashes and gives me a null pointer error on this line :

editor.putString(getString(R.string.name_key), nameEditText.getText().toString());

Answer:

You are looking for the EditText at the wrong View. Its not part of the Activity, its part of the dialog. So check the dialog for the view:

 Dialog dialogView = dialog.getDialog();
 EditText paymentEt = (EditText) dialogView.findViewById(R.id.edittext_payment);

Question:

I want my AlertDialog to pop up as soon as my EditText has focus. Right now, I have to click on my EditText twice.

The first time I click my EditText, the soft keypad appears (for typing directly in my Edittext). Then, the second time I click the EditText, the AlertDialog appears.

How can I have it so only one click on the EditText is needed for the AlertDialog to pop up?

Here's my code:

In my onCreate...

//when user clicks on "commentName" EditText we want a new AlertDialog to open
commentName.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

    AlertDialog.Builder builder = new AlertDialog.Builder(NewContact.this);
    builder.setTitle("Ur Comment:");

    //start the following xml file/ layout
    View viewInflated = LayoutInflater.from(NewContact.this).inflate(R.layout.comment_text_pop_up, null, false);
    builder.setView(viewInflated);

    // Set up the buttons
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
      }
    });
    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
      }
    });

    builder.show();

  }
});

Answer:

I got it to work according to your description with an OnFocusChangeListener.

Just replace the entire snippet from your question with the following. And paste in the AlertDialog code below the comment.

// commentName is your EditText
commentName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            return; // Prevents alert from being shown when losing focus.
        }
        // Your AlertDialog code goes here
    }
});

The if (!hasFocus) prevents the alert from being shown when the user clicks something else that makes the EditText lose focus.

Question:

I am so tired on finding the mistake. I didn't find any mistake but I am getting no text from editText. please Look at following Code:

activity_pwd.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter PIN "
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/pwdValue"
    android:layout_width="match_parent"
    android:maxLength="4"
    android:maxLines="1"
    android:inputType="numberPassword"
    android:layout_height="wrap_content">
</EditText>
</LinearLayout>

I called LockImmediately(this); on onCreate method of MainActivity

    public void LockImmediately(Context context) {
    if (lock_app) {
        View myview = LayoutInflater.from(context).inflate(R.layout.activity_pwd,null);
        enterPWD  = (EditText) myview.findViewById(R.id.pwdValue);

        AlertDialog alertDialog = new AlertDialog.Builder(this).setCancelable(false)
                .setView(R.layout.activity_pwd).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String user_text = enterPWD.getText().toString();
                        Log.d("onCreate pws", " i "+user_text);
                        if (pwd.equals(user_text)) {
                            dialog.dismiss();
                            Log.d("onCreate", "Work done");
                        } else {
                            dialog.dismiss();
                            MainActivity.this.finish();
                        }
                    }
                }).create();
        alertDialog.show();
    }
}

Log.d

 02-15 23:15:30.840 29379-29379/com.developersqueen.wishlater D/onCreate: onCreate
 02-15 23:15:37.021 29379-29379/com.developersqueen.wishlater D/onCreate pws:  i 
 02-15 23:15:45.427 29379-29379/com.developersqueen.wishlater D/onCreate:  onCreate
 02-15 23:15:49.026 29379-29379/com.developersqueen.wishlater D/onCreate pws:  i 

You can see that log above that I have concatenate edittext value with "i" but it's returning no value.. I have tried clearing data, unistalling app, clean, build everything but same result always!! Any help would be appreciated..


Answer:

When you are setting the view to the AlertDialog, you should set the view, where you found the ID of the EditText.

You have used myview to find the ID of the EditText, but you are trying to get myView from the Activity, not from the Dialog.

If you set the view to be myview, you can get the text from the enterPWD EditText.

AlertDialog alertDialog = new AlertDialog.Builder(this).setCancelable(false)
                .setView(myview).setPositiveButton("OK", new DialogInterface.OnClickListener() {
...
}

You should create a separate layout for the Activity and for the Dialog itself. Not to use one layout for both.

Question:

I'm trying to implement a mask in the EditText, the EditText appears when the user clicks in a TextView field and a alertdialog pops up, that EditText is inside an AlertDialog, but somehow the listener is not working. What am I missing here?

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

        numero = (TextView) findViewById(R.id.edit_numero);

        numero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog("Text");
            }
        });
    }


    public void dialog(String titulo) {

        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);

        dialog.setCancelable(true);

        LayoutInflater factory = LayoutInflater.from(MainActivity.this);
        View view = factory.inflate(R.layout.observacao, null);

        EditText observacao = (EditText) view.findViewById(R.id.numero);
        Mask.insert("###.###.###-##", observacao);

        TextView obslabel = (TextView) view.findViewById(R.id.obslabel);

        obslabel.setText(titulo);

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {



            }
        });

        dialog.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.setView(view);

        dialog.show();
    }

    public static class Mask {
        public static String unmask(String s) {
            return s.replaceAll("[.]", "").replaceAll("[-]", "")
                    .replaceAll("[/]", "").replaceAll("[(]", "")
                    .replaceAll("[)]", "");
        }

        public static TextWatcher insert(final String mask, final EditText ediTxt) {
            return new TextWatcher() {
                boolean isUpdating;
                String old = "";

                public void onTextChanged(CharSequence s, int start, int before,
                                          int count) {
                    String str = Mask.unmask(s.toString());
                    String mascara = "";
                    if (isUpdating) {
                        old = str;
                        isUpdating = false;
                        return;
                    }
                    int i = 0;
                    for (char m : mask.toCharArray()) {
                        if (m != '#' && str.length() > old.length()) {
                            mascara += m;
                            continue;
                        }
                        try {
                            mascara += str.charAt(i);
                        } catch (Exception e) {
                            break;
                        }
                        i++;
                    }
                    isUpdating = true;
                    ediTxt.setText(mascara);
                    ediTxt.setSelection(mascara.length());
                }

                public void beforeTextChanged(CharSequence s, int start, int count,
                                              int after) {
                }

                public void afterTextChanged(Editable s) {
                }
            };
        }
    }

Answer:

You have to use the TextWatcher you obtain by calling

Mask.insert("###.###.###-##", observacao);

with the EditText, so change that line to

observacao.addTextChangedListener(Mask.insert("###.###.###-##", observacao));

Question:

Making a to-do list. Having 2 issues, The not so important issue is that for some reason I can't see the TextView's that I set up as "labels". The more important thing is that when I click the create new task button, my alert pops up, I can put values in my EditText boxes, but when I hit create, it crashes and I get a NullPointer exception saying I'm trying to call getText() on a null object reference. I can't figure out if I'm inflating incorrectly or if I'm not linking the EditTexts to the alert properly. The annoying thing is that my edittext alert box works just fine editing existing list items(that I hardcoded for testing). Here's my layout and activity, I commented the line in which it breaks. Sorry about all the Log.d's I'm really trying to visualize how all this works.

The Layout

<?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">

    <EditText
        android:layout_width="55dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/txtCreatePriority"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="25dp"
        android:hint="1"
        android:textAlignment="center" />

    <EditText
        android:layout_width="235dp"
        android:layout_height="wrap_content"
        android:id="@+id/txtCreateItemContent"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/txtCreatePriority"
        android:layout_toEndOf="@+id/txtCreatePriority"
        android:layout_marginLeft="15dp"
        android:hint="Do Laundry"
        android:textAlignment="center" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Priority"
        android:id="@+id/lblPriority"
        android:layout_above="@+id/txtCreatePriority"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="17dp"
        android:textStyle="bold"
        android:textSize="23dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Task to-do"
        android:id="@+id/lblItemContent"
        android:layout_above="@+id/txtCreateItemContent"
        android:layout_toRightOf="@+id/lblPriority"
        android:layout_toEndOf="@+id/lblPriority"
        android:layout_marginLeft="65dp"
        android:textStyle="bold"
        android:textSize="23dp" />
</RelativeLayout>

The Activity

public class MainActivity extends AppCompatActivity {

    private ListDataSource ds;
    private ListView listViewToDo;
    private Button btnAddNew;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Context context = this;
        Log.d("MainActivity","Attempting to create data source");
        try {
            ds = new ListDataSource();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            Log.d("MainActivity","Failed to create data source");
        }
        btnAddNew = (Button)findViewById(R.id.btnAddNew);
        Log.d("Main Activity","Attempting to link empty list view to on screen view");
        listViewToDo = (ListView)findViewById(R.id.listOfLists);
        Log.d("Main Activity", "Views linked, Attempting to set adapter to listView");
        listViewToDo.setAdapter(new ListDataSourceAdapter(this, ds));
        Log.d("Main Activity", "Successfully set Adapter");
        btnAddNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("addItem", "Entered onclick, Attempting to create AlertDialog");
                AlertDialog.Builder addItem = new AlertDialog.Builder(context);
                Log.d("addItem", "AlertDialog Built, attempting to create inflater");
                LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                addItem.setView(inflater.inflate(R.layout.create_item_layout, null));
                Log.d("addItem", "inflater built linking text boxes");
                final TextView txtCreatePriority = (TextView)findViewById(R.id.txtCreatePriority);
                final TextView txtCreateCellContent = (TextView)findViewById(R.id.txtCreateItemContent);
                final TextView lblPriority = (TextView)findViewById(R.id.lblPriority);
                final TextView lblItemContent = (TextView)findViewById(R.id.lblItemContent);
                addItem.setTitle("Create new item");
                addItem
                        .setCancelable(false)
                        .setPositiveButton("Create", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Log.d("editText onClick", "in onClick method, preparing to add entry");
                                // This is where the code breaks
                                ds.getList().add(Integer.valueOf(txtCreatePriority.getText().toString()), new CellContent(Integer.valueOf(txtCreatePriority.getText().toString()) + 1, txtCreateCellContent.getText().toString().trim()));
                                Log.d("editText onClick", "added new entry");
                                ListDataSourceAdapter adapter = new ListDataSourceAdapter(context, ds);
                                Log.d("editText onClick", "reestablished link to adapter");
                                listViewToDo.setAdapter(adapter);
                                Log.d("editText onClick", "adapter set");
                                adapter.notifyDataSetChanged();
                                Log.d("editText onClick", "DataSetChanged");
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alertDialog = addItem.create();
                alertDialog.show();
            }
        });
        // add button listener
        listViewToDo.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
            {
                AlertDialog.Builder editItem = new AlertDialog.Builder(context);
                final EditText edittext = new EditText(context);
                editItem.setTitle("Change item");
                editItem
                        .setMessage("Set new todo item")
                        .setView(edittext)
                        .setCancelable(false)
                        .setPositiveButton("Submit", new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                Log.d("editText onClick","in onClick method, preparing to remove previous entry");
                                ds.getList().remove(position);
                                Log.d("editText onClick", "removed previous entry");
                                ds.getList().add(position, new CellContent(position + 1, edittext.getText().toString().trim()));
                                Log.d("editText onClick", "added new entry");
                                ListDataSourceAdapter adapter = new ListDataSourceAdapter(context,ds);
                                Log.d("editText onClick","reestablished link to adapter");
                                listViewToDo.setAdapter(adapter);
                                Log.d("editText onClick", "adapter set");
                                adapter.notifyDataSetChanged();
                                Log.d("editText onClick", "DataSetChanged");
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                AlertDialog alertDialog = editItem.create();
                alertDialog.show();
            }
        });
    }
}

The Error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

Answer:

You're calling "(EditText)v.findViewById" on the view v. The view v is the view passed back in the onClickListener, which is the button itself. Since that button does not contain the EditTexts within it, those views are null. And crash when you try to access them.

I'm a little uncertain where the layout with the edit texts is in this code. Is it in the same layout as the listview, or in create_item_layout?

If its create_item_layout, that needs to be inflated before getting the EditTexts. Use the view you inflate to findViewById.

Question:

I have a problem.

I made custom Dialog(loading spinner). I touching down the Button. Then opens RelativeLayout with table and edit text which works like search.

My problem is that when i show loader between button touch and opening Layout it focuses on EditText but doesn't show keyboard. When i don't use my dialog, it works fine. I tried it on foreground and in thread - the same result.

XML:

        <ProgressBar
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:indeterminateOnly="false"
            android:id="@+id/loader_spiner"

            android:background = "@xml/progress"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

Code:

 public void prepareLoader(){
        loader = new Dialog(context);
        loader.setContentView(R.layout.ag_loader);
        loader.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        spinerLoader = (ProgressBar) loader.findViewById(R.id.loader_spiner);
    }

    public void showLoader(){

        spinerLoader.startAnimation(AnimationUtils.loadAnimation(this, R.xml.splash_spinner));
        loader.show();
    }

    public static void hideLoader(){

        loader.hide();

    }

Thanks a lot.


Answer:

in 'loader.show()' you can try this code to show keyboard:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

or:

loader.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

or:

loader.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

or if not work again try it:

Handler delayedRun = new Handler();
delayedRun.post(new Runnable() {
  @Override
  public void run() {
    youreditText.requestFocus();
    InputMethodManager mgr = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.showSoftInput(youreditText, InputMethodManager.SHOW_IMPLICIT);
  }
});

Question:

I'm checking for invalid input to a group of edit texts in an alert dialog, by checking for null input and calling setError. But in my current implementation the dialog still closes even though there has been invalid input.

A boolean check has been added to each edit text to prevent the dialog from being dismissed if any of the edit texts set the boolean to false like this:

      else if(TextUtils.isEmpty(strColour)) {
        colourText.setError("Please enter a value");
        entriesValid = false;

` But the dialog is still dismissed despite the invalid input.

My question, whats the error here that allows the dialog to close on invalid input?

I set a break point on this line, if(entriesValid) to check if the condition is triggered but it doesn't break here meaning that the check is be skipped.

This is the complete custom dialog class:

public class MyMessageDialog  {

    public interface MyMessageDialogListener {
        public void onClosed(String ship, String scientist, String email, String volume, String color);
    }

@SuppressLint("NewApi") 
public static AlertDialog displayMessage(Context context, String title, String message, final MyMessageDialogListener listener){ 
    AlertDialog.Builder builder = new AlertDialog.Builder(context); 
    LayoutInflater inflater = LayoutInflater.from(context);
    builder.setTitle(title); 
    builder.setMessage(message); 
    final View layoutView = inflater.inflate(R.layout.custom_view, null);
    builder.setView(layoutView);
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialog, int which) { 
        boolean entriesValid = true;
        // get the edit text values here and pass them back via the listener
        if(listener != null)
        {
        EditText shipText = (EditText)layoutView.findViewById(R.id.shipNameEditText);
        EditText scientistNameText = (EditText)layoutView.findViewById(R.id.scientistEditText);
        EditText scientistEmailText = (EditText)layoutView.findViewById(R.id.emailEditText);
        EditText volumeText = (EditText)layoutView.findViewById(R.id.volumeEditText);
        EditText colourText = (EditText)layoutView.findViewById(R.id.colourEditText);



        listener.onClosed(shipText.getText().toString(),
                scientistNameText.getText().toString(),
                scientistEmailText.getText().toString(),
                volumeText.getText().toString(),
                colourText.getText().toString());

        String strShipName = shipText.getText().toString();
        String strScientistName = scientistNameText.getText().toString();
        String strScientistEmail = scientistEmailText.getText().toString();
        String strVolume = volumeText.getText().toString();
        String strColour = colourText.getText().toString();
        if(TextUtils.isEmpty(strShipName)) {
            shipText.setError("Please enter a value");
            entriesValid = false;
         }
        else if(TextUtils.isEmpty(strShipName)) {
            shipText.setError("Please enter a value");
            entriesValid = false;
         }
        else if(TextUtils.isEmpty(strScientistName)) {
            scientistNameText.setError("Please enter a value");
            entriesValid = false;
         }
        else if(TextUtils.isEmpty(strScientistEmail)) {
            scientistEmailText.setError("Please enter a value");
            entriesValid = false;
         }
        else if(TextUtils.isEmpty(strVolume)) {
            volumeText.setError("Please enter a value");
            entriesValid = false;
         }
        else if(TextUtils.isEmpty(strColour)) {
            colourText.setError("Please enter a value");
            entriesValid = false;
         }
        }
        if(entriesValid)
            dialog.dismiss(); 
        } 
        }); 
        builder.show(); 
        return builder.create();
    } 

}

Answer:

Instead of checking listener to be null, add a try catch block. I have not tried this code. But my idea is to remove listener block with try catch and set the boolean flag accordingly. That way it becomes simple.

@SuppressLint("NewApi") 
        public static AlertDialog displayMessage(Context context, String title, String message, final MyMessageDialogListener listener){ 
            AlertDialog.Builder builder = new AlertDialog.Builder(context); 
            LayoutInflater inflater = LayoutInflater.from(context);
            builder.setTitle(title); 
            builder.setMessage(message); 
            final View layoutView = inflater.inflate(R.layout.custom_view, null);
            builder.setView(layoutView);
            builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
                boolean entriesValid = true;
                // get the edit text values here and pass them back via the listener
               try
                {
                EditText shipText = (EditText)layoutView.findViewById(R.id.shipNameEditText);
                EditText scientistNameText = (EditText)layoutView.findViewById(R.id.scientistEditText);
                EditText scientistEmailText = (EditText)layoutView.findViewById(R.id.emailEditText);
                EditText volumeText = (EditText)layoutView.findViewById(R.id.volumeEditText);
                EditText colourText = (EditText)layoutView.findViewById(R.id.colourEditText);

                String strShipName = shipText.getText().toString();
                String strScientistName = scientistNameText.getText().toString();
                String strScientistEmail = scientistEmailText.getText().toString();
                String strVolume = volumeText.getText().toString();
                String strColour = colourText.getText().toString();

                if(TextUtils.isEmpty(strShipName)) {
                    shipText.setError("Please enter a value");
                    entriesValid = false;
                 }
                else if(TextUtils.isEmpty(strShipName)) {
                    shipText.setError("Please enter a value");
                    entriesValid = false;
                 }
                else if(TextUtils.isEmpty(strScientistName)) {
                    scientistNameText.setError("Please enter a value");
                    entriesValid = false;
                 }
                else if(TextUtils.isEmpty(strScientistEmail)) {
                    scientistEmailText.setError("Please enter a value");
                    entriesValid = false;
                 }
                else if(TextUtils.isEmpty(strVolume)) {
                    volumeText.setError("Please enter a value");
                    entriesValid = false;
                 }
                else if(TextUtils.isEmpty(strColour)) {
                    colourText.setError("Please enter a value");
                    entriesValid = false;
                 }
                }
    catch(Exception e)
    {
    entriesValid = false;
    }
                if(entriesValid)
                    dialog.dismiss(); 
                } 
                }); 
                builder.show(); 
                return builder.create();
            } 

update - New solution - Tried and worked for me

public class Help_DialogScreen extends Dialog implements OnClickListener{
 Context context;
    public Help_DialogScreen(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        this.context=context;
    }

    @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.help_homescreen);

        EditText tvGoToAddExpense = (EditText)findViewById(R.id.txtGoToAddExpense);

        Button btnTestCLick = (Button)findViewById(R.id.btnTestClick);

        btnTestCLick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context, "Click fired", Toast.LENGTH_SHORT).show();
                // I have used Toast to show that on click of button, dialog is not getting dismissed. You can add your code and do your logic here.
            }
        });


      }

    @Override
    public void onClick(DialogInterface dialog, int which) {

        dismiss();
    }

}

In the code where you should show the dialog, add this code

Help_DialogScreen cdd=new Help_DialogScreen(CURRENTACTIVITY.this);
                cdd.show();

Question:

this is my last desperate attempt to fix this problem.

i am using dialogfragment to make my dialog window MyDialog. the window is supposed to show a score I have sent with and the user can then write in their name and confirm. i am then supposed to be able to retrieve their name.

My first problem is that the edittext that are supposed to show the score, doesn't want to show the score i set the edittext to be (it will only show new text if it was in the xml file). I can however still retrieve the correct score(text) afterwards from the same edittext.

The second problem is that the text that the user writes in can't be retrieved since the edittext isn't updating. However the text that was in the field from the xml file can be retrieved.

It seems like the edittext doesn't want to refresh after they are made in the xml file.

the dialog class (imports taken out):

public class MyDialog extends DialogFragment 
{
private EditText scoreEdit;
private EditText userEdit;

private DialogClickListener callback;
public interface DialogClickListener 
{
    public void onFinishedClick();
}
@Override 
public void onCreate(Bundle savedInstanceState)
{    
        super.onCreate(savedInstanceState);
        try 
        {
            callback = (DialogClickListener) getActivity();
        }catch(ClassCastException e)
        {
            throw new ClassCastException("called class must implement interface");
        }
}
public static MyDialog newInstance(int title)
{   
        MyDialog frag = new MyDialog(); 
        Bundle  args = new Bundle();    
        args.putInt("tittel",title);
        frag.setArguments(args);    
        return  frag;   
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View inflatedView = inflater.inflate(R.layout.dig_lay, null);
    scoreEdit = (EditText) inflatedView.findViewById(R.id.dialogScoreEdit);
    userEdit = (EditText) inflatedView.findViewById(R.id.dialogUsernameEdit);

    scoreEdit.setText("score supposed to change"); 
   // scoreEdit (edittext) is not changing 

    dialog.setView(inflater.inflate(R.layout.dig_lay, null));
    dialog.setTitle("Title");
    dialog.setPositiveButton("reg1", new DialogInterface.OnClickListener() 
    {
        @Override
        public void onClick(DialogInterface dialog, int whichButton) 
        {
            System.out.println("new text supposed to be: " + userEdit.getText().toString()); 
            //old text from xml shows 
            callback.onFinishedClick();
        }
    });
    setCancelable(false);
    return dialog.create(); 
}
}

the XML file for the dialog window:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialogLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" 
    android:layout_marginTop="16dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginBottom="4dp">

       <TextView
        android:text="score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
      <EditText 
        android:id="@+id/dialogScoreEdit"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content" 
        android:hint="score here"
        android:inputType="none"/>
    </LinearLayout>

  <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" 
    android:layout_marginTop="4dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginBottom="16dp"
    android:fontFamily="sans-serif">

      <TextView
        android:text="Username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
      <EditText 
        android:id="@+id/dialogUsernameEdit"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content" 
        android:text="retrive this"
        android:inputType="none"/> 
    </LinearLayout>
</LinearLayout>

picture of the dialogwindow: http://i.stack.imgur.com/EvwSe.png

I have tried calling onResume() and putting the new score in. but the edittext still doesn't change.

I appreciate any answer and sorry for any bad English :)


Answer:

It looks like there are a few issues there. The ones I have noticed are that when you set your view you are reinflating the view, versus setting it to the view you have already set up when you do dialog.setView(inflater.inflate(R.layout.dig_lay, null)); you want to set that instead to dialog.setView(inflatedView);

Also, since we can't see the actual data you are putting into the EditText, we can't see if that might be null, etc.

Finally, I never see you run a scoreEdit.getText(), so you wouldn't be retrieving any changes the user made to the edittext.

Question:

So, I've researched quite a bit to try and implement a simple PIN authentication system for a Hello World game application. Unfortunately, I think a few things are still going over my head.

As my code currently stands, it shows the dialog box and does not allow it to be canceled. However, the EditText field no longer appears, which defeats the purpose of asking for a PIN. I think that a linked XML file will be needed for layout purposes, however, Android Studio does not seem to accept a call to such a file (i.e. pinauth.setView(findViewById(R.layout.dialog_pin));, which I don't think is the correct structure anyway.

Any assistance you can provide would be greatly appreciated. The code for the entire method is posted below.


public void auth(View v)
{

// The logout method works fine, since no PIN is necessary.
if(users.getBoolean("activeLogin", false) == true) successLogout();
    else
    {
        // Get selected user and pull SharedPreferences to get stored PIN.
        final String activeUser = userList.getSelectedItem().toString();
        scores = getSharedPreferences(activeUser, 0);

        // If a PIN is found on file, launch AlertDialog to prompt for PIN. No XML file is linked to the AlertDialog at this time.
        if(scores.getInt("pin", 123456789) != 123456789)
        {
            AlertDialog.Builder pinAuth = new AlertDialog.Builder(this);
            pinAuth.setTitle("PIN required.");
            pinAuth.setMessage("Please enter your pin.");
            pinAuth.setCancelable(false);
            pinAuth.setView(findViewById(R.layout.dialog_pin))
            final EditText pin = new EditText(this);
            pin.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);

            // These checks seem to work ok.
            pinAuth.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if(pin.getText().toString().isEmpty())
                    {
                        makeToast("Sorry, no pin was entered.", Toast.LENGTH_SHORT);
                        return;
                    }
                    else if(Integer.valueOf(pin.getText().toString()) != scores.getInt("pin", 123456789))
                    {
                        makeToast("Sorry, that pin was incorrect. Try again.", Toast.LENGTH_SHORT);
                        return;
                    }
                    else
                        successLogin(activeUser);

                }
            });

            // Show the AlertDialog.
            pinAuth.show();
        }

        // if the account has no PIN
        else successLogin(activeUser);
    }
}

As a side note, the PIN can only be up to 8 numeric characters, so 123456789 is an impossible PIN to create in the first place and therefore the conditional statement checking for the pin not to be equal to said number should not interfere with the operation.


Answer:

You need to inflate the custom layout first.

AlertDialog.Builder pinAuth = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.dialog_pin, null);

pinAuth.setTitle("PIN required.");
pinAuth.setCancelable(false);
pinAuth.setView(view);

final EditText pin = (EditText) view.findViewById(R.id.whateverThisEditTextIdIs);
pin.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);

Note that I have also changed how you reference/create an EditText object. I have also taken away the use of pinAuth.setMessage() because your custom layout could be displaying that message.

Question:

I've been scratching my head over this for a few nights now. I cannot seem to get an EditText (set as a view for an AlertDialog) to automatically spell check when entering text, even though I know spell check is enabled because it's working elsewhere:

error showing spell check not working

I've seen several posts where the dev wants spellcheck disabled, but none where it wasn't working that have any resolution. Is this something disabled because I'm using an AlertDialog (EditTexts elsewhere are working), and if so, is there any kind of workaround or any other solution besides an AlertDialog that I can try?

Here is my code:

final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES|InputType.TYPE_TEXT_FLAG_AUTO_CORRECT|InputType.TYPE_TEXT_FLAG_MULTI_LINE|InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE); //I have tried all combinations of InputType options, including no options.
input.setSingleLine(false);
input.setMaxLines(6);
input.setText("Some Default Text");
input.setSelectAllOnFocus(true);
input.requestFocus();
builder.setView(input);
builder.show();

UPDATE:

I just tried inflating the following layout file:

<android.support.constraint.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="wrap_content">

    <TextView
        android:id="@+id/txtJournalSummaryLabel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Please summarize your experience studying:"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/txtJournalNewSummary"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textCapSentences|textMultiLine"
        android:maxLines="6"
        android:minLines="3"
        android:singleLine="false"
        android:textSize="12sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtJournalSummaryLabel" />
</android.support.constraint.ConstraintLayout>

to the AlertDialog:

View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_journal_summary_prompt, null);
final EditText txtInput = view.findViewById("Some Default Text");
txtInput.setText(this.journalTitles.get(0));
builder.setView(view);

But the AlertDialog is still not showing spelling errors. Is this because the view is not attached to the parent Activity/Fragment? Any help would be greatly appreciated.


Answer:

Figured out a solution. For some reason, when directly inserting the EditText into the builder and then apply the textAutoCorrect flag for inputType, spell check would not work.

image showing autocorrect working

The solution was to create a layout file with the EditText (see modified question above), but make sure to enable the textAutoCorrect flag in the xml resource file, apply the inflated view to the AlertDialog builder, then watch it work.

I wish it would automatically auto-correct what was manually placed in their (previous value), but this works well enough for me. Leaving my solution for posterity.

Question:

I have implemented form in my dialog, and when positive button is clicked I create new object to ma database. I've created global variable for EditText's but still not work. Where I want get text value from them I always get empty string.

here is code:

EditText name, desc;

@Override
@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    view = inflater.inflate(R.layout.new_dialog, null);

    name = (EditText) view.findViewById(R.id.workout_name);
    desc = (EditText) view.findViewById(R.id.workout_description);


    builder.setView(inflater.inflate(R.layout.new_dialog, null)).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            MyDbHelper helper = new MyDbHelper (getActivity());
            MyObj w = new MyObj ();

            w.setName(name.getText().toString(););
            w.setDescription(desc.getText().toString());
            w.setLevel(1);

            long id =  helper.createWorkout(w);
            Toast.makeText(getActivity(), id+"", Toast.LENGTH_LONG).show();

            callback.onPositiveButtonClick();
        }
    }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            callback.onNegativeButtonClick();

        }
    });

    return builder.create();
}

Any ideas please?


Answer:

I stumbled upon the same issue. You can get the views inflated in the dialog using getDialog() provided by the onClick.

((EditText) getDialog().findViewById(R.id.your_editText_ID)).getText().toString()

Question:

In my project there is a MainActivity class with victory() method in it :

public void victory() {
        name = "";
        AlertDialog dialog = DialogScreen.getDialog(this, DialogScreen.IDD_MAPHIGHSCORE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        name = DialogScreen.nickname;
        Log.i("NICKNAME :", " " + name);
    }

where I call getDialog(Activity activity, int ID) method from DialogScreen class :

public class DialogScreen {

static String nickname = "DEF";
public static final int IDD_MAPHIGHSCORE = 1;
public static final int IDD_WORLDHIGHSCORE = 2;

public static AlertDialog getDialog(Activity activity, int ID) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    final EditText editText = new EditText(activity);
    int maxLength = 15;
    editText.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});
    switch(ID) {
        case IDD_MAPHIGHSCORE: {
            builder.setTitle(R.string.newHighScore);
            builder.setMessage(R.string.enterNickName);
            builder.setCancelable(true);
            builder.setView(editText).create();
            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String text = editText.getText().toString();
                    nickname  = text;
                    dialog.dismiss();
                }
            });
        }
    }
    return builder.create();
}

}

But in Log.i I can see just "NICKNAME : ". I also tried getters in DialogScreen class and setters in MainActivity class. But this doesn't help.

So the first question is how to make text from EditText available in MainActivity class?

And the second one is how can I know (from MainActivity class) if the button "OK" from dialog has benn pressed?


Answer:

I guess it is a timing problem Log.i is done before you click the positive button of your dialog. Add a DismissListener to your dialog within the MainActivity and move Log.i into that listener.

Question:

I've implemented an alert dialog containing one edit text for name but I need to store other info such a quantity location using the same alert dialog.

I tried to add another edit text by simply declaring another but this didn't populate the dialog with another edit text.

Does anyone now how you can add extra edit text object to an alert dialog?

This is how I've implemented an alert dialog for containing one edit text:

            AlertDialog.Builder alert = new AlertDialog.Builder(this);

            alert.setTitle("Generic Info");
            alert.setMessage("Ship Name");

            // Set an EditText view to get user input 
            final EditText input = new EditText(this);
            alert.setView(input);

            //need to add two more edit text fields for extra input.


            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
              Editable value = input.getText();
              // Do something with value!

              }
            });

            alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                // Canceled.
              }
            });

            alert.show();
            return true;

Answer:

Try this

Create res/layout/custom_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text 1"
        android:id="@+id/editText" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text 2"
        android:id="@+id/editText2" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text 3"
        android:id="@+id/editText3"
        android:layout_gravity="center_horizontal" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Text 4"
        android:id="@+id/editText4" />
</LinearLayout>

Then in your Activity that you want AlertDialog to show use:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
        LayoutInflater inflater = getActivity().getLayoutInflater();
        builder.setTitle("Custom view with 4 EditTexts");
        builder.setMessage("AlertDialog");
        builder.setView(R.layout.custom_view);
        //In case it gives you an error for setView(View) try
        builder.setView(inflater.inflate(R.layout.custom_view, null));
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
        return builder.create();

And this will give you the following result: