App Crashes on Splash Screen throwing Null Pointer - java

According to Playstore ANR & Crashes the app is throwing null pointer on SplashScreen oncreate. I've checked the functioning and it looks good at my end. Not all phones are crashing however are.
My SplashActivity.java
package com.example.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
public class SplashActivity extends AppCompatActivity {
String path = "";
String banner = "";
String title = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
if(getIntent().getExtras() != null){
Log.e("splash", "from push link");
path = getIntent().getExtras().getString("link");
banner = getIntent().getExtras().getString("bannerImage");
title = getIntent().getExtras().getString("title");
String link = String.valueOf(Html.fromHtml(Html.fromHtml(path).toString()));
String imgurl = String.valueOf(Html.fromHtml(Html.fromHtml(banner).toString()));
Log.e("link----", "link--" + link);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Push", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String pushtitle = pref.getString("pushtitle", "");
StringBuilder sb = new StringBuilder();
sb.append(pushtitle).append(title).append(",");
Log.e("pushtitle===========", sb.toString());
editor.putString("pushtitle", sb.toString());
String links = pref.getString("link", "");
StringBuilder sb2 = new StringBuilder();
sb2.append(links).append(link).append(",");
Log.e("link===========", sb2.toString());
editor.putString("link", sb2.toString());
String imgurlstr = pref.getString("imgurl", "");
StringBuilder sb3 = new StringBuilder();
sb3.append(imgurlstr).append(imgurl).append(",");
Log.e("imgurl===========", sb3.toString());
editor.putString("imgurl", sb3.toString());
editor.commit();
}
int secondsDelayed = 1;
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
if (path != "") {
Log.e("splash", "path==" + path);
intent.putExtra("link", String.valueOf(Html.fromHtml(Html.fromHtml(path).toString())));
}
startActivity(intent);
finish();
}
}, secondsDelayed * 1000);
}
}
The playstore crashes report as following.
java.lang.NullPointerException com.example.app.SplashActivity.onCreate
java.lang.RuntimeException: at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2984) at
android.app.ActivityThread.handleLaunchActivity
(ActivityThread.java:3045) at android.app.ActivityThread.-wrap14
(ActivityThread.java) at android.app.ActivityThread$H.handleMessage
(ActivityThread.java:1642) at android.os.Handler.dispatchMessage
(Handler.java:102) at android.os.Looper.loop (Looper.java:154) at
android.app.ActivityThread.main (ActivityThread.java:6776) at
java.lang.reflect.Method.invoke (Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:1496) at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:1386) Caused by: java.lang.NullPointerException:
at java.io.StringReader. (StringReader.java:50) at
android.text.HtmlToSpannedConverter.convert (Html.java:758) at
android.text.Html.fromHtml (Html.java:245) at
android.text.Html.fromHtml (Html.java:188) at
com.example.app.SplashActivity.onCreate (SplashActivity.java:27)
at android.app.Activity.performCreate (Activity.java:6955) at
android.app.Instrumentation.callActivityOnCreate
(Instrumentation.java:1126) at
android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2927
EDIT: Debugging the App I got the below error:
Log messages will follow once session has started...
I/art ( 3818): Not late-enabling -Xcheck:jni (already on) W/art
( 3818): Unexpected CPU variant for X86 using defaults: x86 W/System
( 3818): ClassLoader referenced unknown path:
/data/app/com.example.app-1/lib/x86 D/FirebaseApp( 3818):
com.google.firebase.auth.FirebaseAuth is not linked. Skipping
initialization. W/InstanceID/Rpc( 3818): Found 10012 D/FirebaseApp(
3818): com.google.firebase.crash.FirebaseCrash is not linked. Skipping
initialization. I/FA ( 3818): App measurement is starting up,
version: 10084 I/FA ( 3818): To enable debug logging run: adb
shell setprop log.tag.FA VERBOSE I/FA ( 3818): To enable faster
debug mode event logging run: I/FA ( 3818): adb shell setprop
debug.firebase.analytics.app com.example.app I/FirebaseInitProvider(
3818): FirebaseApp initialization successful W/art ( 3818): Before
Android 4.1, method android.graphics.PorterDuffColorFilter
android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter,
android.content.res.ColorStateList, android.graphics.PorterDuff$Mode)
would have incorrectly overridden the package-private method in
android.graphics.drawable.Drawable E/splash ( 3818): from push link
D/AndroidRuntime( 3818): Shutting down VM E/AndroidRuntime( 3818):
FATAL EXCEPTION: main E/AndroidRuntime( 3818): Process:
com.example.app, PID: 3818 E/AndroidRuntime( 3818):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.app/com.example.app.SplashActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
java.lang.String.length()' on a null object reference
E/AndroidRuntime( 3818): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
E/AndroidRuntime( 3818): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
E/AndroidRuntime( 3818): at
android.app.ActivityThread.-wrap12(ActivityThread.java)
E/AndroidRuntime( 3818): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
E/AndroidRuntime( 3818): at
android.os.Handler.dispatchMessage(Handler.java:102) E/AndroidRuntime(
3818): at android.os.Looper.loop(Looper.java:154) E/AndroidRuntime(
3818): at android.app.ActivityThread.main(ActivityThread.java:6077)
E/AndroidRuntime( 3818): at java.lang.reflect.Method.invoke(Native
Method) E/AndroidRuntime( 3818): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
E/AndroidRuntime( 3818): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
E/AndroidRuntime( 3818): Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'int java.lang.String.length()' on a
null object reference E/AndroidRuntime( 3818): at
java.io.StringReader.(StringReader.java:50) E/AndroidRuntime(
3818): at android.text.HtmlToSpannedConverter.convert(Html.java:758)
E/AndroidRuntime( 3818): at android.text.Html.fromHtml(Html.java:245)
E/AndroidRuntime( 3818): at android.text.Html.fromHtml(Html.java:188)
E/AndroidRuntime( 3818): at
com.example.app.SplashActivity.onCreate(SplashActivity.java:27)
E/AndroidRuntime( 3818): at
android.app.Activity.performCreate(Activity.java:6662)
E/AndroidRuntime( 3818): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
E/AndroidRuntime( 3818): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
E/AndroidRuntime( 3818): ... 9 more

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
if(getIntent().getExtras() != null && this.getIntent().getExtras().containsKey("yourKey")){
try {
Log.e("splash", "from push link");
path = getIntent().getExtras().getString("link");
banner = getIntent().getExtras().getString("bannerImage");
title = getIntent().getExtras().getString("title");
String link = String.valueOf(Html.fromHtml(Html.fromHtml(path).toString()));
String imgurl = String.valueOf(Html.fromHtml(Html.fromHtml(banner).toString()));
Log.e("link----", "link--" + link);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Push", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String pushtitle = pref.getString("pushtitle", "");
StringBuilder sb = new StringBuilder();
sb.append(pushtitle).append(title).append(",");
Log.e("pushtitle===========", sb.toString());
editor.putString("pushtitle", sb.toString());
String links = pref.getString("link", "");
StringBuilder sb2 = new StringBuilder();
sb2.append(links).append(link).append(",");
Log.e("link===========", sb2.toString());
editor.putString("link", sb2.toString());
String imgurlstr = pref.getString("imgurl", "");
StringBuilder sb3 = new StringBuilder();
sb3.append(imgurlstr).append(imgurl).append(",");
Log.e("imgurl===========", sb3.toString());
editor.putString("imgurl", sb3.toString());
editor.commit();
} catch (NullPointerException e ) {
path = "";
banner = "";
title = "";
}
}

Related

Fatal exception at main android during dropbox authentication [duplicate]

This question already exists:
Dropbox Core API is not working. I don't want to hardcode app key and secret?
Closed 7 years ago.
I am getting fatal exception error at main nullpointer exception. basically i have 2 activities login and main activity.you will enter app key and app secret in login activity then after authentication it will take you to main activity any help ??
login activity
public class login_activity extends AppCompatActivity {
public String APP_kEY ;
public String APP_SECRET;
public String accessToken;
EditText app_key_view;
EditText App_secret_view;
Button dropbox;
public DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = getSharedPreferences("login",MODE_PRIVATE);
APP_kEY = pref.getString("appkey",null);
APP_SECRET = pref.getString("appsecret",null);
accessToken = pref.getString("access",null);
if (accessToken != null){
AppKeyPair appkeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appkeys);
session.setOAuth2AccessToken(accessToken);
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity);
app_key_view=(EditText)findViewById(R.id.app_key_text);
App_secret_view=(EditText)findViewById(R.id.app_secret_text);
dropbox = (Button)findViewById(R.id.link_dropbox);
//////////////////////////////////////////////////////////////
dropbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
APP_kEY = app_key_view.getText().toString();
APP_SECRET = App_secret_view.getText().toString();
AppKeyPair appKeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<>(session);
mDBApi.getSession().startOAuth2Authentication(login_activity.this);
}
});
}
#Override
protected void onResume () {
super.onResume();
if(mDBApi.getSession().authenticationSuccessful()){
try {
mDBApi.getSession().finishAuthentication();
accessToken = mDBApi.getSession().getOAuth2AccessToken();
SharedPreferences.Editor editor = getSharedPreferences("login",MODE_PRIVATE).edit();
editor.putString("appkey",APP_kEY);
editor.putString("appsecret",APP_SECRET);
editor.putString("access",accessToken);
editor.commit();
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
catch (IllegalStateException e){
Log.i("DbAuthLog", "Error authenticationg", e);
}
}
}
Logcat
09-11 21:06:01.947 3842-3842/? I/art﹕ Late-enabling -Xcheck:jni
09-11 21:06:01.975 3842-3851/? I/art﹕ Debugger is no longer active
09-11 21:06:02.370 3842-3857/? I/art﹕ Background sticky concurrent mark sweep GC freed 2909(253KB) AllocSpace objects, 2(32KB) LOS objects, 0% free, 50MB/50MB, paused 36.891ms total 133.660ms
09-11 21:06:02.803 3842-3842/? D/AndroidRuntime﹕ Shutting down VM
09-11 21:06:02.803 3842-3842/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ayzaz.timescopev1.timescope, PID: 3842
java.lang.RuntimeException: Unable to resume activity {com.example.ayzaz.timescopev1.timescope/com.example.ayzaz.timescopev1.timescope.login_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
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.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at com.example.ayzaz.timescopev1.timescope.login_activity.onResume(login_activity.java:77)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2975)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            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)
09-11 21:06:05.849 3842-3842/com.example.ayzaz.timescopev1.timescope I/Process﹕ Sending signal. PID: 3842 SIG: 9
onResume() always gets called after onCreate().
When onResume() begins, mDBApi is null, because this field is only ever assigned in the onClick() method.
You either need to assign mDBApi in onCreate() directly, or you need to check that it is not null before you try to use it.

java.lang.NullPointerException occuring, developing android, how do I fix that? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
java.lang.NullPointerException occuring
Log-cat says Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
Here's my code:
I'm trying to get jSon data from a server(MySql) database, then displaying it in a list.
public class AllProducts extends ListActivity {
private ProgressDialog pDialog;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> productsList;
private static String url_all_products = "http://server:host.../view.php";
private static final String TAG_SUCCESS="success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
JSONArray products=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList=new ArrayList<HashMap<String, String>>();
new LoadAllProducts().execute();
Exception at new LoadAllProducts().execute();
ListView lv = getListView();
}
class LoadAllProducts extends AsyncTask<String,String,String>
Java.lang.NullPointerException Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
occuring at class LoadAllProducts extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog= new ProgressDialog(AllProducts.this);
pDialog.setMessage("Loading Products....Wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
Exception at pDialog.show();
}
#Override
protected String doInBackground(String... params) {
ContentValues param=new ContentValues();
JSONObject json= jParser.makeHttpRequest(url_all_products,"GET",param);
Log.d("All Products: ", json.toString());
java.lang.NullPointerException occuring at Log.d("All Products: ", json.toString());
try{
int success=json.getInt(TAG_SUCCESS);
if(success==1)
{
products = json.getJSONArray(TAG_PRODUCTS);
for(int j=0; j<products.length() ; j++ )
{
JSONObject c = products.getJSONObject(j);
String id=c.getString(TAG_PID);
String name=c.getString(TAG_NAME);
HashMap<String,String> map=new HashMap<String,String>();
map.put(TAG_PID,id);
map.put(TAG_NAME,name);
productsList.add(map);
}
}
else {
Intent i=new Intent(getApplicationContext(),NewProduct.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}catch(JSONException e)
{
e.printStackTrace();
}
return null;
}
}
}
I have a button in my UI to get data from server and show it in a list, as i tap the button, pDialog shows and then the app goes "not responding" and these exceptions occur
Here is the LogCat
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:122)
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication W/System.err﹕ ... 19 more
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
09-03 16:10:40.500 27696-31923/com.example.vashisht.myapplication E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
09-03 16:10:40.510 27696-31923/com.example.vashisht.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.vashisht.myapplication, PID: 27696
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:76)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.doInBackground(AllProducts.java:57)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
09-03 16:10:40.980 27696-27696/com.example.vashisht.myapplication E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.vashisht.myapplication.AllProducts has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{10a4b377 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:382)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.vashisht.myapplication.AllProducts$LoadAllProducts.onPreExecute(AllProducts.java:67)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.vashisht.myapplication.AllProducts.onCreate(AllProducts.java:50)
at android.app.Activity.performCreate(Activity.java:5958)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
09-03 16:10:44.250 27696-31923/com.example.vashisht.myapplication D/Process﹕ killProcess, pid=27696
09-03 16:10:44.260 27696-31923/com.example.vashisht.myapplication D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:138 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690
this means that the JSONObject json == null. You can check this in code before calling methods on the JSONObject. I guess you dont actually get data when you call the httprequest.

Cannot update text in EditText inside onActivityResult

I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
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:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
            at android.app.ActivityThread.access$1100(ActivityThread.java:150)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:5225)
            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:741)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
            at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...

NullPointerException when I try to capture an image (built-in camera) and save it to a file [duplicate]

This question already has answers here:
Android Camera : data intent returns null
(11 answers)
Closed 8 years ago.
Here's what the app does - User clicks button (to take a picture) on Activity A, the captured image gets set as on an ImageView in Activity A, and then the user clicks a "save" button, which takes him/her to Activity B, where the image they took gets displayed (on an ImageView in Activity B)
In order to do this I am trying to find a way to save the image. I tried many different things, but I keep getting a NullPointerException. Here is my code:
I highlighted the area where I think the error is:
public void onClick(View view) {
switch (view.getId()) {
case R.id.take_picture_button:
takePic = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile(); //so photoFile = the file we created up top
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
**takePic.putExtra(MediaStore.EXTRA_OUTPUT**, //extra_output is just the name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video.
**Uri.fromFile(photoFile));**
startActivityForResult(takePic, cameraData);
}
And here is the code for the onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == cameraData && resultCode == RESULT_OK) {
mReturningWithResult = true;
extras = data.getExtras();
And here is where I set my image view to my captured image (on Activity A)
#Override
protected void onPostResume() {
super.onPostResume();
if (mReturningWithResult) {
foodImage = (Bitmap) extras.get("data");
foodImageView.setImageBitmap(foodImage);
}
mReturningWithResult = false;//resetting it for next time
}
Here is the logcat (sorry I'm new to this)
10-15 20:58:59.612 32005-32005/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
10-15 20:59:21.545 32005-32005/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:23.127 32005-32005/com.example.nikhil.foodshark W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark D/AndroidRuntime﹕ Shutting down VM
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41a39da0)
10-15 20:59:33.678 32005-32005/com.example.nikhil.foodshark E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nikhil.foodshark, PID: 32005
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.nikhil.foodshark/com.example.nikhil.foodshark.NewDish}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3680)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1400(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
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 com.example.nikhil.foodshark.NewDish.onActivityResult(NewDish.java:144)
at android.app.Activity.dispatchActivityResult(Activity.java:5650)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3676)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
            at android.app.ActivityThread.access$1400(ActivityThread.java:174)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
            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)
10-15 20:59:56.353 32005-32005/com.example.nikhil.foodshark I/Process﹕ Sending signal. PID: 32005 SIG: 9
10-15 20:59:56.613 378-378/com.example.nikhil.foodshark I/PersonaManager﹕ getPersonaService() name persona_policy
10-15 20:59:56.723 378-378/com.example.nikhil.foodshark I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050_msm8960_refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050__release_AU ()
OpenGL ES Shader Compiler Version: 17.01.12.SPL
Build Date: 03/28/14 Fri
Local Branch:
Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_2.7_RB1.04.04.02.007.050
Local Patches: NONE
Reconstruct Branch: NOTHING
10-15 20:59:56.763 378-378/com.example.nikhil.foodshark D/OpenGLRenderer﹕ Enabling debug mode 0
Do you guys know a way I can fix this? Thank you!
You are passing MediaStore.EXTRA_OUTPUT, in which case, the intent field in onActivityResult can be null.
The solution is to just use the photo file you created, and passed as uri in the putExtra
So instead of trying to get the photo file location from the intent, just use Uri.fromFile(photoFile)
replace
extras = data.getExtras();
...
with
`Uri.fromFile(photoFile)`
or just use photoFile if that is what you want...just dont rely on intent data

Crash while downloading file with AsyncTask

I'm developing an app for Android to download the pic from all the friends. I successfully made my app logging in. Now, I need to parse a JSON and download some of the pics. Here the sources:
FacebookPicDownloader (asynctask to download all the pics):
public class FacebookPicDownloader extends AsyncTask <String, Integer, Integer>{
Context context;
private final int MAX_BUFFER_SIZE = 2048;
String id;
int length;
public FacebookPicDownloader (Context context){
this.context = context;
}
//http://graph.facebook.com/ + userid + /picture?type=large to download the photos
#Override
protected Integer doInBackground(String... params) {
for (int i=0; i<params.length; i++){
try {
URL mUrl = new URL("http://graph.facebook.com/" + params[i] + "/picture?type=large");
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
connection.connect();
length = connection.getContentLength();
int downloaded = 0;
File file = new File ("/sdcard/syncro/");
if (!file.exists() || !file.isDirectory()){
file.mkdir();
}
id = params[0];
file = new File ("/sdcard/syncro/" + id);
FileOutputStream fos = new FileOutputStream (file);
//Start downloading
InputStream stream = connection.getInputStream();
byte [] buffer = new byte [(length < MAX_BUFFER_SIZE) ? length : MAX_BUFFER_SIZE];
int read;
while ((read=stream.read(buffer)) != -1){
fos.write(buffer, 0, read);
downloaded += read;
}
fos.close();
} catch (Exception e){
return 2;
}
}
return 1;
}
Manager.java, another AsyncTask that calls FacebookPicDownloader
import java.util.ArrayList;
import org.json.*;
import com.gnufabio.syncro.util.Util;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;
import com.facebook.android.*;
import com.gnufabio.syncro.util.*;
public class Manager extends AsyncTask<String, Integer, Integer>{
Context context;
Facebook facebook;
ProgressDialog dialog;
public void doStuff(Facebook facebook, Context context, String ... params){
this.context = context;
this.facebook = facebook;
this.execute(params);
}
#Override
protected void onPreExecute(){
dialog = ProgressDialog.show(context, "Wait" , " Loading. Please wait ... ", true);
dialog.setCancelable(false);
}
#Override
protected Integer doInBackground(String... params) {
String friendlist;
try {
friendlist = facebook.request("me/friends");
FileWriterThread filewriter = new FileWriterThread();
filewriter.writeFile(friendlist, "/sdcard/syncro/friends");
} catch (Exception e) {
friendlist = "";
}
String previous = "[NONE]";
ArrayList validContacts = new ArrayList<String>();
Cursor nameCur = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
if (display != null && !(display.contains(previous) || display.equalsIgnoreCase(previous)) && display.contains(" ")){
Log.d("SYNCRO", "Valid contact found: " + display);
validContacts.add(display);
previous = display;
}
}
nameCur.close();
try {
ArrayList idToDownload = new ArrayList <String>();
JSONArray jFriendList = new JSONArray(new JSONObject(friendlist).getString("data"));
for (int i = 0; i < jFriendList.length(); i++){
JSONObject jFriend = jFriendList.getJSONObject(i);
for (int y = 0; y < validContacts.toArray().length; y++){
if (jFriend.getString("name").equals((String)(validContacts.get(y)))){
String id = jFriend.getString("id");
Log.d("SYNCRO", "Adding pic for id \"" + id + "\"");
idToDowload.add(id);
}
}
}
FacebookPicDownloader downloader = new FacebookPicDownloader(context);
downloader.execute((String[]) idToDownload.toArray());
} catch (JSONException e) {
Log.d("SYNCRO", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Integer result){
dialog.dismiss();
}
}
The problem is that it downloads just the first pic, and then the app crashes...here the logcat:
D/szipinf ( 7785): Initializing inflate state
E/AndroidRuntime( 7735): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime( 7735): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime( 7735): at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
E/AndroidRuntime( 7735): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
E/AndroidRuntime( 7735): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
E/AndroidRuntime( 7735): at java.lang.Thread.run(Thread.java:1019)
E/AndroidRuntime( 7735): Caused by: java.lang.ClassCastException: [Ljava.lang.Object;
E/AndroidRuntime( 7735): at com.gnufabio.syncro.Manager.doInBackground(Manager.java:78)
E/AndroidRuntime( 7735): at com.gnufabio.syncro.Manager.doInBackground(Manager.java:1)
E/AndroidRuntime( 7735): at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
E/AndroidRuntime( 7735): ... 4 more W/ActivityManager( 541): Force finishing activity com.gnufabio.syncro/.SuperSyncronizerActivity D/szipinf ( 7797): Initializing inflate state D/szipinf ( 7797): Initializing zlib to inflate D/dalvikvm( 7797): GC_CONCURRENT freed 224K, 44% free 3519K/6215K, external 0K/0K, paused 3ms+3ms
E/WindowManager( 7735): Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4051c538 that was originally added here
E/WindowManager( 7735): android.view.WindowLeaked: Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4051c538 that was originally added here
E/WindowManager( 7735): at android.view.ViewRoot.<init>(ViewRoot.java:260)
E/WindowManager( 7735): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
E/WindowManager( 7735): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
E/WindowManager( 7735): at android.view.Window$LocalWindowManager.addView(Window.java:424)
E/WindowManager( 7735): at android.app.Dialog.show(Dialog.java:241)
E/WindowManager( 7735): at android.app.ProgressDialog.show(ProgressDialog.java:110)
E/WindowManager( 7735): at android.app.ProgressDialog.show(ProgressDialog.java:93)
E/WindowManager( 7735): at com.gnufabio.syncro.Manager.onPreExecute(Manager.java:36)
E/WindowManager( 7735): at android.os.AsyncTask.execute(AsyncTask.java:391)
E/WindowManager( 7735): at com.gnufabio.syncro.Manager.doStuff(Manager.java:31)
E/WindowManager( 7735): at com.gnufabio.syncro.SuperSyncronizerActivity$2.onClick(SuperSyncronizerActivity.java:73)
E/WindowManager( 7735): at android.view.View.performClick(View.java:2486)
E/WindowManager( 7735): at android.view.View$PerformClick.run(View.java:9130)
E/WindowManager( 7735): at android.os.Handler.handleCallback(Handler.java:587)
E/WindowManager( 7735): at android.os.Handler.dispatchMessage(Handler.java:92)
E/WindowManager( 7735): at android.os.Looper.loop(Looper.java:130)
E/WindowManager( 7735): at android.app.ActivityThread.main(ActivityThread.java:3694)
E/WindowManager( 7735): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager( 7735): at java.lang.reflect.Method.invoke(Method.java:507)
E/WindowManager( 7735): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
E/WindowManager( 7735): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
E/WindowManager( 7735): at dalvik.system.NativeStart.main(Native Method) D/dalvikvm( 7797): GC_CONCURRENT freed 171K, 41% free 3888K/6535K, external 0K/0K, paused 3ms+4ms
Thanks to anyone will help me.
The crash is caused by this code: (String[]) idToDownload.toArray().
Try creating a new String array instead of using the cast:
Replace the line
downloader.execute((String[]) idToDownload.toArray());
By:
String[] stringArray= new String[idToDownload.size()];
idToDownload.toArray(stringArray);
downloader.execute(stringArray);
KR

Categories

Resources