Updating UI using AsyncTask - java

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

Related

convert array by split to integer

I get error :
FATAL EXCEPTION: main at java.lang.Integer.invalidInt
for this block :
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
MAIN CODE:
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
String[] c = data.split("limit");
int x = c.length;
if(x>1){
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
}
What is wrong?
Here is the stack trace:
FATAL EXCEPTION: main
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.tos.hidro.Terminal$2$1.run(Terminal.java:207)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

how to set a text in edit text field from JSON data

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());

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.

Music Player - Function doesn't work when trying to use objects

I am making a music player application for my Computing project. I got it working but found that using objects would get more more marks. As a result, I changed some of my code to incorporate the use of objects, but it doesn't work when I execute my application. Btw I am quite new to Java so it's possible I made a silly mistake.
When I used this code the function I tried to implement worked:
private void SongTitleEndTime(){
try {
TextViewSongTitle = (TextView)findViewById(R.id.songTitle);
if (id != 0 ){
String where = MediaStore.Audio.Media._ID + " = " + "'" + id + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media._ID.toString(), MediaStore.Audio.Media.ALBUM_ID.toString()}, where , null,
null);
mCursor.moveToFirst();
String title = mCursor.getString(0);
String artist = mCursor.getString(1);
String name = title + " - " + artist;
TextViewSongTitle.setText(name);
String fulltime;
albumfullid = Long.parseLong(mCursor.getString(3));
TextView EndTime = (TextView) findViewById(R.id.endtime);
long Minutes = TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration());
long Seconds = TimeUnit.MILLISECONDS.toSeconds(mMediaPlayer.getDuration()) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(mMediaPlayer.getDuration()));
if (Seconds < 10) {
String second = "0" + String.valueOf(Seconds);
fulltime = Minutes + ":" + second;
} else {
//else display as normal
fulltime = Minutes + ":" + Seconds;
}
EndTime.setText(fulltime);
//display the duration of song
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} //catch for errors
}
But when I tried this, I got an error:
Main Class:
private void SongTitleEndTime() {
try {
final TextView TextViewSongTitle = (TextView) findViewById(R.id.songTitle);
if (CurrentSongID != 0) {
final Song CurrentSong = new Song(CurrentSongID);
SongName = CurrentSong.SongName;
TextViewSongTitle.setText(SongName);
AlbumID = CurrentSong.AlbumID;
final TextView EndTime = (TextView) findViewById(R.id.endtime);
final String TotalSongDuration = CurrentSong.TotalDuration;
EndTime.setText(TotalSongDuration);
}
} catch (final IllegalArgumentException e) {
e.printStackTrace();
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
Object Class:
package com.example.music.test;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;
public class Song extends Activity {
private final String where;
public String SongName;
public long AlbumID;
public String TotalDuration;
public Song(final long SongID) {
where = MediaStore.Audio.Media._ID + " = " + "'" + SongID + "'";
final Cursor mCursor = managedQuery(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media._ID.toString(),
MediaStore.Audio.Media.ALBUM_ID.toString() }, where, null, null);
mCursor.moveToFirst();
final String SongTitle = getSongTitle(mCursor);
final String SongArtist = getSongArtist(mCursor);
SongName = SongTitle + " - " + SongArtist;
AlbumID = getAlbumID(mCursor);
TotalDuration = getTotalDuration();
}
public String getSongTitle(final Cursor mCursor) {
final String songtitle = mCursor.getString(0);
return songtitle;
}
public String getSongArtist(final Cursor mCursor) {
final String songartist = mCursor.getString(1);
return songartist;
}
public long getAlbumID(final Cursor mCursor) {
final long AlbumID = Long.parseLong(mCursor.getString(3));
return AlbumID;
}
public String getTotalDuration() {
String TotalTime;
final long Minutes = TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration());
final long Seconds = TimeUnit.MILLISECONDS
.toSeconds(Player.mMediaPlayer.getDuration())
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(Player.mMediaPlayer.getDuration()));
if (Seconds < 10) {
final String second = "0" + String.valueOf(Seconds);
TotalTime = Minutes + ":" + second;
} else {
TotalTime = Minutes + ":" + Seconds;
}
return TotalTime;
}
}
The error I get is:
01-02 21:55:41.941: E/AndroidRuntime(717): FATAL EXCEPTION: main
01-02 21:55:41.941: E/AndroidRuntime(717): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.music.test/com.example.music.test.Player}: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Handler.dispatchMessage(Handler.java:99)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.os.Looper.loop(Looper.java:137)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invokeNative(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): at java.lang.reflect.Method.invoke(Method.java:511)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-02 21:55:41.941: E/AndroidRuntime(717): at dalvik.system.NativeStart.main(Native Method)
01-02 21:55:41.941: E/AndroidRuntime(717): Caused by: java.lang.NullPointerException
01-02 21:55:41.941: E/AndroidRuntime(717): at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:91)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.managedQuery(Activity.java:1737)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Song.<init>(Song.java:21)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.SongTitleEndTime(Player.java:90)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.AllActivities(Player.java:80)
01-02 21:55:41.941: E/AndroidRuntime(717): at com.example.music.test.Player.onCreate(Player.java:66)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Activity.performCreate(Activity.java:5008)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-02 21:55:41.941: E/AndroidRuntime(717): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-02 21:55:41.941: E/AndroidRuntime(717): ... 11 more
Song is an Activity. Thus you can't call manageQuery before onCreate has been called. That's your error.

Crash while downloading file with AsyncTask

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

Categories

Resources