1

I'm new to coding so while trying to make the an application which accepts values in one Layout "My Profile" and replaces the edittext fields in another layout "Booking form".

I.e. at My profile it will store Name, Email, Phone. So at Booking page it should fill in these values from sharedpreference.

I am able to store these values to shared preference but unable to display them. The code is as follows , have been at it for over 13hrs not able to get through the NPE at the very first section where it tried to setText.

My Activity File

package com.buses;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class DetailActivity extends FragmentActivity {

    //Variables for Storing Message & Button objects
    /*final EditText name= (EditText)findViewById(R.id.prof_uname);
    final EditText phone= (EditText)findViewById(R.id.prof_mob_num);
    final EditText email= (EditText)findViewById(R.id.prof_email);
    final EditText dob= (EditText)findViewById(R.id.prof_dob);

    final EditText bname= (EditText)findViewById(R.id.uname);
    final EditText bphone= (EditText)findViewById(R.id.mob_num);
    final EditText bemail= (EditText)findViewById(R.id.email);*/
    // EditText from_loc= null;
    // EditText to_loc= null;
    CheckBox today, tomorrow;
    TimePicker pickup;
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String Name = "nameKey";
    public static final String Phone = "phoneKey";
    public static final String Email = "emailKey";
    public static final String DOB = "dobKey";
    SharedPreferences sharedpreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cab_detail);
        // Show the Up button in the action bar.
        getActionBar().setDisplayHomeAsUpEnabled(true);
        // Profile Layout Display
        /*
         * name = (EditText)findViewById(R.id.prof_uname); phone =
         * (EditText)findViewById(R.id.prof_mob_num); email =
         * (EditText)findViewById(R.id.prof_email); dob =
         * (EditText)findViewById(R.id.prof_dob);
         */
        sharedpreferences = this.getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            // Value below prints on logcat output
            System.out.println(sharedpreferences.getString(Name, ""));
            // NPE error is shown as Caught at the line below
            ((EditText) findViewById(R.id.prof_uname))
                .setText(sharedpreferences.getString(Name, null));
        }
        if (sharedpreferences.contains(Phone)) {
            ((EditText) findViewById(R.id.prof_mob_num))
                .setText(sharedpreferences.getString(Phone, ""));
        }
        if (sharedpreferences.contains(Email)) {
            ((EditText) findViewById(R.id.prof_email))
                .setText(sharedpreferences.getString(Email, ""));
        }
        if (sharedpreferences.contains(DOB)) {
            ((EditText) findViewById(R.id.prof_dob)).setText(sharedpreferences
                .getString(DOB, ""));
        }
        // Book Layout
        /*
         * bname = (EditText)findViewById(R.id.uname); bphone =
         * (EditText)findViewById(R.id.mob_num); bemail =
         * (EditText)findViewById(R.id.email);
         */
        if (sharedpreferences.contains(Name)) {
            ((EditText) findViewById(R.id.uname)).setText(sharedpreferences
                .getString(Name, ""));
        }
        if (sharedpreferences.contains(Phone)) {
            ((EditText) findViewById(R.id.mob_num)).setText(sharedpreferences
                .getString(Phone, ""));
        }
        if (sharedpreferences.contains(Email)) {
            ((EditText) findViewById(R.id.email)).setText(sharedpreferences
                .getString(Email, ""));
        }
        // savedInstanceState is non-null when there is fragment state
        // saved from previous configurations of this activity
        // (e.g. when rotating the screen from portrait to landscape).
        // In this case, the fragment will automatically be re-added
        // to its container so we don't need to manually add it.
        // For more information, see the Fragments API guide at:
        //
        // http://developer.android.com/guide/components/fragments.html
        //
        if (savedInstanceState == null) {
            // Create the detail fragment and add it to the activity
            // using a fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(CabDetailFragment.ARG_ITEM_ID, getIntent()
                .getStringExtra(CabDetailFragment.ARG_ITEM_ID));
            CabDetailFragment fragment = new CabDetailFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                .add(R.id.cab_detail_container, fragment).commit();
        }
    }

    void onCreateContextMenu() {}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // This ID represents the Home or Up button. In the case of this
            // activity, the Up button is shown. Use NavUtils to allow users
            // to navigate up one level in the application structure. For
            // more details, see the Navigation pattern on Android Design:
            //
            // http://developer.android.com/design/patterns/navigation.html#up-vs-back
            //
            NavUtils.navigateUpTo(this, new Intent(this, ListActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // When Book Button is clicked
    public void send(View v) {
        new SendEmailAsyncTask().execute();
    }

    class SendEmailAsyncTask extends AsyncTask<Void, Void, Boolean> {

        // Email Code
        // if (BuildConfig.DEBUG) Log.v(SendEmailAsyncTask.class.getName(),
        // "SendEmailAsyncTask()");
        // email Code
        @Override
        protected Boolean doInBackground(Void... params) {
            if (BuildConfig.DEBUG)
                Log.v(SendEmailAsyncTask.class.getName(), "doInBackground()");
            try {
                m.send();
                return true;
            } catch (AuthenticationFailedException e) {
                Log.e(SendEmailAsyncTask.class.getName(), "Bad account details");
                e.printStackTrace();
                return false;
            } catch (MessagingException e) {
                Log.e(SendEmailAsyncTask.class.getName(), m.getTo(null)
                    + "failed");
                e.printStackTrace();
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    // Save Option use here
    public void save(View v) {
        new SaveEmailAsyncTask().execute();
    }

    class SaveEmailAsyncTask extends AsyncTask<Void, Void, Boolean> {

        // Email Code
        // if (BuildConfig.DEBUG) Log.v(SaveEmailAsyncTask.class.getName(),
        // "SaveEmailAsyncTask()");
        // email code
        // }
        @Override
        protected Boolean doInBackground(Void... params) {
            if (BuildConfig.DEBUG)
                Log.v(SaveEmailAsyncTask.class.getName(), "doInBackground()");
            try {
                m.send();
                return true;
            } catch (AuthenticationFailedException e) {
                Log.e(SaveEmailAsyncTask.class.getName(), "Bad account details");
                e.printStackTrace();
                return false;
            } catch (MessagingException e) {
                Log.e(SaveEmailAsyncTask.class.getName(), m.getTo(null)
                    + "failed");
                e.printStackTrace();
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }
}

Log.cat file

Note all layouts open perfectly when no values are present in sharedpreferences because "if (sharedpreferences.contains(Name))" is not called

E/Trace(2222): error opening trace file: No such file or directory (2)
D/dalvikvm(2222): GC_FOR_ALLOC freed 86K, 8% free 2670K/2880K, paused 73ms, total 77ms
I/dalvikvm-heap(2222): Grow heap (frag case) to 3.329MB for 635812-byte allocation
D/dalvikvm(2222): GC_FOR_ALLOC freed 3K, 7% free 3288K/3504K, paused 198ms, total 198ms
D/dalvikvm(2222): GC_CONCURRENT freed <1K, 7% free 3289K/3504K, paused 14ms+92ms, total 162ms
D/libEGL(2222): loaded /system/lib/egl/libEGL_emulation.so
D/(2222): HostConnection::get() New Host Connection established 0x2a147768, tid 2222
D/libEGL(2222): loaded /system/lib/egl/libGLESv1_CM_emulation.so
D/libEGL(2222): loaded /system/lib/egl/libGLESv2_emulation.so
W/EGL_emulation(2222): eglSurfaceAttrib not implemented
D/OpenGLRenderer(2222): Enabling debug mode 0
I/Choreographer(2222): Skipped 174 frames!  The application may be doing too much work on its main thread.
I/System.out(2222): Jasneet
D/AndroidRuntime(2222): Shutting down VM
W/dalvikvm(2222): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
E/AndroidRuntime(2222): FATAL EXCEPTION: main
E/AndroidRuntime(2222): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.primecabs/com.primecabs.CabDetailActivity}: java.lang.NullPointerException
E/AndroidRuntime(2222):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
E/AndroidRuntime(2222):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(2222):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(2222):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(2222):     at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(2222):     at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2222):     at android.app.ActivityThread.main(ActivityThread.java:5041)
E/AndroidRuntime(2222):     at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2222):     at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(2222):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(2222):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(2222):     at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(2222): Caused by: java.lang.NullPointerException
E/AndroidRuntime(2222):     at com.primecabs.CabDetailActivity.onCreate(CabDetailActivity.java:110)
E/AndroidRuntime(2222):     at android.app.Activity.performCreate(Activity.java:5104)
E/AndroidRuntime(2222):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
E/AndroidRuntime(2222):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
E/AndroidRuntime(2222):     ... 11 more
Community
  • 1
  • 1
Jskandhari
  • 31
  • 11
  • 1
    try this `((EditText)findViewById(R.id.prof_uname)).setText(sharedpreferences.getString(Name, "")` – M D Feb 13 '14 at 07:06
  • set this : your_edittext.setText(sharedpreferences.getString(Name, "")); – Waqar Ahmed Feb 13 '14 at 07:08
  • Check `R.id.prof_uname` exists or not – Viswanath Lekshmanan Feb 13 '14 at 07:08
  • Done all.. you will find your_edittext respective objects in comment blocks. Initially getString(Name,null) was set to getString(Name,"") only. Infact even if put the first line in if block the first line with SetText which comes outside the comment block will through NPE R.id.prof_uname exists.. – Jskandhari Feb 13 '14 at 07:15
  • 1
    where did you save data in shared prefrence? – Piyush Feb 13 '14 at 07:23
  • Piyush under class SaveEmailAsyncTask extends AsyncTask { public SaveEmailAsyncTask(){ String tovalue_uname = ((EditText)findViewById(R.id.prof_uname)).getText().toString(); String tovalue_mobnum = ((EditText)findViewById(R.id.prof_mob_num)).getText().toString(); //similarly for other ids editor.putString(Name, tovalue_uname); editor.putString(Phone, tovalue_mobnum); editor.putString(Email, tovalue_email); editor.putString(DOB, tovalue_dob); editor.apply(); ...... – Jskandhari Feb 13 '14 at 07:29
  • But i can't see here in your code. – Piyush Feb 13 '14 at 07:32
  • Use **editor.commit()** instead **editor.apply();** – Piyush Feb 13 '14 at 07:36
  • It is not published in the code above.. It is defined public void save (View v) – Jskandhari Feb 13 '14 at 07:36
  • I was using editor.commit() only until I read about the difference here [link](http://stackoverflow.com/questions/15335456/difference-between-commit-and-apply-in-android-sharedpreferences) – Jskandhari Feb 13 '14 at 07:39
  • Have you check that SharedPreference keyname and Mode is same when you have inserted? – Piyush Feb 13 '14 at 07:41
  • Keyname Yes , Mode ? you mean EditText forgive me, am a beginner – Jskandhari Feb 13 '14 at 07:46
  • Is it the same with all others ? If you comment the first section the others work ? – Mr_and_Mrs_D Feb 13 '14 at 13:08
  • Yes same with all others also, i.e. if I put the first if block in comments the second one will give the error at the line which is suppose to set values. – Jskandhari Feb 13 '14 at 16:14

3 Answers3

0
if (sharedpreferences.contains(Name))
          {
              System.out.println(sharedpreferences.getString(Name, "")); 
              ((EditText)findViewById(R.id.prof_uname)).setText(sharedpreferences.getString(Name, "")); <-------- NPE error is shown as Caught at this line

          }

The answer given by MD and wqrahd is right. But just to explain the concept the Syntax for retrieving preferences is sharedpreferences.getString("KEY", "DEFAULT VALUE") If the "KEY" is not present then it returns the "DEFAULT VALUE" else it returns the latest value saved in the preferences

Swapnil
  • 654
  • 7
  • 27
  • I have tested using the solution suggested by you, if you will notice the next example has "" instead of null, even the sysout has the "". – Jskandhari Feb 13 '14 at 07:17
  • added the Log Cat File – Jskandhari Feb 13 '14 at 09:01
  • @Jskandhari according to your loag cat error is at line 110 at com.primecabs.CabDetailActivity.onCreate(CabDetailActivity.java:110) sources code you have provided shows a code which is commented at line 110 please provide proper sources – Swapnil Feb 13 '14 at 09:29
  • Where I have pointed out< ((EditText)findViewById(R.id.prof_uname)).setText(sharedpreferences.getString(Name, null)); <-------- NPE error is shown as Caught > in the code above is Line no. 110 #while posting herein the spaces between import blocks were removed. – Jskandhari Feb 13 '14 at 09:50
0

Since sharedpreferences.getString(Name, null) is not null the only other thing that can be null is (EditText)findViewById(R.id.prof_uname). Print it:

EditText et = (EditText)findViewById(R.id.prof_uname);
Log.w("DetailActivity", "EditText: " + et); // null I bet

Reason : you are in a FragmentActivity. Apparently these elements belong to fragments not loaded yet ? Not sure, let me know if I am right and we'll work it out

Also I do not see R import


Important: your formatting is very bad, and what you gave did not even compile (you had some ifs in the middle of the class (?!)). I edited it but next time you will get a -1. Such bad formatting leads to bugs and makes debugging hard. And nobody will want to read your code or take you seriously, trust me.

Try to have no horizontal scrollbar and the less code the better - try to post only the important parts. Avoid blank lines. Logcat times are seldom useful.

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
  • Hi, Thanks for being honest. Will look into your findings and let you know. – Jskandhari Feb 13 '14 at 16:14
  • @Jskandhari: you seem serious enough otherwise I would just -1 ;) Tell me if the EditText is null – Mr_and_Mrs_D Feb 13 '14 at 16:17
  • YES ! EditText is Null :/ while System.out.println(sharedpreferences.getString(Name, "")); gives the name. As far as Import Android.R is concerned it is not present and on importing it it throws a warning. – Jskandhari Feb 13 '14 at 16:26
  • @Jskandhari: There is no `R.id.prof_uname` in `R.layout.activity_cab_detail` – Mr_and_Mrs_D Feb 14 '14 at 03:16
  • After the null error was identified, have made these changes in the code `sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); Context context=this.getApplicationContext(); System.out.println(context); LayoutInflater inflater = LayoutInflater.from(context); View v = inflater.inflate(R.layout.fragment_cab_detail_book, null);` and then `bname = (TextView)v.findViewById(R.id.uname); Log.w("DetailActivity", "TextView Frab: " + bname);` everything shows values in log but `bname.setText(sharedpreferences.getString(Name, ""));` isn't should I change XML – Jskandhari Feb 14 '14 at 05:19
  • above since introducing view id.prof_uname is in different view i.e. where I ask the user to enter profile details `fragment_cab_prof` hence you will find bname having `id.uname` – Jskandhari Feb 14 '14 at 05:23
0

Resolved, turns out that coupled with multiple problems, with inputs from @Mr_and_Mrs_D

1) The object was having null value

EditText et = (EditText)findViewById(R.id.prof_uname);
Log.w("DetailActivity", "EditText: " + et); 

2) Rectified it by providing a view (while I was in CabDetailActivity

EditText et = (EditText)v.findViewById(R.id.prof_uname);
Log.w("DetailActivity", "EditText: " + et);

While everything was having the values, but the SetText was not reflecting when the application was executed. Later I found out the the view it was inflating was not the same as the one which was being used.

Therefore after few look arounds', and re-analysing the process flow. I came to conclusion that since my view was being inflated at Fragment i.e. CabDetailFragment ; which on was not able to read getSharePreferences, circumventing that error took time and eventually my CabDetailFragment is

package com.primecabs;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import com.primecabs.home.Content;

/**
 * A fragment representing a single Cab detail screen. This fragment is either
 * contained in a {@link CabListActivity} in two-pane mode (on tablets) or a
 * {@link CabDetailActivity} on handsets.
 */
public class CabDetailFragment extends Fragment {

    /**
     * The fragment argument representing the item ID that this fragment
     * represents.
     */
    public static final String ARG_ITEM_ID = "item_id";
    // Variables for Storing Message & Button objects
    TextView name, from_loc, to_loc, phone, email, dob;
    CheckBox today, tomorrow;
    TimePicker pickup;
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String Name = "nameKey";
    public static final String Phone = "phoneKey";
    public static final String Email = "emailKey";
    public static final String DOB = "dobKey";
    SharedPreferences sharedpreferences;
    /**
     * The dummy content this fragment is presenting.
     */
    private Content.Item mItem;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public CabDetailFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments().containsKey(ARG_ITEM_ID)) {
            // Load the content specified by the fragment
            // arguments. In a real-world scenario, use a Loader
            // to load content from a content provider.
            mItem = Content.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = null;
        sharedpreferences = this.getActivity().getSharedPreferences(
            MyPREFERENCES, Context.MODE_PRIVATE);
        if (mItem.id == "1") {
            rootView = inflater.inflate(R.layout.fragment_cab_detail_book,
                container, false);
            TextView bname = (TextView) rootView.findViewById(R.id.uname);
            TextView bphone = (TextView) rootView.findViewById(R.id.mob_num);
            TextView bemail = (TextView) rootView.findViewById(R.id.email);
            if (sharedpreferences.contains(Name)) {
                bname.setText(sharedpreferences.getString(Name, ""));
            }
            if (sharedpreferences.contains(Phone)) {
                bphone.setText(sharedpreferences.getString(Phone, ""));
            }
            if (sharedpreferences.contains(Email)) {
                bemail.setText(sharedpreferences.getString(Email, ""));
            }
        }
        if (mItem.id == "3") {
            rootView = inflater.inflate(R.layout.fragment_user_profile,
                container, false);
            // Profile Layout Display
            name = (TextView) rootView.findViewById(R.id.prof_uname);
            phone = (TextView) rootView.findViewById(R.id.prof_mob_num);
            email = (TextView) rootView.findViewById(R.id.prof_email);
            dob = (TextView) rootView.findViewById(R.id.prof_dob);
            if (sharedpreferences.contains(Name) == true) {
                name.setText(sharedpreferences.getString(Name, ""));
            }
            if (sharedpreferences.contains(Phone)) {
                (phone).setText(sharedpreferences.getString(Phone, ""));
            }
            if (sharedpreferences.contains(Email)) {
                (email).setText(sharedpreferences.getString(Email, ""));
            }
            if (sharedpreferences.contains(DOB)) {
                (dob).setText(sharedpreferences.getString(DOB, ""));
            }
        }
        if (mItem.id == "2") {
            rootView = inflater.inflate(R.layout.fragment_cab_detail_confirm,
                container, false);
            // Show the content as text in a TextView.
            // if (mItem != null) {
            // ((TextView) rootView.findViewById(R.id.cab_detail))
            // .setText(mItem.content);
        }
        return rootView;
    }
}

Thank you all

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
Jskandhari
  • 31
  • 11
  • If you solved your problem you should mark this answer as the solution. – Megacan Feb 14 '14 at 09:50
  • 1
    @Megacan Sure will do. – Jskandhari Feb 15 '14 at 02:27
  • Would be better style if you did `if (sharedpreferences.contains(Name)) {TextView bname = (TextView) rootView.findViewById(R.id.uname); bname.setText(sharedpreferences.getString(Name, "")); }` - that is define the variables where you use them. Also you should use a switch for integers instead of ifs `switch(mItem.id)` – Mr_and_Mrs_D Feb 15 '14 at 02:44
  • @Mr_and_Mrs_D aaah. Yes ! ; one small help, though off topic how do I set max date 45 Days from current day in date picker. – Jskandhari Feb 15 '14 at 11:48