Crash while downloading file with AsyncTask - java

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

Related

App Crashes on Splash Screen throwing Null Pointer

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 = "";
}
}

Android Looper thread crashes with NullPointerException

I'm trying to get a looper thread to work but despite all attempts, it crashes. I'm not using the HandlerThread class, as I'm doing quite a bit of 802.11 related stuff in the thread itself and posting Runnables with lots of duplicate code doesn't seem to be the right way to go here.
Here the skeleton of the looper thread class:
public class WiFiScanner extends Thread {
Looper mLooper;
Handler mHandler;
#Override
public void run() {
Looper.prepare();
synchronized(this) {
mLooper = Looper.myLooper();
notifyAll();
}
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
..... // message parsing
}
}
}
/* waits for Looper initialization */
public boolean waitForLooper() {
synchronized(this) {
while(mLooper == null) {
try {
wait();
} catch (InterruptedException e) {}
}
}
return true;
}
}
and the code initializing it in the main activity:
wifiScanner = new WiFiScanner(
... // callback stuff
);
wifiScanner.start();
wifiScanner.waitForLooper();
wifiScanner.initialize();
initialize is a simple function in the WiFiScanner class, posting a message bundle to the message queue:
public void initialize() {
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
WiFiMsg msgId = WiFiMsg.INITIALIZE;
b.putSerializable("msgId", msgId);
msg.obj = b;
mHandler.sendMessage(msg);
}
Despite waitForLooper() returning successfully, the call to initialize() causes a null pointer exception. I assume the looper isn't really in a state to have message dispatched into the queue as a static delay of 500ms between waitForLooper() and initialize() circumvents this issue.
Any ideas on how to fix this in a reasonably elegant way?
PS: Now by popular demand, a stack trace:
E/AndroidRuntime( 3178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime( 3178): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime( 3178): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 3178): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime( 3178): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 3178): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 3178): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime( 3178): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3178): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime( 3178): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime( 3178): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 3178): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3178): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3178): at de.uni_leipzig.informatik.rvs.videodownload.wifi.WiFiScanner.initialize(WiFiScanner.java:204)
E/AndroidRuntime( 3178): at de.uni_leipzig.informatik.rvs.videodownload.MainActivity.onCreate(MainActivity.java:270)
E/AndroidRuntime( 3178): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime( 3178): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime( 3178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
E/AndroidRuntime( 3178): ... 11 more
Your notify should be after mHandler is set, not mLooper - since your NPE is on mHandler.

Unable to start activity ComponentInfo; trying to create splash screen

I recently added a splash screen to my Android application to mask the loading of a JSON file, but my app crashes after finishing parsing. I've commented out and uncommented out code until I found the problematic segment, but I'm not sure why it isn't working.
The code works if I comment out the for loop from this code segment.
From MagazinePagesActivity.java:
public void loadItems() {
for (Item item : SplashActivity.downloadedItems) {
Post post = (Post) item;
for (String tag : post.tags) {
if (tag.equals(this.tag)) {
// loader.loadImage(magazine.imageURL, new
// SimpleImageLoadingListener());
Bundle bundle = new Bundle();
bundle.putString("title", post.title);
bundle.putString("article", post.article);
bundle.putString("imageURL", post.imageURL);
MagazineFragment cover = new MagazineFragment();
cover.setArguments(bundle);
coverAdapter.addNewItem(cover);
}
}
}
setContentView(vp);
}
At first, I thought it was because SplashActivity.downloadedItems wasn't properly defined, but it looks fine to me:
From SplashActivity.java:
public static ArrayList<Item> downloadedItems = new ArrayList<Item>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new RetreiveJSONTask() {
protected void onPostExecute(String JSON)
{
Log.d("SplashActivity", "Beginning parsingJSON" );
downloadedItems = parseJSON ( JSON );
Log.d("SplashActivity", "Finished parsingJSON" );
Log.d("SplashActivity", "" + SplashActivity.downloadedItems.isEmpty());
Intent i = new Intent(SplashActivity.this, MagazinePagesActivity.class);
startActivity(i);
// Closes the splash screen
finish();
}
}.execute(sourceURL());
}
From LogCat:
10-16 19:23:12.602: D/AndroidRuntime(828): Shutting down VM
10-16 19:23:12.602: W/dalvikvm(828): threadid=1: thread exiting with uncaught exception (group=0x41465700)
10-16 19:23:12.632: E/AndroidRuntime(828): FATAL EXCEPTION: main
10-16 19:23:12.632: E/AndroidRuntime(828): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bruinfootball/com.dailybruin.bruinframework.channels.StoryListActivity}: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:99)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:137)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:525)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-16 19:23:12.632: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.JSONItemsActivity.onCreate(JSONItemsActivity.java:20)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryItemsActivity.onCreate(StoryItemsActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.onCreate(StoryListActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Activity.performCreate(Activity.java:5133)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-16 19:23:12.632: E/AndroidRuntime(828): ... 11 more
Not sure if it helps, but both SplashActivity and MagazinePagesActivity extend JSONItemsActivity, separately.
Thanks in advance for any help! I'm fairly new to Android, so please bear with me.
Edit: That's odd, the debug statement I put to check if the ArrayList is empty returns true, but another debug statement within parseJSON shows that things are being added. My parseJSON method:
public ArrayList<Item> parseJSON(String jsonString) {
ArrayList<Item> magazines = new ArrayList<Item>();
JSONArray jArray;
try {
jArray = new JSONArray(jsonString);
JSONObject jObject;
JSONObject image;
String img;
String title;
String subtitle;
int commentCount;
String content;
String date;
String ID;
String slug;
JSONArray array;
String[] tags;
for (int i = 0; i < jArray.length(); i++) {
jObject = jArray.getJSONObject(i);
img = jObject.getString("tall_image_url");
if (img.equals(""))
img = jObject.getString("image_url");
if (img.equals("") && !jObject.isNull("poster_image")) {
image = jObject.getJSONObject("poster_image");
img = image.getString("name");
}
title = jObject.getString("title");
subtitle = jObject.getString("subtitle");
commentCount = jObject.getInt("comment_count");
content = jObject.getString("content_html");
date = jObject.getString("creation_date");
ID = jObject.getString("id");
slug = jObject.getString("slug");
array = jObject.getJSONArray("tags_list");
tags = new String[array.length()];
for (int j = 0; j < array.length(); j++) {
tags[j] = array.getString(j);
}
for (String tag : tags) {
if (tag.equals(this.tag))
{
Post additive = new Post(img, title, subtitle,
commentCount, content, date, ID, slug, tags);
magazines.add(additive);
Log.d("SplashActivity", additive.toString());
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return magazines;
}
StoryListActivity line 27:
public void loadItems() {
(findViewById(R.id.progress_bar)).setVisibility(View.GONE);
getSupportFragmentManager().beginTransaction()
.replace(R.id.loading, new StoryListFragment()).commit();
}
StoryItemsActivity (MagazinePagesActivity and StoryListActivity extend this class; this class extends JSONItemsActivity, which SplashActivity also extends):
package com.dailybruin.bruinframework.channels;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.dailybruin.bruinframework.R;
import com.dailybruin.bruinframework.base.BaseActivity;
import com.dailybruin.bruinframework.base.URLBuilder;
import android.os.Bundle;
public abstract class StoryItemsActivity extends JSONItemsActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public String sourceURL()
{
return URLBuilder.getPostsURL(getString(R.string.slug));
}
public ArrayList<Item> parseJSON(String jsonString) {
// Using pre-downloaded and parsed JSON
return SplashActivity.downloadedItems;
}
}
Check this part of the code. Line number 27. That is null and hence causing NPE.
Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)

Send a string to a servlet from android

I am trying to send a string from a android application to a servlet and then retrieve that string to my android application ,but when i try to invoke the servlet it force close on me
and i dont know why (im very new to android and this is a practice exercise for me)
here is my android simple app:
ANDROID
package com.theopentutorials.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static String request = "kjo ishte e gjitha";
public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
and here is my simple servlet
SERVLET
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String par1 = request.getParameter("param1");
PrintWriter out = response.getWriter();
out.println(par1);
}
}
And the logcat log error says
01-10 13:36:50.014: E/AndroidRuntime(1187): FATAL EXCEPTION: AsyncTask #1
01-10 13:36:50.014: E/AndroidRuntime(1187): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.lang.Thread.run(Thread.java:856)
01-10 13:36:50.014: E/AndroidRuntime(1187): Caused by: java.lang.NullPointerException: lock == null
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.Reader.<init>(Reader.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.getOutputFromUrl(HttpGetServletActivity.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:54)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:1)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-10 13:36:50.014: E/AndroidRuntime(1187): ... 4 more
doest somebody have any idea ?
Thank you for your help in advance !
Have a nice day!
You need to add the internet access permission
<uses-permission android:name="android.permission.INTERNET"/>
I found that you should use the URLEncoder to encode the url because your url contains spaces. Please check http://developer.android.com/reference/java/net/URLEncoder.html
You have forgot to set param1 from your android app.
connection.setRequestProperty("param1", "Your String Value");
then you will get the value back as response from Servlet.

Updating UI using AsyncTask

I am trying to implement a login after is shown progressbar but it shows an erro.Below is the code I am using
class PostService extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String s = UserFunctions.response;
Log.d(Details.TAG, "checking i response...");
UserFunctions.basicLogin(email, password);
Log.d(Details.TAG,
s + " " + UserFunctions.basicLogin(email, password));
return s;
}
Intent i;
#Override
protected void onPostExecute(String r) {
// TODO Auto-generated method stub
super.onPostExecute(UserFunctions.response);
Log.d(Details.TAG, "Password Point");
if(UserFunctions.basicLogin(email, password)){
i = new Intent("com.example.eve_haps.DASHBOARDACTIVITY");
startActivity(i);
}else {
Toast.makeText(MainActivity.this,
"Login UnSuccesful. Check email and/or password",
Toast.LENGTH_SHORT).show();
}
}
}
But it returns an error log
E/AndroidRuntime( 7465): FATAL EXCEPTION: main
E/AndroidRuntime( 7465): java.lang.StringIndexOutOfBoundsException: length=0; regionStart=0; regionLength=17
E/AndroidRuntime( 7465): at java.lang.String.startEndAndLength(String.java:593)
E/AndroidRuntime( 7465): at java.lang.String.substring(String.java:1474)
E/AndroidRuntime( 7465): at com.example.eve_haps.UserFunctions.basicLogin(UserFunctions.java:107)
E/AndroidRuntime( 7465): at com.example.eve_haps.MainActivity$PostService.onPostExecute(MainActivity.java:105)
E/AndroidRuntime( 7465): at com.example.eve_haps.MainActivity$PostService.onPostExecute(MainActivity.java:1)
E/AndroidRuntime( 7465): at android.os.AsyncTask.finish(AsyncTask.java:602)
E/AndroidRuntime( 7465): at android.os.AsyncTask.access$600(AsyncTask.java:156)
E/AndroidRuntime( 7465): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
E/AndroidRuntime( 7465): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 7465): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 7465): at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime( 7465): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 7465): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 7465): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime( 7465): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime( 7465): at dalvik.system.NativeStart.main(Native Method)
Below is the code for implementing the login
public static boolean basicLogin(String email, String password) {
String msg = "Login successful";
boolean status = false;
String url;
String links[] = {
"..." + "?user=",
"..." + "?actn=login"
+ "&user=" };
auth_link = links[0]+email + "&password=" + password;
response = Connect.doHTTPGet(auth_link);
// result = getHttpResponse(url);
Log.d(Details.TAG, " " + msg.length() + " " + UserFunctions.response.substring(0, 17) + " "+ UserFunctions.response.substring(0, 17).length() );
if (UserFunctions.response.substring(0, 17).trim().equals(msg)) {
Log.d(Details.TAG, " " + msg.length() + " " + UserFunctions.response.substring(0, 17));
status = true;
}
Log.d(Details.TAG, " " + "Connection Test"
+ UserFunctions.response);
return status;
Please what is the error. I would reply appreciate it

Categories

Resources