androidsharedpreferencesandroid-sharedpreferences

Set string IP address using sharedpreferences into database connection class


This is my connection class what i really want is how do i get the data in SharedPreference and set it into my String IPadd.

 public class ConnectionClass  {



    String IPadd ="192.168.254.117";


    String classs = "com.mysql.jdbc.Driver";

    String url = "jdbc:mysql://"+IPadd+"/dblight";
    String un = "light";
    String password = "12345";


    @SuppressLint("NewApi")
    public Connection CONN() {


        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        try {

            Class.forName(classs);

            conn = DriverManager.getConnection(url, un, password);


            conn = DriverManager.getConnection(ConnURL);
        } catch (SQLException se) {
            Log.e("ERRO", se.getMessage());
        } catch (ClassNotFoundException e) {
            Log.e("ERRO", e.getMessage());
        } catch (Exception e) {
            Log.e("ERRO", e.getMessage());
        }
        return conn;
    }

}

My SharedPreference code to set the data

   try {
                         String strIP = ip.getText().toString();
                         SharedPreferences sharedPref = getSharedPreferences(Filename, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
                         editor.putString("name", strIP);
                         editor.commit();
                         Toast.makeText(getBaseContext(), "IP Saved Successfully", Toast.LENGTH_LONG).show();
                            }
                        catch (Exception ex)
                            {

                            }

Solution

  • 1)Add an Application class

    public class MyApplication extends Application {
    
    private static final String TAG = MyApplication.class.getSimpleName();
    
    private static MyApplication sInstance;
    
    @Nullable
    public static Context getAppContext() {
        return sInstance;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() called");
        sInstance = this;
     }
    }
    

    2) Add the android:name line to your Manifest application tag

    <application
        android:name="your.package.name.MyApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
    

    3) Inside your ConnectionClass class do this

    IPadd = MyApplication.getAppContext().getSharedPreferences(Filename,Context.MODE_PRIVATE).getString("name","defaultValue");