Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9249783
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T10:17:05+00:00 2026-06-18T10:17:05+00:00

In my main class i’ve a button to call a class which shows a

  • 0

In my main class i’ve a button to call a class which shows a dialog box with an edittext. My problem is this – Main activity is not getting edittext value at the first run, if i run it for a second time, i get the old edittext value.

It seems the main activity class executes the full block of code and returns a previous value which is stored in the class, i’ve tried many methods including shared preference.

MainActivity.java

public class MainActivity extends Activity {
    EditText comment_et,input_et;
    Spinner spinner;
    Button addbutton,reportbut;
    String input_string,date,time,comment,item;
    TextView date_tv,time_tv;
    String temp[];
    Datas datatemp;
    String savedinput;

    ArrayList<String> list = new ArrayList<String>();


    ArrayAdapter<String> adapter;
    DatabaseHandler db = new DatabaseHandler(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) 
{

        SharedPreferences prefs = getSharedPreferences("myprefs", 0);
        savedinput=  prefs.getString("KEY_SAVEDINPUT","");

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

        spinner = (Spinner)findViewById(R.id.spin1);
        input_et = (EditText)findViewById(R.id.input_et);
        addbutton = (Button)findViewById(R.id.addbutton);
        reportbut = (Button)findViewById(R.id.report);

        comment_et = (EditText)findViewById(R.id.comment_et);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
        date_tv = (TextView)findViewById(R.id.date_tv);
        time_tv = (TextView)findViewById(R.id.time_tv);

        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        int mHour = c.get(Calendar.HOUR_OF_DAY);
        int mMinute = c.get(Calendar.MINUTE);

        date = ""+mDay+"/"+mMonth+1+"/"+mYear;
        time = ""+mHour+":"+mMinute;
        date_tv.setText(date);
        time_tv.setText(time);

        int max_id = db.getDatasCount();

        for(int i = 1; i<max_id+1 ;i++)
         {          

        datatemp = db.getItemOnly(i);
        String s = datatemp._item.toString();
        list.add("   "+ s);
         }


        addbutton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                AlertDialogManager alert = new AlertDialogManager();

                alert.showAlertDialog(MainActivity.this, "Enter Item",
                        "Please enter the spinner item",
                        true);
                System.out.println("main : " +savedinput);

            }   

        });



            reportbut.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent i = new Intent(getApplicationContext(), ListviewActivity.class);
                    startActivity(i);

                }

            });


        spinner.setAdapter(adapter);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                item = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {


            }
        });

        Button submit = (Button)findViewById(R.id.save);
        submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) 
            {

                 comment  = comment_et.getText().toString();

                    System.out.println("comment:"+comment);

                /**
                 * CRUD Operations
                 * */
                // Inserting Contacts
                Log.d("Insert: ", "Inserting ..");
                db.addData(new Datas(item, comment, date, time));
                Toast.makeText(getApplicationContext(), "Data Submitted Successfully",
                Toast.LENGTH_LONG).show();
                // Reading all contacts
                Log.d("Reading: ", "Reading all contacts..");
                List<Datas> datas = db.getAllDatas();       

                for (Datas d : datas) {
                    String log = "Id: "+d.getID()+" ,Item: " + d.getItem() + " ,Comment: " + d.getComment() + " ,Date: " + d.getDate() + ",Comment: " + d.getTime();
                        // Writing Contacts to log
                Log.d("Item: ", log);
                }
            }
        });
}

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

AlertDialogManager.java

public class AlertDialogManager {
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *               - pass null if you don't want icon
     * */
    String savedinput;
    public void showAlertDialog(final Context context, String title, String message,
            Boolean status) 
    {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        //setting input
         final EditText input = new EditText(context);
         alertDialog.setView(input);

         // saving input to a string
         savedinput = input.getText().toString();
         System.out.println(savedinput);

        if(status != null)
            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                savedinput = input.getText().toString();

                SharedPreferences prefs = context.getSharedPreferences("myprefs", 0);
                SharedPreferences.Editor editor =prefs.edit();
                editor.putString("KEY_SAVEDINPUT", savedinput);
                editor.commit();                
                System.out.println("from class "+savedinput);
            }
        });



        // Showing Alert Message
        alertDialog.show();

    }

    String getItem()
    {
        return savedinput;
    }
}

and here is my logcat, just for further clarification

02-01 13:48:43.372: I/System.out(897): main : firstexecute
02-01 13:48:46.942: W/KeyCharacterMap(897): No keyboard for id 0
02-01 13:48:46.942: W/KeyCharacterMap(897): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-01 13:48:49.532: I/System.out(897): from class secondexecute
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T10:17:07+00:00Added an answer on June 18, 2026 at 10:17 am

    You have several issues here.

    1. You shouldn’t read savedValue in onCreate, you should do it only when you actually use it. See @ρяσѕρєяK answer.
    2. alert.showAlertDialog is non blocking. So after dialog is shown line System.out.println("main : " + savedInput); is executed. It doesn’t wait for your input. So you should call some other action beside saving to shared preferences on dialog’s ok buttonn. This action should invoke logic that should happen after user entered some text in the dialog.

    Update

    public void showAlertDialog(final Context context, String title, String message,
                                Boolean status, final Spinner spinner) 
    {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    
        // Setting Dialog Title
        alertDialog.setTitle(title);
    
        // Setting Dialog Message
        alertDialog.setMessage(message);
    
        //setting input
         final EditText input = new EditText(context);
         alertDialog.setView(input);
    
         // saving input to a string
         savedinput = input.getText().toString();
         System.out.println(savedinput);
    
        if(status != null)
            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
    
        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                savedinput = input.getText().toString();
                // do whatever you want with spinner and savedInput here.
            }
        });
    
        // Showing Alert Message
        alertDialog.show();
     }
    

    onClick to show dialog:

    alert.showAlertDialog(MainActivity.this, "Enter Item",
         "Please enter the spinner item",
         true, (Spinner) findViewById(R.id.spin1));
    

    Update 2
    Apparently you need to add new item to your spinner adapter. For this you can create list of all items and pass this list along with adapter to dialog. When user enters string and press OK button onClick method adds this string to the list and call notifyDataSetChanged to update UI:

    Add this in MainActivity:

    List<String> spinnerItems;
    

    In onCreate:

    spinnerItems = new ArrayList<String>();
    adapter = enw ArrayAdapter<String>(this, 0, spinnerItems);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    

    Pass spinnerItems and adapter to showAlertDialog:

    alert.showAlertDialog(MainActivity.this, "Enter Item",
         "Please enter the spinner item",
         true, spinnerItems, adapter);
    

    And finally add text to list and notify adapter:

    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            savedinput = input.getText().toString();
            spinnerItems.add(savedInput);
            adapter.notifyDataSetChanged();
        }
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a main class which extends Activity which should spawn a ListActivity and
this is my Main class which belongs to the server application! but it is
I have a main class which spawns a thread, let's call them MainClass and
I have a main class in which Im trying to call on a function
My main class look like this: public class Soundboard extends Activity { SharedPreferences preferences;
I have added my main class, from which I call buttons class, and that's
I have this class inside my main class to put a close button on
I have class main extends jframe , it has a button that calls /shows
I have made a main Dialog class on which I send the layout ID
I have my main class from which i call my sub class. My sub

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.