John Smith
John Smith

Reputation: 2738

android passing parameter from a class to another

I have below snippet code to pass a parameter from a class (activity) to another class. To do so, used sharedPreferences, but i try to get in my secondclass the value that was saved in main activity , i am getting java.lang.Nullpointer exception. What I am doing wrong here?

public class Secondclass extends Activity { 
//other functions....
private void get_file_name() {

        final  main m=new  main();
        String myvalue=m.set_paramater();
        //I want to access FOLDER_NAME here
         Log.e("TAG","the value "+myvalue);

}
}

public class main extends Activity{
String FOLDER_NAME;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         FOLDER_NAME="a_name";
      Save_file_name("APP_NAME",FOLDER_NAME);
}
private void Save_file_name(String key,String value){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();

        }

 public String set_paramater(){
         SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
         String strSaveddata = sharedPreferences.getString("APP_NAME", "");
         return strSaveddata;
    }
}

}

Here is the trace file:

 E/AndroidRuntime(10622): FATAL EXCEPTION: main
 E/AndroidRuntime(10622): java.lang.NullPointerException
E/AndroidRuntime(10622): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:120)
 E/AndroidRuntime(10622): at android.app.Activity.getLocalClassName(Activity.java:3488)
 E/AndroidRuntime(10622): at android.app.Activity.getPreferences(Activity.java:3522)

Upvotes: 0

Views: 418

Answers (4)

Asela
Asela

Reputation: 154

Not an answer to your problem but just some info. You can share data among activities of your application by extending the Android Application class.

Extend the Application class and create your own class.

package com.foo.bar;
import android.app.Application;
public class MyApplication extends Application {
    private boolean foo;
    @Override
    public void onCreate() {
        foo = false;
    }
    public void SetFoo(boolean fooValue) {
        foo = fooValue;
    }
    public boolean GetFoo() {
        return foo;
    }
}

Your manifest must set the application class.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.foo.bar"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="16"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:name=".MyApplication">
        <activity
            android:label="@string/app_name"
            android:name=".MyActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Your can access the application class instance within an activity like this.

MyApplication mApp = (MyApplication)getApplication();

Upvotes: 0

Mohsin Naeem
Mohsin Naeem

Reputation: 12642

final  main m=new  main();

It is wrong! as you are using

SharedPreferences sharedPreferences = gePreferences(MODE_PRIVATE);

which required Context. Which is null at the time when you call set_paramater()

Just make set_paramater() in Secondclass. It will solve your problem!

package com.example.test;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class main extends Activity {
    String FOLDER_NAME;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FOLDER_NAME = "a_name";
        Save_file_name("APP_NAME", FOLDER_NAME);
        Button nextButton=(Button)findViewById(R.id.next_button);
        nextButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                startActivity(new Intent(main.this,Secondclass.class));

            }
        });

    }

    private void Save_file_name(String key, String value) {
        SharedPreferences sharedPreferences = getSharedPreferences(
                "myPreffFile", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();

    }

}

and...

  package com.example.test;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Secondclass extends Activity {
    // other functions....
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button nextButton = (Button) findViewById(R.id.next_button);
        nextButton.setText("Show Value");
        nextButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                get_file_name();

            }
        });

    }

    private void get_file_name() {
        Toast.makeText(this, set_paramater(), Toast.LENGTH_SHORT).show();

    }

    public String set_paramater() {
        SharedPreferences sharedPreferences = getSharedPreferences(
                "myPreffFile", MODE_PRIVATE);

        String strSaveddata = sharedPreferences.getString("APP_NAME", "");
        return strSaveddata;
    }
}

NOTE: it is fully test code. I run this..if still error came then the fault is in other place.

Upvotes: 0

Grimmace
Grimmace

Reputation: 4041

It is bad practice to instantiate an Activity from another Activity, in your case with the line:

final  main m=new  main();

Android handles the creation of all your activities and you shouldn't have to do it yourself. If you do it this way the Activity will not have a valid Application Context. Without a valid Application context getPreferences(MODE_PRIVATE) will return null.

Also, it is probably better to use:

PreferenceManager.getDefaultSharedPreferences(this)

Using getPreferences(...) will make the preferences private to your Activity. Using getDefaultSharedPreferences(this) will make your preferences available to other activities instead of just the Activity that created it. This allows you to share your data across your two activities.

Upvotes: 1

Ponyets
Ponyets

Reputation: 336

Activity.getPreferences() retrieve a SharedPreferences object for accessing preferences that are private to this activity, which means in two activities you got different SharedPreferences.

You may use Context.getSharedPreferences() with same name to get same SharedPreferences

Upvotes: 0

Related Questions