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.
Related
I am trying to change from one screen to another after a user has signed up. The user is created but I get a java.lang.NullPointerException when I call the view interface from the presenter.
Here is the part in the presenter that creates the user and prompts the change to a login screen.
public void signUp() {
postUserUseCase.setWyat_user(user);
subscription = postUserUseCase
.execute()
.subscribeOn(rx.schedulers.Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<User>() {
#Override
public void onCompleted() {
Log.d("complete","complete");
signUpView.showLoginScreen();
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(User user) {
Log.d("next",user.getEmail());
}
});
}
SignupActivity implements the view interface's showLoginScreen method.
public class SignUpActivity extends AppCompatActivity implements SignUpView {
#Override
public void showLoginScreen() {
Intent loginIntent = new Intent(this,LoginActivity.class);
startActivity(loginIntent);
}
}
The user is created but I get a null pointer onCompleted.
EDIT:
This is different from What is a NullPointerException, and how do I fix it? because if I did the initializing of an interface I get a whole class with the methods that my activity will override. This is a view interface not a variable or a class.I just want to call on method.
EDIT 2: Logcat for the error.
01-14 14:41:49.359 28309-28309/com.wyat.wyat E/AndroidRuntime: FATAL
EXCEPTION: main
java.lang.IllegalStateException: Fatal Exception thrown on
Scheduler.Worker thread.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:62)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
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:995)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
at dalvik.system.NativeStart.main(Native Method)
Caused by: rx.exceptions.OnCompletedFailedException
at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:90)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:272)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:207)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
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:995)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.wyat.wyat.accounts.presenters.SignUpPresenter$1.onCompleted(SignUpPresenter.java:92)
at rx.observers.SafeSubscriber.onCompleted(SafeSubscriber.java:84)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.checkTerminated(OperatorObserveOn.java:272)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.call(OperatorObserveOn.java:207)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
If wifi or mobile data is not enabled, it should ask the user, if he clicks yes in the AlertDialog, it will go to the settings.
This is inside main, on create, when the update button clicked:
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG,"ButtonUpdate clicked");
connectIfNecessary();
currentDate = Calendar.getInstance();
formatter= new SimpleDateFormat("yyyy-MM-dd");
new UpdateDB(MainActivity.this);
txtLastUpdateShow.setText(formatter.format(currentDate.getTime()));
});
This is connectifnecessary:
public void connectIfNecessary(){
Log.v(TAG, "main connectIfNecessary");
if(!isConnected()){
final Context ctx = this;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage("need internet");
builder.setTitle("do you want to enable it now?");
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
}
this is isConnected:
public boolean isConnected(){
Log.v(TAG, "mainisconnected");
ConnectivityManager conectivtyManager = (ConnectivityManager)
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (conectivtyManager.getActiveNetworkInfo() != null
&& conectivtyManager.getActiveNetworkInfo().isAvailable()
&& conectivtyManager.getActiveNetworkInfo().isConnected()) {
Log.v(TAG, "mainisconnected true");
return true;
} else {
Log.v(TAG, "mainisconnected false");
return false;
}
}
in updatedb constructor, it will call asynctask to connect websites.
When i run this, and click update button, it crashes because it goes into updatedb withpout asking me in builder. The errors:
FATAL EXCEPTION: AsyncTask #1
Process: com.cursedchico.IstanbulEventPool, PID: 13068
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:841)
Caused by: java.lang.NullPointerException
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:303)
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:109)
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:841)
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e17480 V.E..... R.....I. 0,0-488,216} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:902)
at com.cursedchico.IstanbulEventPool.MainActivity.connectIfNecessary(MainActivity.java:106)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:276)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e36258 V.E..... R......D 0,0-488,165} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.app.ProgressDialog.show(ProgressDialog.java:117)
at android.app.ProgressDialog.show(ProgressDialog.java:100)
at com.cursedchico.IstanbulEventPool.EventRetriever.onPreExecute(UpdateDB.java:269)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.cursedchico.IstanbulEventPool.UpdateDB.<init>(UpdateDB.java:56)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:280)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
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:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java:106) is builder.show()
MainActivity.java:276) connectIfNecessary();
I am getting errors for hours, at first about appcompat, then manifest then layout now this.
I use real tablet device.
When device is not connected , following would be execution flow
Get inside connectIfNecessary()
Create Alert to ask user to enable internet. Please note that only Alter object is created at this moment, it will be displayed on screen only after stack of main thread unwinds.
Return from connectIfNecessary() create instance of updateDB(). Inside this application is crashing
Few simple changes would fix your code.
add isConnected() if check before creating instance of updateDB(). This will cover the CONNECTED case
if the device is NOT CONNECTED, user will shown the alter and take to settings screen. If user enables WIFI from settings and comes back, onResume() of your activity will be called. Check connectivity and add updateDB() here.
Here is the code I had used but when I enter the page, it will automatically stopped. I have used volley request object and it does not support facebook login also. I have used custom list view valley for web service .
public void reload()
{
//final AlertDialog alertDialog = new AlertDialog.Builder(Editprofile.this).create();
Log.d("url23",url23);
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url23,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
String TAG = null;
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
/* String fn= obj.getString("Fname");
String ln= obj.getString("Lname");
String em= obj.getString("email");
String ph= obj.getString("phnum");
String lk= obj.getString("live");
String wr= obj.getString("work");
String de= obj.getString("describe");
Log.d("OUTPUT IS",fn);*/
fname.setText(obj.getString("Fname"));
lname.setText(obj.getString("Lname"));
/* email.setText(em,TextView.BufferType.EDITABLE);
phone.setText(ph,TextView.BufferType.EDITABLE);
live.setText(lk,TextView.BufferType.EDITABLE);
work.setText(wr,TextView.BufferType.EDITABLE);
desc.setText(de,TextView.BufferType.EDITABLE);*/
// adding movie to movies array
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String TAG="";
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
here is logcat error
10-29 08:21:34.953: D/(3631): [{"work":"software","id":76,"username":"admin123","phnum":"90000000000","image_src":"http:\/\/demo.cogzidel.com\/dropinn\/images\/no_avatar.jpg","email":"admin#gmail.com","Fname":"admin","describe":"developer","Lname":"admin123","live":"chennai"}]
10-29 08:21:34.953: D/OUTPUT IS(3631): admin
10-29 08:21:34.953: D/AndroidRuntime(3631): Shutting down VM
10-29 08:21:34.953: W/dalvikvm(3631): threadid=1: thread exiting with uncaught exception (group=0xb0d0cb20)
10-29 08:21:34.953: E/AndroidRuntime(3631): FATAL EXCEPTION: main
10-29 08:21:34.953: E/AndroidRuntime(3631): Process: info.androidhive.customlistviewvolley, PID: 3631
10-29 08:21:34.953: E/AndroidRuntime(3631): java.lang.NullPointerException
10-29 08:21:34.953: E/AndroidRuntime(3631): at com.example.dropinnnow.Editprofile$6.onResponse(Editprofile.java:690)
10-29 08:21:34.953: E/AndroidRuntime(3631): at com.example.dropinnnow.Editprofile$6.onResponse(Editprofile.java:1)
10-29 08:21:34.953: E/AndroidRuntime(3631): at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
10-29 08:21:34.953: E/AndroidRuntime(3631): at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
10-29 08:21:34.953: E/AndroidRuntime(3631): at android.os.Handler.handleCallback(Handler.java:733)
10-29 08:21:34.953: E/AndroidRuntime(3631): at android.os.Handler.dispatchMessage(Handler.java:95)
10-29 08:21:34.953: E/AndroidRuntime(3631): at android.os.Looper.loop(Looper.java:136)
10-29 08:21:34.953: E/AndroidRuntime(3631): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-29 08:21:34.953: E/AndroidRuntime(3631): at java.lang.reflect.Method.invokeNative(Native Method)
10-29 08:21:34.953: E/AndroidRuntime(3631): at java.lang.reflect.Method.invoke(Method.java:515)
10-29 08:21:34.953: E/AndroidRuntime(3631): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-29 08:21:34.953: E/AndroidRuntime(3631): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-29 08:21:34.953: E/AndroidRuntime(3631): at dalvik.system.NativeStart.main(Native Method)
Try this, hope it helps you,
fname.setText(obj.getString("Fname").toString());
lname.setText(obj.getString("Lname").toString());
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
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