My app work strange on diffrent phones - once everything is fine and other time it crash when i try to make photo and save it in my phone's memory. Photo shows up in folder in memory, but when we should come back to application it is shut down:
06-14 23:58:37.448 12344-12344/com.apps.madzia.photo_application E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.apps.madzia.photo_application, PID: 12344
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apps.madzia.photo_application/com.apps.madzia.photo_application.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2412)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
at android.app.ActivityThread.access$1000(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.GridView.setAdapter(GridView.java:187)
at com.apps.madzia.photo_application.fragments.FragmentGallery.onCreateView(FragmentGallery.java:42)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1917)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:544)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5468)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2385)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2470)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053)
at android.app.ActivityThread.access$1000(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
The code of my function to make photos:
public void make_photo() {
Calendar c;
c = Calendar.getInstance();
imageName = "fotka_" + c.get(Calendar.YEAR) + "_" + c.get(Calendar.MONTH) + "_" + c.get(Calendar.DAY_OF_MONTH)
+ "_" + c.get(Calendar.HOUR_OF_DAY) + "_" + c.get(Calendar.MINUTE) + "_" + c.get(Calendar.SECOND);
File katalog = new File(IMAGE_FILE_PATH);
File photo = new File(IMAGE_FILE_PATH+imageName + ".jpg");
if( Environment.getExternalStorageState() == Environment.MEDIA_UNKNOWN || Environment.getExternalStorageState() == Environment.MEDIA_REMOVED || Environment.getExternalStorageState() == Environment.MEDIA_UNMOUNTED) {
Log.d("ExternalStorage", "cannot find memory SD card");
File file = new File(getFilesDir(), imageName);
IMAGE_FILE_PATH = file.getParent()+"/";
Log.d("IMAGE_FILE_PATH", IMAGE_FILE_PATH);
}else {
}
Log.d("photo", photo.getPath());
if (!katalog.exists()) {
katalog.mkdirs();
}
try {
// fotka = File.createNewFile(imageName, ".jpg", katalog);
photo.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Intent zdjecie = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
zdjecie.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
startActivityForResult(zdjecie, 1);
}
Caused by: java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.GridView.setAdapter(GridView.java:187)
at com.apps.madzia.photo_application.fragments.FragmentGallery.onCreateView(FragmentGallery.java:42)
This means that in your FragmentGallery in onCreateView method on line 42 u are setting null ArrayAdapter
Related
I'm trying to get a screenshot from a fragment, but seems that when I do
bitmap = view.getDrawingCache(); it returns null. Does anyone knows why is this happening and how can I fix this?
here is my code:
public void takeScreenshot(View view) {
OutputStream output;
view = view.getRootView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath + "/"
+ getString(R.string.app_name) + "/");
dir.mkdirs();
File file = new File(dir, getString(R.string.app_name) + ".jpg");
bitmap = view.getDrawingCache();
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, output);
output.flush();
output.close();
Log.d(TAG, "screenshot saved");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and calling the method
takeScreenshot(getActivity().findViewById(R.id.fragment_container));
and here is the logCat output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.contractfit/com.contractfit.activities.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.contractfit.fragments.BaseFragment.takeScreenshot(BaseFragment.java:532)
at com.contractfit.fragments.MainFragment.init(MainFragment.java:211)
at com.contractfit.fragments.MainFragment.onCreateView(MainFragment.java:116)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5461)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
Consider doing this like Instrumentation test cases do it, your code is close but differs a bit.
From https://android.googlesource.com/platform/external/droiddriver/+/367267b/src/io/appium/droiddriver/instrumentation/InstrumentationUiDevice.java
Get root view (if it's public):
context.getDriver().getRootElement().getRawElement()));
Take screenshot
public Bitmap call() {
Bitmap screenshot;
rootView.destroyDrawingCache();
rootView.buildDrawingCache(false);
Bitmap drawingCache = rootView.getDrawingCache();
int[] xy = new int[2];
rootView.getLocationOnScreen(xy);
if (xy[0] == 0 && xy[1] == 0) {
screenshot = Bitmap.createBitmap(drawingCache);
} else {
Canvas canvas = new Canvas();
Rect rect = new Rect(0, 0, drawingCache.getWidth(), drawingCache.getHeight());
rect.offset(xy[0], xy[1]);
screenshot =
Bitmap.createBitmap(rect.width() + xy[0], rect.height() + xy[1], Config.ARGB_8888);
canvas.setBitmap(screenshot);
canvas.drawBitmap(drawingCache, null, new RectF(rect), null);
canvas.setBitmap(null);
}
rootView.destroyDrawingCache();
return screenshot;
This code used to work fine with the Nexus 5 image gallery. Ever since moving to the newer Google Photos app selecting images crash this code.
Error:
08-07 10:10:10.792 25086-25086/com.app.app E/CursorWindow﹕ Failed to
read row 0, column -1 from a CursorWindow which has 1 rows, 7 columns.
08-07 10:10:10.795 25086-25086/com.app.app D/AndroidRuntime﹕ Shutting
down VM 08-07 10:10:10.801 25086-25086/com.app.app E/AndroidRuntime﹕
FATAL EXCEPTION: main
Process: com.app.app, PID: 25086
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent {
dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/17870/ACTUAL/1285012603
flg=0x1 (has clip) }} to activity
{com.app.app/com.app.app.PhotoActivity}:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from
CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized
correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at android.database.CursorWrapper.getString(CursorWrapper.java:114)
at com.app.app.PhotoActivity.getRealPathFromURI(PhotoActivity.java:456)
at com.app.app.PhotoActivity.onActivityResult(PhotoActivity.java:436)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
ONACTIVITYRESULT:
case ACTION_SELECT_PHOTO: {
if (resultCode == RESULT_OK) {
Uri selectedImageURI = data.getData();
File imageFile = new File(getRealPathFromURI(selectedImageURI)); // LINE 436
mCurrentPhotoPath = imageFile.toString();
if (mCurrentPhotoPath != null) {
setPic();
mCurrentPhotoPath = null;
}
}
break;
}
GETREALPATHFROMURI:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx); // HERE IS THE ERROR: LINE 456
cursor.close();
}
return result;
}
I'd guess my issue is in one of two places, either getContentResolver().query needs to use some newer method. OR the getColumnIndex(MediaStore.Images.ImageColumns.DATA) MediaStore is the incorrect way to deal with the newer cloud based photo apps.
A URI does not mean there is a file. An app is able to provide the contents through any mechanism it wants (a local file, a local file in a private directory you can't read, streamed over the internet, built dynamically on the fly).
Instead, you should use ContentResolver.openInputStream(contentUri) to get the contents from a URI. You can then transform that into a Bitmap via BitmapFactory.decodeStream()
My app crash when encounters BufferedReader operation. Ive tried to implement the code inside an asyncTask classe, because ive read that the crash is caused by the ui thread, but nothing has changed.
public class URLConnectionReader extends AsyncTask<URL, Void, String> {
String result = null;
#Override
protected String doInBackground(URL... params) {
String result = null;
URL url = (params[0]);
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
url.openStream()
)
);
}catch (IOException e){
e.printStackTrace();
}
return result;
}
}
Logs
03-02 13:28:43.215 25186-25186/com.example.jsonreader E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jsonreader, PID: 25186
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonreader/com.example.jsonreader.MainActivity}: android.os.NetworkOnMainThreadException
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: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at com.example.jsonreader.URLConnectionReader.doInBackground(URLConnectionReader.java:38)
at com.example.jsonreader.MainActivity.onCreate(MainActivity.java:27)
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)
MainActivity code
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLConnectionReader reader = new URLConnectionReader();
String result = reader.doInBackground(address);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}catch (IOException e){
e.printStackTrace();
}
i solved the problem to get back data using the .get instruction
String result = reader.execute(address).get();
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());
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);
}