I hope someone can help me.
I have an android app that has a standard login but also has twitter and facebook login buttons.
When the user try's to login using the facebook button the app crashes and I am unsure as to why? I believe that it is because the email field is returning as null.
I have rebuilt the app numerous times, the app is public on facebook, the app id is correct as is the package name.
logcat is below
09-03 15:15:45.971 16896-17259/com.projects.bmxtrackfinder W/chromium﹕ [WARNING:keycode_converter.cc(91)] empty code string
09-03 15:15:47.470 16896-17259/com.projects.bmxtrackfinder W/chromium﹕ [WARNING:keycode_converter.cc(91)] empty code string
09-03 15:15:48.128 16896-17259/com.projects.bmxtrackfinder W/chromium﹕ [WARNING:keycode_converter.cc(91)] empty code string
09-03 15:15:52.942 16896-16896/com.projects.bmxtrackfinder W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 16896
09-03 15:16:04.690 16896-16896/com.projects.bmxtrackfinder W/BindingManager﹕ Cannot call determinedVisibility() - never saw a connection for the pid: 16896
09-03 15:16:04.821 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:04.821 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:04.828 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:04.829 16896-16896/com.projects.bmxtrackfinder E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
09-03 15:16:05.094 16896-16896/com.projects.bmxtrackfinder E/FACEBOOK USERNAME**﹕ John TrackFinder
09-03 15:16:05.095 16896-16896/com.projects.bmxtrackfinder E/FACEBOOK ID**﹕ 135514753461349
09-03 15:16:05.096 16896-16896/com.projects.bmxtrackfinder E/FACEBOOK EMAIL**﹕ null
09-03 15:16:05.124 16896-17668/com.projects.bmxtrackfinder E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #4
Process: com.projects.bmxtrackfinder, PID: 16896
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
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 java.lang.Object.toString()' on a null object reference
at com.fragments.activity.LoginActivity$2.onAsyncTaskDoInBackground(LoginActivity.java:263)
at com.asynctask.MGAsyncTask.doInBackground(MGAsyncTask.java:45)
at com.asynctask.MGAsyncTask.doInBackground(MGAsyncTask.java:10)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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 15:16:05.667 16896-16896/com.projects.bmxtrackfinder E/WindowManager﹕ android.view.WindowLeaked: Activity com.fragments.activity.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{2f585567 V.E..... R.....ID 0,0-729,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at android.app.ProgressDialog.show(ProgressDialog.java:116)
at android.app.ProgressDialog.show(ProgressDialog.java:99)
at com.asynctask.MGAsyncTask.onPreExecute(MGAsyncTask.java:60)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
at android.os.AsyncTask.execute(AsyncTask.java:539)
at com.fragments.activity.LoginActivity.syncFacebookUser(LoginActivity.java:274)
at com.fragments.activity.LoginActivity$4.onCompleted(LoginActivity.java:423)
at com.facebook.Request$1.onCompleted(Request.java:303)
at com.facebook.Request$4.run(Request.java:1726)
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: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-03 15:16:12.839 16896-16908/com.projects.bmxtrackfinder W/art﹕ Suspending all threads took: 11.292ms
(LoginActivity.java:263) = String email = user.asMap().get("email").toString;
Asynch code below:
package com.asynctask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import com.projects.bmxtrackfinder.R;
import com.utilities.MGUtilities;
public class MGAsyncTask extends AsyncTask<Void, Void, String> {
public ProgressDialog dialog;
public Activity activity;
public Object object;
public int tag = 0;
public int listTag = 0;
OnMGAsyncTaskListener mCallback;
public interface OnMGAsyncTaskListener {
public void onAsyncTaskDoInBackground(MGAsyncTask asyncTask);
public void onAsyncTaskProgressUpdate(MGAsyncTask asyncTask);
public void onAsyncTaskPostExecute(MGAsyncTask asyncTask);
public void onAsyncTaskPreExecute(MGAsyncTask asyncTask);
}
public void setMGAsyncTaskListener(OnMGAsyncTaskListener listener) {
try {
mCallback = (OnMGAsyncTaskListener) listener;
} catch (ClassCastException e) {
throw new ClassCastException(this.toString() + "Did not implement OnMGAsyncTaskListener");
}
}
public MGAsyncTask(Activity activity) {
this.activity = activity;
}
public void startAsyncTask() {
this.execute();
}
#Override
protected String doInBackground(Void... params) {
mCallback.onAsyncTaskDoInBackground(this);
return "";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation. parse json data
dialog.dismiss();
mCallback.onAsyncTaskPostExecute(this);
}
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For example showing ProgessDialog
String loading = MGUtilities.getStringFromResource(activity, R.string.loading);
dialog = ProgressDialog.show(activity, "", loading, true);
mCallback.onAsyncTaskPreExecute(this);
}
#Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
mCallback.onAsyncTaskProgressUpdate(this);
}
public void setMessage(String message) {
dialog.setMessage(message);
}
public void setTitle(String title) {
dialog.setTitle(title);
}
public void setIcon(int resId) {
dialog.setIcon(resId);
}
}
Related
I want to get the list of videos from Youtube channel.
You will see below the class to connect to Youtube and my Activity that interacts with this class. I get an exception "java.lang.RuntimeException: Unable to start activity VideoListActivity" when calling YouTube.Search.List.execute();
I am new in android, so I think there is a stupid mistake. Please help to find it, or maybe suggest the another way to get data from Youtube.
YoutubeConnector class
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class YoutubeConnector {
private static YouTube youtube;
private static YouTube.Search.List query;
public static final String KEY = DeveloperKey.DEVELOPER_KEY;
public static List<VideoItem> search() throws IOException {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest httpRequest) throws IOException {
}
}).setApplicationName(R.string.app_name).build();
query = youtube.search().list("id,snippet");
query.setKey(KEY);
query.setType("video");
query.setChannelId("**************");
query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();
List<VideoItem> items = new ArrayList<VideoItem>();
for (SearchResult result : results) {
VideoItem item = new VideoItem();
item.setTitle(result.getSnippet().getTitle());
item.setDescription(result.getSnippet().getDescription());
item.setThumbnailURL(result.getSnippet().getThumbnails().getDefault().getUrl());
item.setId(result.getId().getVideoId());
items.add(item);
}
return items;
}
}
VideoListActivity class
public class VideoListActivity extends ListActivity{
List<VideoItem> videoFileList;
public class VideoAapter extends ArrayAdapter{
//.....................
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
setListAdapter(new VideoAapter(VideoListActivity.this, R.layout.list_item_video, videoFileList));
}
}
Logcat
06-16 18:14:56.926 30817-30817/com.example.alex.youtubecanal W/art: Failed to find OatDexFile for DexFile /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex ( canonical path /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex) with checksum 0x7eb43558 in OatFile /data/data/com.example.alex.youtubecanal/cache/slice-slice_5-classes.dex
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isShipBuild true
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SMARTBONDING_FEATURE_ENABLED is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal D/AndroidRuntime: Shutting down VM
06-16 18:14:57.641 30817-30817/com.example.alex.youtubecanal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alex.youtubecanal, PID: 30817
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.alex.youtubecanal/com.example.alex.youtubecanal.VideoListActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3133)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
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:245)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:128)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:370)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:93)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.example.alex.youtubecanal.YoutubeConnector.search(YoutubeConnector.java:37)
at com.example.alex.youtubecanal.VideoListActivity.onCreate(VideoListActivity.java:58)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
You need to run the YoutubeConnector.search outside of onCreate() in an Async Thread. This basically means that the method is stalling the program and will cause the program to crash or hang. To fix, create a new class called Search for example:
SearchClass.java:
import android.os.AsyncTask;
import java.io.IOException;
public class Search extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String a){
VideoListActivity.context.updateAdapter();
}
}
VideoListActivity.java:
public class VideoListActivity extends ListActivity{
static List<VideoItem> videoFileList;
static Context context;
public class VideoAapter extends ArrayAdapter{
//.....................
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Search search= new Search();
search.execute(new String[]{});
}
public void updateAdapter(ArrayList<String> list) {
setListAdapter(new VideoAapter(VideoListActivity.this,R.layout.list_item_video, videoFileList));
}
}
Hopefully this will work :). If it does not, just post the error, and we'll get back. Good luck!
It looks like the problem is coming from a NetworkOnMainThreadException. Check out this example. Hope it helps!
I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
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:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
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:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
The following code is a part of my app and it isn't working and I don't know why.
I don't know at which place I can put the "new MormaKaugummi().execute();". At any place the App crashed and gave me the error "Unfortunately, Criminal Life has stopped."
The "counter textview" is in an another activity in the same app.
(The name of the App is Criminal Life).
I need a unique solution because I'm new in Android programming.
public class Morma extends AppCompatActivity {
class MormaKaugummi extends AsyncTask<String, String, String> {
private int count = 0;
private void count() {
count++;
}
private void update() {
TextView counter = (TextView) findViewById(R.id.counter);
String Kcounter = Integer.toString(count);
counter.setText(Kcounter);
}
#Override
protected String doInBackground(String... params) {
count();
update();
return null;
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
That's the logcat
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:32)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.doInBackground(Morma.java:15)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at java.lang.Thread.run(Thread.java:856)
11-07 13:48:35.514 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:35.674 622-622/peppermine_studios.criminallife W/EGL_emulation: eglSurfaceAttrib not implemented
11-07 13:48:37.364 622-1376/? I/Process: Sending signal. PID: 622 SIG: 9
You are trying to do findviewbyId and update the text view in your doInBackground method via the update function, which you cannot do.
As for the crash its happening because of a null pointer exception as you can read for yourself in the logcat's caused by clause it tells you the exact line number where the null pointer exception is thrown
Caused by: java.lang.NullPointerException
11-07 13:48:34.964 622-1376/peppermine_studios.criminallife E/AndroidRuntime: at peppermine_studios.criminallife.Morma$MormaKaugummi.update(Morma.java:26)
as you can see here, its caused by null pointer at line 26 in Morma.java and I am guessing that your TextView counter is null since you are trying to initialize a variable to reference a UI element from a non-UI thread, the counter variable will be initialized as null obviously.
Now for the solution:
What you need to do is put the update function in the onPostExecute method for the async task class. Reason: onPostExceute runs on whatever thread the asyntcTask.execute method was called from so you are supposed to do your UI update in the onPostExecute method
#Override
protected String doInBackground(String... params) {
count();
return null;
}
#Override
protect void onPostExecute(String result) {
update();
}
Also since you are returning null from doInBackground anyway you should Extend AsyncTask<String,String,Void> ideally.
EDIT 1:
Added code
public class Morma extends AppCompatActivity {
// make the text view class variable if you want to update it outside of onCreate.
private TextView mCounterTextView;
class MormaKaugummi extends AsyncTask<Void, Void, Void> {
private int count = 0;
private void count() {
count++;
}
private void update() {
String Kcounter = Integer.toString(count);
mCounterTextView.setText(Kcounter);
}
#Override
protected void doInBackground(Void... aVoid) {
count();
}
#Override
protected void onPostExecute(Void aVoid) {
update();
}
}
private ProgressBar progressBarKaugummi;
private int progressStatusKaugummi = 0;
private Handler handlerKaugummi = new Handler();
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_morma);
Button buttonMormaKaugummiKlauen = (Button) findViewById(R.id.buttonMormaKaugummiKlauen);
// initiate all your view items in onCreate.
mCounterTextView = (TextView) findViewById(R.id.counter);
buttonMormaKaugummiKlauen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBarKaugummi = (ProgressBar) findViewById(R.id.progressBarMormaKaugummi);
new Thread(new Runnable() {
public void run() {
while (progressStatusKaugummi < 100) {
progressStatusKaugummi += 1;
handlerKaugummi.post(new Runnable() {
public void run() {
progressBarKaugummi.setProgress(progressStatusKaugummi);
}
});
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
if (progressStatusKaugummi == 100) {
progressBarKaugummi.setProgress(0);
recreate();
new MormaKaugummi().execute();
}
}
});
You need to initialize all your view elements like the textview in onCreate itself and keep the reference as a class variable if you are going to use that view outside of onCreate.
I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
I'm new at android programming, I want to fetch Parse in ListView arrangement and i found the perfect guide, but i cant really implement it on my code.
I have browse a lot for 2 days and i give up.
Here's the error
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.osbert.buttons, PID: 2732
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.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library.
at com.parse.ParseUser.checkApplicationContext(ParseUser.java:1426)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1048)
at com.parse.ParseUser.access$900(ParseUser.java:27)
at com.parse.ParseUser$9.then(ParseUser.java:1041)
at com.parse.ParseUser$9.then(ParseUser.java:1038)
at com.parse.TaskQueue.enqueue(TaskQueue.java:61)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1038)
at com.parse.ParseUser.getCurrentUserAsync(ParseUser.java:1001)
at com.parse.ParseQuery.getUserAsync(ParseQuery.java:352)
at com.parse.ParseQuery.access$1600(ParseQuery.java:78)
at com.parse.ParseQuery$15.call(ParseQuery.java:1000)
at com.parse.ParseQuery$15.call(ParseQuery.java:997)
at com.parse.ParseQuery.doWithRunningCheck(ParseQuery.java:936)
at com.parse.ParseQuery.findInBackground(ParseQuery.java:997)
at com.parse.ParseQuery.find(ParseQuery.java:588)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.doInBackground(RestaurantList.java:60)
at com.example.osbert.buttons.RestaurantList$RemoteDataTask.doInBackground(RestaurantList.java:34)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.osbert.buttons.RestaurantList has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{27bb5583 V.E..... R......D 0,0-729,322} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
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.osbert.buttons.RestaurantList$RemoteDataTask.onPreExecute(RestaurantList.java:46)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.osbert.buttons.RestaurantList.onCreate(RestaurantList.java:30)
at android.app.Activity.performCreate(Activity.java:5937)
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)
And here's my code
package com.example.osbert.buttons;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class RestaurantList extends Activity {
// Declare Variables
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
ListViewAdapter adapter;
private List<WorldPopulation> worldpopulationlist = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute RemoteDataTask AsyncTask
new RemoteDataTask().execute();
}
// RemoteDataTask AsyncTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(RestaurantList.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
worldpopulationlist = new ArrayList<WorldPopulation>();
try {
// Locate the class table named "Country" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Country");
// Locate the column named "ranknum" in Parse.com and order list
// by ascending
query.orderByAscending("ranknum");
ob = query.find();
for (ParseObject country : ob) {
// Locate images in flag column
ParseFile image = (ParseFile) country.get("flag");
WorldPopulation map = new WorldPopulation();
map.setRank((String) country.get("rank"));
map.setCountry((String) country.get("country"));
map.setPopulation((String) country.get("population"));
map.setFlag(image.getUrl());
worldpopulationlist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(RestaurantList.this,
worldpopulationlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
finish();
}
}
}
Pls help :((
Thanks in advance
Have you even tried resolving this?
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library?
Its the cause of the crash.
Also why are you calling finish() i onPostExecute?! It will close your activity...and i suppose you would like to see the results in your list view?
U error Logs says the solution.....
Caused by: java.lang.RuntimeException: You must call Parse.initialize(context, oauthKey, oauthSecret) before using the Parse library.
at com.parse.ParseUser.checkApplicationContext(ParseUser.java:1426)