MediaPlayer with Internal Files - java

I'm trying to select an audio file from internal storage, which I then create a media player from.
public void openPressed(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
MediaPlayer player = MediaPlayer.create(this, data.getData());
player.start();
}
}
All of this is in my main activity, but after selecting a file, the app crashes.
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/audio/media/29 }} to activity {com.malik.mixtape/com.malik.mixtape.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.malik.mixtape.MainActivity.onActivityResult(MainActivity.java:65)
at android.app.Activity.dispatchActivityResult(Activity.java:6135)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
            at android.app.ActivityThread.access$1300(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Try to do this instead, I am assuming that data.getData() returns the path to the file,
MediaPlayer player = new MediaPlayer();
player.setOnPreparedListener(mPreparedListener);
player.setDataSource(MyActivity.this, Uri.fromFile(new File(data.getData())));
MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener()
{
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player)
{
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.start();
}
};

Related

Android "Taking Photos Simply" tutorial does not work for me [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
So, I am trying to implement taking of photos in my app.
I am following the official "Taking Photos Simply" tutorial, but it just gives me errors.
The only thing I am doing differently, it that I am using a popup dialog fragment.
Below is the error I get:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131073, result=-1, data=null} to activity {com.myapp.demo/com.myapp.demo.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3605)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3648)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.paulcanning.mote.NoteDialogFragment.onActivityResult(NoteDialogFragment.java:179)
at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:153)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3601)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3648)
            at android.app.ActivityThread.access$1400(ActivityThread.java:154)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5289)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Button click listener
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
//startActivityForResult(takePictureIntent, 1);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 1);
}
}
}
});
onActivityResult (note, it wouldn't let me use protected)
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == getActivity().RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
You are supplying EXTRA_OUTPUT. Hence, camera apps do not need to supply getExtra("data"), so it will generally be null.
Quoting the documentation for ACTION_IMAGE_CAPTURE:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field. This is useful for applications that only need a small image. If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri value of EXTRA_OUTPUT.
Your image (hopefully) is in the location that you supplied in EXTRA_OUTPUT.

How can i solve getApplicationContext() java.lang.NullPointerExeception

I am trying to connect to an azure application, using android, but I am getting this error. Here is my code and my logs.
I have checked everything and it seen to be right, but the problem I think is with getApplicationContext(). I am unable to debug.
can someone help me please?
public class login extends Activity {
UserServicesImpl usv;
private EditText txtemail;
private EditText txtpassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtemail = (EditText) findViewById(R.id.txtemail);
txtpassword = (EditText) findViewById(R.id.txtpassword);
}
public void LoginKarrega(View view){
usv = new UserServicesImpl();
AlertDialog alertDialog = new AlertDialog.Builder(login.this).create();
alertDialog.setTitle("Alert");
if(usv.exist(txtemail.getText().toString(), txtpassword.getText().toString()) == true) {
alertDialog.setMessage("Sucessful login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
else {
alertDialog.setMessage("wrong login");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
at com.microsoft.windowsazure.mobileservices.notifications.MobileServicePush.<init>(MobileServicePush.java:134)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.initialize(MobileServiceClient.java:1473)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:182)
at com.microsoft.windowsazure.mobileservices.MobileServiceClient.<init>(MobileServiceClient.java:158)
at ao.co.karrega.services.customers.UserServicesImpl.<init>(UserServicesImpl.java:39)
at ao.co.karrega.login.LoginKarrega(login.java:32)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Use below code to solve this error. Currently you are using this instead of getApplicationContext().
try {
mClient = new MobileServiceClient(
"https://newvbdemo.azure-mobile.net/",
"SUFYiOYEAlbEoKfsDgfWNIywaPSMhC29",
getApplicationContext()
);
mTable = mClient.getTable("Users",Users.class);
}catch (MalformedURLException e) {
e.printStackTrace();
}
Your class UserServicesImpl extends Activity but it does not seem to be an Activity.
In particular, activities usually don't have an explicit constructor, and you cannot use an Activity as a Context before its onCreate() lifecycle method. Construction phase <init> in your stacktrace is too early.
The stacktrace also shows that you're trying to instantiate an activity with new in LoginKarrega. Never instantiate an activity with new yourself.
Looks like you should be removing the extends Activity and pass a Context as an argument instead.

Android MediaRecorder NullPointerException

Im just starting out with Java Development and i am fiddling around with the Android Media recorder. However I am getting a NullPointerException which I click the record button using the following source code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
//import android.net.Uri;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Environment;
import android.view.View;
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import java.lang.String;
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaRecorder myAudioRecorder = new MediaRecorder();
myAudioRecorder = new MediaRecorder();
// Uri target = Uri.parse(outputFile.getAbsolutePath());
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void Start_Record(View v)
{
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myAudioRecorder.stop();
myAudioRecorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I realise that this probably due to the fill pointer being set to NULL, however I am struggling to see how to initialize the file reference for this to vanish. I am getting th exception on mediaRecorderPrepare()
Here is the Exception thrown:
03-09 22:53:56.548 31836-31836/uk.co.spectralgear.spectralboost E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference
at uk.co..MainActivity.Start_Record(MainActivity.java:38)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Any help would be greatly appreciated:)
PROBLEM:
Your class variable "myAudioRecord" is null when "Start_Record()" tries to use it:
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'void Android.media.MediaRecorder.prepare()' on a null object reference
SOLUTION: Delete this line from your "onCreate()" method:
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder; // Your class variable: OK...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// MediaRecorder myAudioRecorder = new MediaRecorder(); // DELETE THIS LINE!!!
myAudioRecorder = new MediaRecorder(); // OK...
...
The declaration of "myAudioRecorder" inside onCreate() HIDES the outer declaration. So the outer (class-level) "myAudioRecorder" never gets initialized ... and your program dies with an NPE when "Start_Record()" tries to access it.
PS:
Please consider changing the method name to "start_Record()". Or better, "startRecord()". This is more consistent with Java naming conventions.
I think you are using stop() function while it was already stopped. Check your code and logic.

Adding an input value onto an existing value in a different activity

I'm looking to create a running total on my MainActivity.java, this will be done through adding integers calculated in ActivityAdd.java then sending them across onClick save to a TextView in the MainActivity.java.
It's currently not opening the app due to the stack flow error stating invalid int "". Any advise on this?
AddActivity.Java
OnClickListener button02OnClickListener =
new OnClickListener(){
#Override
public void onClick(View v) {
String theText = result.getText().toString();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("calorie", theText);
startActivity(intent);
}};
MainActivity.Java
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.textView1);
Integer oldValue = Integer.parseInt(textView1.getText().toString());
Integer newValue = Integer.parseInt(calorie);
textView1.setText((oldValue + newValue));
StackFlow error
02-24 09:42:39.873 2535-2535/com.example.student.neillapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.student.neillapp, PID: 2535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.student.neillapp/com.example.student.neillapp.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.student.neillapp.MainActivity.onCreate(MainActivity.java:30)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The Error occurs due to Empty String "" in textView1.
You are not checking if the String is Blank or not.
So, I added extra 2 lines.
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.textView1);
String strOldValue = textView1.getText().toString();
//Integer oldValue = StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
//UPDATE: Replace above with
//Integer oldValue = (myString != null && !myString.isEmpty()) ? Integer.parseInt(myString) : 0;
//UPDATE:
Integer oldValue = 0;
try {
oldValue = Integer.parseInt(myString);
} catch(Exception e) {
//oldValue = 0;
}
Integer newValue = Integer.parseInt(calorie);
textView1.setText((oldValue + newValue));
I think this might help you.
If i understood , what you are looking for is starting an activity for result...
So to do that in your main activity you have to start the ActivityAdd for result like so..
Intent intent = new Intent(getActivity(), ActivityAdd.class);
startActivityForResult(intent,1);
Also in the main activity then you override method onActivityResult like so :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK){
//UPDATE TEXTVIEWS HERE
//DATA IS THE INTENT
}
}
Now in our add activity we must return result once we have it..
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtra("calorie", theText);
setResult(RESULT_OK, intent);
finish();
In you MainActivity.java
String calorie = getIntent().getStringExtra("calorie");
TextView textView1 = (TextView)findViewById(R.id.TextView1);
Integer oldValue = Integer.parseInt(textView1.getText().toString());
Integer newValue = Integer.parseInt(calorie);
//setText() needs a String to set so you can do anyone of the following
textView1.setText(""+(oldValue + newValue));
or
Integer total = oldValue + newValue;
textView1.setText(total.toString());

Volley Request Queue NullPointerException

I am trying to use the Volley library to query an xml api on the web with a search query provided by the user through a SearchWidget.
Whenever I enter a search string, the app crashes with a NullPointerException on adding the StringRequest to the RequestQueue.
Why is this happening?
I am already using Volley with a singleton pattern, as recommended in the Android Developer Guide.
Here is my search() function in the MainActivity.
public static final String TAG = "MYAPPTAG"
private RequestQueue mRequestQueue;
...
protected void onCreate(Bundle savedInstanceState) {
...
// Handle search intent
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
}
...
private void search(String query) {
String xml = null;
String url = "http://www.acme.com/example.php?query=" + query;
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
stringRequest.setTag(TAG);
mRequestQueue
.add(stringRequest); // the exception fires here
}
...
See below for the stack trace.
02-22 23:08:50.636 9856-9856/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.app, PID: 9856
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5146)
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:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.app.MainActivity.search(MainActivity.java:121)
at com.example.app.MainActivity.onCreate(MainActivity.java:83)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5146)
            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:732)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
            at dalvik.system.NativeStart.main(Native Method)
You are firing off a search before you've set the requestqueue from singleton.
So onCreate, you check for the Intent and then start a search before you've got a handle on the volley singleton and, in turn, the requestqueue. Try moving the volley code before the Intent check, like this:
volley = MySingleton.getInstance(getApplicationContext());
mRequestQueue = volley.getRequestQueue();
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
search(query);
}

Categories