Throws NullPointerException while retrieving data from SharedPreferences - java

First of all, sorry for my bad English !
I have an Activity ( say MainActivity.java ) and a class ( say AsynkTaskClass.java ).
AsynkTaskClass.java contains an AsynkTask. I am calling this AsynkTask from MainActivity.java.
Before calling this AsynkTask, I am saving some data using SharedPreferences.
From the onPostExecute function of AsynkTask, I am calling a normal function ( say displaySharedData() )which defined in MainActivity.java. There I am trying to retrieve the data I stored using SharedPreferences. Then It shows a NullPointerException. But I can access the Shared data from anywhere other than this displaySharedData() function.
This is the Log Output:
W/dalvikvm(3896): threadid=1: thread exiting with uncaught exception
E/AndroidRuntime(3896): FATAL EXCEPTION: main
E/AndroidRuntime(3896): java.lang.NullPointerExceptionE/AndroidRuntime(3896): at com.samApp.project.samApp.ui.MainActivity.displaySharedData(MainActivity.java:52)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:264)
E/AndroidRuntime(3896): at com.samApp.project.samApp.s3.AsynkTaskClass$UploadImage.onPostExecute(AsynkTaskClass.java:1)
E/AndroidRuntime(3896): at android.os.AsyncTask.finish(AsyncTask.java:417)
E/AndroidRuntime(3896): at android.os.AsyncTask.access$300(AsyncTask.java:127)
E/AndroidRuntime(3896): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
E/AndroidRuntime(3896): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(3896): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime(3896): at android.app.ActivityThread.main(ActivityThread.java:3683)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(3896): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime(3896): at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
public class MainActivity extends Activity implements TextView.OnEditorActionListener {
public SharedPreferences myData;
public String mySharedData="com.samApp.project.samApp.ui";
public SharedPreferences.Editor editor;
protected void onCreate(Bundle savedBundle) {
super.onCreate(savedBundle);
myData = PreferenceManager.getDefaultSharedPreferences(this);
editor = myData.edit();
editor.commit();
attachfileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PHOTO_SELECTED);
}
});
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case PHOTO_SELECTED:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Log.d("URIsssss", String.valueOf(selectedImage));
AsynkTaskClass obj = new AsynkTaskClass ();
AsynkTaskClass.s3context=this;
obj.new UploadImage().execute(selectedImage);
}
}
}
}
protected void onResume() {
super.onResume();
editor.putString("name", "MeSSi");
editor.commit();
}
public void displaySharedData()
{
Log.d("SharedData",myData.getString("name","")); // line No : 52
}
}
AsynkTaskClass.java
public class AsynkTaskClass {
MainActivity mainActvtyObj = new MainActivity();
public static Context s3context;
protected void onPostExecute(S3TaskResult result) {
if(dialog != null)
dialog.dismiss();
if (result.getErrorMessage() != null) {
displayErrorAlert(
AsynkTaskClass.s3context.getString(R.string.upload_failure_title),
result.getErrorMessage());
}
mainActvtyObj.displaySharedData();
}
}
So, Any Help ??

MainActivity mainActvtyObj = new MainActivity();
Never instantiate activity classes with new.
For example, their lifecycle callbacks such as onCreate() are not run. You init your myData in onCreate() and it remains null in this activity instance.
Instead, pass a reference to your activity object to the async task as a parameter.

Finally I got a working solution.
I don't know whether It is perfect! But it works well..
I replaced the displaySharedData() calling statement i.e. mainActvtyObj.displaySharedData(); to the following :
((MainActivity) s3context).displaySharedData();
Now It Works Great !!

Related

How to use interface between two activities [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am passing my data from one activity to another activity via intent using a bundle.now this bundle is received by another activity here i am gonna display the values i passed.now when the a button is clicked it is suppose to fire a interface which has a function .There it is showing a null point error.
MainActivity.class
public class MainActivity extends AppCompatActivity implements WILO.Communicator {
int Tap=0,loss=9;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CountDowntimer();
}
public void CountDowntimer()
{
new CountDownTimer(3000, 1000) {
#Override
public void onTick(long millisUntilFinished)
{
Tap+=1;
loss-=2;
}
#Override
public void onFinish()
{
Bundle arg=new Bundle();
arg.putInt("Tap",Tap);
arg.putInt("Loss",loss);
Intent i=new Intent(getBaseContext(),WILO.class);
i.putExtras(arg);
startActivity(i);
}
}.start();
}
#Override
public void Restart()
{
CountDowntimer();
}
}
WILO.class
public class WILO extends Activity {
Communicator communicator;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wilo);
Bundle arg=getIntent().getExtras();
Button Restart;
TextView Tap,Loss;
Restart= (Button) findViewById(R.id.Restart);
Tap= (TextView) findViewById(R.id.Tap);
Loss= (TextView) findViewById(R.id.Loss);
Loss.setText(String.valueOf(arg.getInt("Loss")));
Tap.setText(String.valueOf(arg.getInt("Tap")));
Restart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
communicator.Restart();
finish();
}
});
}
interface Communicator
{
public void Restart();
}
}
Error
FATAL EXCEPTION: main
Process: com.matrix.storm.question, PID: 27805
java.lang.NullPointerException
at com.matrix.storm.question.WILO$1.onClick(WILO.java:34)
at android.view.View.performClick(View.java:4452)
at android.view.View$PerformClick.run(View.java:18451)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5421)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:979)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
at dalvik.system.NativeStart.main(Native Method)
How to use interface between two activities
You can not connect two activities using interfaces. If you want to send receive data between two activities, you can use the help of intent arguments and ActivityResult method.
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 2);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}

Keep getting a NullPointerException for MediaPlayer [duplicate]

This question already exists:
MediaPlayer NullPointerException in local method [duplicate]
Closed 7 years ago.
There is an annoying bug in my code somewhere and I can't sleep because of it!
I kind of get why I might be getting it - I think something to do with onCreate method I think.
This is what I have:
public class PredefinedUserPlayer extends Activity {
MediaPlayer mediaPlayer;
String names;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.userdefplayer);
names = "http://X.X.X.X/musikz/musikz01.mp3";
mediaPlayer = new MediaPlayer();
}
public void playSelectedFile() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(PredefinedUserPlayer.this, Uri.parse(names));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
}
The playSelectedFile() method is being called in another class and here is that bit of code here:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PredefinedUserPlayer predefinedUserPlayer = new PredefinedUserPlayer()
predefinedUserPlayer.playSelectedFile();
}
});
I can't really have the MediaPlayer stuff in the above class which is why I have had to instantiate the PredefinedUserPlayer class. This is the actual stack trace (maybe someone can help me debug and fix this annoying bug):
java.lang.NullPointerException
at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:99)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:882)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:859)
at lukasz.musik.PredefinedUserPlayer.playSelectedFile(PredefinedUserPlayer.java:86)
at lukasz.musik.CustomMusicAdapter$ViewHolder$1.onClick(CustomMusicAdapter.java:85)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
You can't new activity by hand like this:
PredefinedUserPlayer predefinedUserPlayer = new PredefinedUserPlayer()
You can use Broadcast to achieve it,Like this:
**First,Register a BroadcastReceiver in PredefinedUserPlayer Activity:
public static String ACTION_PLAY = "ACTION_PLAY_FILE";
private final BroadcastReceiver mPlayFileReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ACTION_PLAY.equals(action)) {
playSelectedFile();
}
}
};
IntentFilter intentFilter = new IntentFilter(ACTION_PLAY);
LocalBroadcastManager.getInstance(this).registerReceiver(mPlayFileReceiver,intentFilter);
Second,Send Broadcast with action ACTION_PLAY to inform the receiver to be invoked:
LocalBroadcastReceiver.getInstance(this).sendBroadcastSync(new Intent(PredefinedUserPlayer.ACTION_PLAY));

Google Glass Take Picture Intent

I'm trying to take a picture with a Google Glass App. Therefore I'm using a SurfaceView which shows the camera preview in the background. The photo is taken with an intent.
The problem is that the onActivityResult method belonging to the intent is never called. I've read that this problem is a bug on Google Glass but should be closed with the newer versions of Google Glass.
onCreate Method:
private CameraSurfaceView cameraView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initiate CameraView
cameraView = new CameraSurfaceView(this);
// Set the view
this.setContentView(cameraView);
}
Intent Calling:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_camera:
take picture
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent != null)
{
Toast.makeText(getApplicationContext(), "Taking Picture",
Toast.LENGTH_SHORT).show();
startActivityForResult(intent, TAKE_PICTURE_REQUEST);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This all works fine. The user sees the camera preview and when the intent is called a picture will be taken and stored. After that the user sees a prompt "Tap to Accept". After tapping the app ends but the onActivityResult method is never called.
onActivityResult Method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.i("Camera", "Hello from onActivityResult");
// Handle photos
if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK)
{
String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);
processPictureWhenReady(picturePath);
}
super.onActivityResult(requestCode, resultCode, data);
}
Releasing the camera:
#Override
protected void onResume() {
super.onResume();
// Do not hold the camera during onResume
if (cameraView != null) {
cameraView.releaseCamera();
}
}
#Override
protected void onPause() {
super.onPause();
// Do not hold the camera during onPause
if (cameraView != null) {
cameraView.releaseCamera();
}
}
Logcat Log for my application with Log Level "Info"
05-03 08:45:02.328 29785-29785/com.dhbw.charadect I/dalvikvm-heap﹕ Grow heap (frag case) to 5.955MB for 921616-byte allocation
05-03 08:45:03.305 29785-29785/com.dhbw.charadect I/Choreographer﹕ Skipped 51 frames! The application may be doing too much work on its main thread.
05-03 08:45:03.313 29785-29785/com.dhbw.charadect W/Resources﹕ Converting to boolean: TypedValue{t=0x3/d=0x210 "res/anim/decelerate_interpolator.xml" a=1 r=0x10a0006}
05-03 08:45:04.008 29785-29785/com.dhbw.charadect I/Choreographer﹕ Skipped 30 frames! The application may be doing too much work on its main thread.
05-03 08:45:14.414 29785-29797/com.dhbw.charadect I/Camera﹕ Received CAMERA_MSG_RELEASE
Thanks in advance for all answers and comments!

How to Call BroadcastReceiver from Activity via Interface in Android

I need to set Listener for Activity Class from BroadcastReceiver Class But here in my below code I am getting null pointer exception in BroadcastReceiver class..
Here is my code
Activity Class
public class MainActivity extends ActionBarActivity implements TheListener
{
Message_Incomingsms jv_class_Message_Incomingsms;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jv_class_Message_Incomingsms = new Message_Incomingsms();
jv_class_Message_Incomingsms.setSmsReceivedistener(this);
}
#Override
public void onSmsReceived(String jv_string_address, String jv_string_MessageText)
{
Toast.makeText(getApplicationContext(),"This Message is from Lister number is "+jv_string_address +" Message is "+jv_string_MessageText,Toast.LENGTH_LONG).show();
//Doing some Activity.....
}
}
Interface
public void setSmsReceivedistener(Context context)
{
this.jv_TheListener = (TheListener)context;
}
BroadCastReceiver Class
public class Message_Incomingsms extends BroadcastReceiver
{
String jv_string_phone_received_Number;
String jv_string_phone_received_messageText;
public TheListener jv_TheListener;
#Override
public void onReceive(Context context, Intent intent)
{
Log.d("Received","OnReceive method is called");
jv_smsmanager_incoming_sms = SmsManager.getDefault();
jv_bundle_incoming_sms = intent.getExtras();
if(jv_bundle_incoming_sms!=null)
{
Object[] jv_pdusObj_incoming_sms = (Object[]) jv_bundle_incoming_sms.get("pdus");
for(int jv_i = 0; jv_i < jv_pdusObj_incoming_sms.length ;jv_i++)
{
SmsMessage jv_current_message = SmsMessage.createFromPdu((byte[]) jv_pdusObj_incoming_sms[jv_i]);
jv_string_phone_received_Number =jv_current_message.getDisplayOriginatingAddress();
jv_string_phone_received_messageText = jv_current_message.getDisplayMessageBody();
}
//Here Below line is problem for me Always am getting null value for (jv_TheListener)
//Why value is not getting assigned for this (jv_TheListener) always
jv_TheListener.onSmsReceived(jv_string_phone_received_Number,jv_string_phone_received_messageText);
}
}
public void setSmsReceivedistener(Context context)
{
this.jv_TheListener = (TheListener)context;
}
}
Please provide me solution for above BroadCastClass code where am always getting null exception for (jv_TheListener)
log Cat ( I removed some lines for in code for not to confuse.. so dont refer linenumber based on below error)
04-18 23:45:12.268 4064-4064/com.talkeasy.elavarasans.creativeactionbar E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start receiver com.talkeasy.elavarasans.creativeactionbar.Message_Incomingsms: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2153)
at android.app.ActivityThread.access$1500(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4448)
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:823)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.talkeasy.elavarasans.creativeactionbar.Message_Incomingsms.onReceive(Message_Incomingsms.java:53)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2146)
            at android.app.ActivityThread.access$1500(ActivityThread.java:127)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208)
Thanks in Advance...

How to access data in the previous activity?

Using StartActivity i reached SecondActivity from FirstActivity..Now i want to access object declared in the previous activity.
Is there any obvious mechanisms that i am missing.I cant use Parceable on the object(DropboxAPI) i want to pass since i do not have its source(i can't make it parceable).
Can i pass FirstActivity.this since i can make it Parceable using an intent?or like
Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("MyClass",FirstActivity.this);
startActivity (intent);
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import android.app.Application;
import android.hardware.Camera.Parameters;
import android.os.Parcel;
import android.os.Parcelable;
public class temp extends Application {
DropboxAPI<AndroidAuthSession> mApi;
public void onCreate() {
super.onCreate();
}
temp(DropboxAPI<AndroidAuthSession> Api)
{
mApi=Api;
}
public DropboxAPI<AndroidAuthSession> getName() {
return mApi;
}
public void setName(DropboxAPI<AndroidAuthSession> dropboxclient) {
this.mApi = dropboxclient;
}
}
Code in first class:
t = (temp)getApplication();
t.setName(mApi);
//basket.putParcelable("key", MCActivity.this);
Intent intent=new Intent(MCActivity.this,DownActivity.class);
//intent.putExtra("MyClass",t);
startActivity (intent);
Code in Second class:
public void onCreate(Bundle bun) {
// TODO Auto-generated method stub
super.onCreate(bun);
setContentView(R.layout.download);
mImage = (ImageView)findViewById(R.id.image_view);
//Bundle gotit=getIntent().getExtras();
t = (temp)getApplication();
int i=2;
i=5;
dApi=t.getName();
}
Logcat:
06-28 02:24:31.979: I/System.out(729): debugger has settled (1308)
06-28 02:25:08.387: D/AndroidRuntime(729): Shutting down VM
06-28 02:25:08.387: W/dalvikvm(729): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-28 02:25:08.705: E/AndroidRuntime(729): FATAL EXCEPTION: main
06-28 02:25:08.705: E/AndroidRuntime(729): java.lang.ClassCastException: android.app.Application
06-28 02:25:08.705: E/AndroidRuntime(729): at cloud.mobile.MCActivity$3.onClick(MCActivity.java:164)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.view.View.performClick(View.java:2408)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.view.View$PerformClick.run(View.java:8816)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Handler.handleCallback(Handler.java:587)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Handler.dispatchMessage(Handler.java:92)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.os.Looper.loop(Looper.java:123)
06-28 02:25:08.705: E/AndroidRuntime(729): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-28 02:25:08.705: E/AndroidRuntime(729): at java.lang.reflect.Method.invokeNative(Native Method)
06-28 02:25:08.705: E/AndroidRuntime(729): at java.lang.reflect.Method.invoke(Method.java:521)
06-28 02:25:08.705: E/AndroidRuntime(729): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-28 02:25:08.705: E/AndroidRuntime(729): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-28 02:25:08.705: E/AndroidRuntime(729): at dalvik.system.NativeStart.main(Native Method)
try using Application class:
public class MyApplication extends Application {
//Variable we want to share to All Activities in Application
private DropboxClient dropboxclient;
#Override
public void onCreate() {
super.onCreate();
}
//Getter Method
public DropboxClient getName() {
return dropboxclient;
}
//Setter Method
public void setName(DropboxClient dropboxclient) {
this.dropboxclient = dropboxclient;
}
}
In MyFirstActivity Activity:
private MyApplication app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app = (MyApplication)getApplication(); //Get Application
app.setName(dropboxclient);
Intent intent = new Intent();
intent.setClass(this, MySecondActivity.class);
startActivity(intent);
In MySecondActivity Activity:
private MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (MyApplication)getApplication(); //Get Application
DropboxClient dropboxclient=app.getName();//Access global value
do the following,
start the activity with startActivityForResult()
startActivityForResult(0, MyActivity.class);
before your started activity finished, in the started activity, create an intent, and put whatever data you want to pass back as extras in the intent. now call setResult(..., intent);
Intent resultIntent = new Intent();
resultIntent.putExtra("myKey", myVal);
setResult(0, resultIntent);
in your starting activity, implement onActivityResult(), and handle the result of the started activity. you will be passed an Intent, which is the intent where you added extras in the started activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //TODO handle here. 
}
Extend Application class and declare and initialize your cross activity objects in that class and write getters for those objects.
now using following code in an activty, you can access those Objects.
getApplication().getMyObject().doSomeAction();
remember, you will have to modifiy your androidManifest.xml to tell android about your extended application class.
Solution:
Using StartActivityforResult there data moveback to Second Activity to First Activity
One Example there data move to second Activity to first Activity-
http://micropilot.tistory.com/1577

Categories