protected String doInBackground(String... params) {
int progress = 0;
publishProgress(progress += 10);
String[] link_list = new String[100];
Bitmap bmp ;
Document xmlDoc = Jsoup.parse(url, 3000);
Elements title = xmlDoc.select("div[class=meta]");
title_lenth = title.size();
for (int i = 0; i < title_lenth; i++) {
link_list[count] = title.get(i).text();
try{
JSONObject JObj_link ;
JObj_link = new JSONObject(link_list[count]);
link_list[count] = JObj_link.getString("ou");
Log.e("ou Content", link_list[count]);
}catch (Exception e){
Log.e("ou Content", e.toString());
}
System.out.print(titlelist[count]);
count ++ ;
}
setBmp(link_list);
publishProgress(progress += 15);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
publishProgress(progress = 100);
return title_word;
}
I deleted some code Not critical
I want to do
-> setBmp(link_list);
link_list is a string array content urls (http://xxx.xx.jpg)
the setbmp can download pics and set imageview
now there is error messages
Logcat :
03-10 09:32:23.461 16218-16493/com.takepickpicturedemo E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.takepickpicturedemo, PID: 16218
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:942)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:5081)
at android.view.View.invalidateInternal(View.java:12713)
at android.view.View.invalidate(View.java:12677)
at android.view.View.invalidate(View.java:12661)
at android.widget.AbsListView.resetList(AbsListView.java:1996)
at android.widget.GridView.setAdapter(GridView.java:194)
at com.takepickpicturedemo.MainActivity.setBmp(MainActivity.java:741)
at com.takepickpicturedemo.MainActivity$GetPredict.doInBackground(MainActivity.java:582)
at com.takepickpicturedemo.MainActivity$GetPredict.doInBackground(MainActivity.java:497)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
edit
so ..
Main thread cannot do Network
doInBackground cannot setting UI
How can I do to download & change UI
As I see, setBmp() method calls a UI update. A UI update should occur in the UI thread. You should know that doInBackground occurs in a background thread and not the UI thread.
Instead of calling it in the doInBackground method, try calling setBmp() from onPostExecute method of the AsyncTask.
NOTE: onPostExecute method is executed in the UI thread.
Error occurs because setBmp() somehow affects views, which is not allowed on other threads than UI thread. Wrappping it with runOnUiThread() will help. Replace the line
setBmp(link_list);
by:
runOnUiThread(new Runnable() {
#Override
public void run() {
setBmp(link_list);
}
});
To make it work, you also should make link_list final on creation:
final String[] link_list = new String[100]; // "final" added
Here is you setBmp(link_list); Method. May be this Method Try to show Image. **doInBackground** method do not created a view.
Thanks
Related
I am trying to use BackgroundMode.disableWebViewOptimizations(); in my ionic app but when i launch the app in the android studio then i am getting this error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.siloc.users, PID: 6275
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.View org.apache.cordova.CordovaWebViewEngine.getView()' on a null object reference
at de.appplant.cordova.plugin.background.BackgroundModeExt$1.lambda$run$0$BackgroundModeExt$1(BackgroundModeExt.java:169)
at de.appplant.cordova.plugin.background.-$$Lambda$BackgroundModeExt$1$ENae6xHnDD7pQOdOSwld6cT0QNo.run(Unknown Source:2)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:230)
at android.app.ActivityThread.main(ActivityThread.java:7880)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:526)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
E/NetdClient: querySockNetidForUid nid:0, uid:10357, command.cmdId:11, id:0
This is the function in BackgroundModeExt.java file
private void disableWebViewOptimizations() {
Thread thread = new Thread(){
public void run() {
try {
Thread.sleep(1000);
getApp().runOnUiThread(() -> {
View view = webView.getEngine().getView();
try {
Class.forName("org.crosswalk.engine.XWalkCordovaView")
.getMethod("onShow")
.invoke(view);
} catch (Exception e){
view.dispatchWindowVisibilityChanged(View.VISIBLE);
}
});
} catch (InterruptedException e) {
// do nothing
}
}
};
thread.start();
}
iS there any way i can solve this problem?
Change line: View view = webView.getEngine().getView(); to View view = webView.getView();
I have an app that downloads the current unix timestamp from the internet. The code for the download task is as follows.
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
}
return null;
}
I run this code in onCreate
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.currenttimestamp.com/").get();
Pattern p = Pattern.compile("current_time = (.*?);");
Matcher m = p.matcher(result);
m.find();
String unixTime = (m.group(1));
timeStamp = Integer.parseInt(unixTime);
endTimeMaths = endTime/1000;
} catch (InterruptedException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
} catch (ExecutionException e) {
e.printStackTrace();
Toast.makeText(SplashActivity.this, "you aint got no internet man", Toast.LENGTH_SHORT).show();
}
timeDelta = timeStamp-endTimeMaths;
Log.i("TimeDelta", timeDelta+"");
//If dem boys cheatin
if (timeDelta < 1){
Toast.makeText(SplashActivity.this, "You cheatin boi?", Toast.LENGTH_SHORT).show();
reward=false;
} else if (timeDelta >= 300){
reward = true;
Toast.makeText(SplashActivity.this, "Here is your reward for being gone", Toast.LENGTH_SHORT).show();
}
}
The Exception is as follows
09-04 21:26:42.853 8459-8493/com.firefluxentertainment.retroclicker E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.firefluxentertainment.retroclicker, PID: 8459
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:155)
at com.firefluxentertainment.retroclicker.SplashActivity$DownloadTask.doInBackground(SplashActivity.java:119)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Since all the code is in try catch braces I have no idea why it would be crashing. Any help is very much appreciated!
This is because you are trying to show toast in a non-UI thread. There are multiple solutions to your problem :
Create a handler in the Activity and pass it along to DownloadTask. Simply send a message in Handler and show the toast.
Another solution is to send the context in DownloadTask and show the toast as
context.runOnUIThread(new Runnable() {
public void run(){
Toast.showToast("your message here")
}
)
You can send the result of your task in onPostExecute() and show Toast there.
I have activity A and B. Both of them have AsyncTasks that connect to the web and fetch some JSON. I get an error that I can't quite replicate always, but I'm not sure what I'm doing wrong. I get the error when I press the back button from activity B to A to Homescreen.
protected Void doInBackground(Void... params) {
synchronized (this) {
if (img_flag == 1) {
System.out.println("entered into doinback1");
UploadImage();
System.out.println("entered into doinback2");
}
if (offlineast_flag == 0) {
System.out.println("entered into doinback3");
UpdateAsset_webService();
System.out.println("entered into doinback4");
ServiceRequest _autoupdate = new ServiceRequest();
_autoupdate.cat_sync(Update_asset.this, _companyId, _usrid,
access_id, profile_id, catid_db);
System.out.println("entered into doinback5");
}
if (img_flag == 2) {
System.out.println("entered into doinback6");
UploadImageOffline();
} else {
System.out.println("entered into doinback7");
loading_dialog.dismiss();
System.out.println("entered into doinback8");
}
}
return null;
}
// Update the progress
protected void onProgressUpdate(Integer... values) {
}
// after executing the code in the thread
protected void onPostExecute(Void result) {
onback();
loading_dialog.dismiss();
img_flag = 0;
Toast.makeText(getApplicationContext(),
"Your asset updated successfully.", Toast.LENGTH_LONG)
.show();
}
This is my Logcat:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.Futuenter code herereTask.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.kodology.assetbin.Update_asset.UpdateAsset_webService(Update_asset.java:1733)
at com.kodology.assetbin.Update_asset$LoadViewTask.doInBackground(Update_asset.java:2239)
at com.kodology.assetbin.Update_asset$LoadViewTask.doInBackground(Update_asset.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
... 4 more
I’m having a navigation drawer for my app that contains a menu with which I can navigate between the fragments. The first fragment that i get after the app lunch is the Home which contains a listView and a footer attached in the bottom (is just for the test). The problem is when I lunch the Home fragment for the first time nothing happen and its work very well, but when I change the fragments from the navigation drawer and trying to get back the home fragment the app crash. The error log show me a null pointer Exception. Thes is my code detail
onCreateView method
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
try {
v = inflater.inflate(R.layout.fragment_homes, container, false);
listView = (ListView) v.findViewById(R.id.homeList);
l = new HomeListAdapter(this, homeList);
if(l == null)
Log.i("tag","null");
listView.setAdapter(l);
} catch (InflateException e) {
}
return v;
}
onPostExecute method
#Override
protected void onPostExecute(final String res) {
/*try {
jObj = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
/* JSONArray j = null;
try {
j = new JSONArray(res);
} catch (JSONException e) {
e.printStackTrace();
}*/
// Parsing json
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition");
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
l.notifyDataSetChanged();
//pDialog.hide();
}
The error log
10-10 09:31:30.884 2447-2447/com.example.user.unchained E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user.unchained, PID: 2447
java.lang.NullPointerException
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:375)
at com.example.user.unchained.HomesActivity$PlaceholderFragment$FeedsTask.onPostExecute(HomesActivity.java:277)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
And this is exactly the line that cause the error : l.notifyDataSetChanged();. I notice that the error is just in the case when i'm trying to display the fragment for the secode time.
So any help please ? Thanks !
You need to use this in doInBackground.
#Override
protected Void doInBackground(void... ) {
try {
for (int i = 0; i < 5; i++) {
//JSONObject obj = j.getJSONObject(i);
Home home = new Home();
//String photoNews = java.net.URLDecoder.decode(obj.getString("photonews"), "UTF-8");
home.setNomC("Karim Ennassiri");
home.setPhotoP("http://i1239.photobucket.com/albums/ff509/FestusMANAFEST/iker-casillas20Wallpaper__yvt2.jpg");
home.setPhotoAr("http://voyage-essaouira-maroc.com/upload/apostrophe_image_(13).jpg");
home.setText("Chlada V2.0 Edition"); //give some other name in getter setter for setText in Home.java. It makes not to understand whether you are using setText for textview assigning.
home.setNbrSick("5");
home.setNbrComm("8");
home.setNbrShare("0");
homeList.add(home);
}
postExecute is used to display UI. don't perform heavy operation like parsing in PostExecute.
I am creating an RSS reader application for android 4.0+. I have put the reader code in AsyncTask because of the NetworkOnMainThreadException. The code almost works fine, however one line has an error. This is my code:
Java code:
private class PostTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url=params[0];
headlines = new ArrayList();
links = new ArrayList();
//Download and parse xml feed
headlines = new ArrayList();
links = new ArrayList();
try {
URL url1 = new URL("http://feeds.pcworld.com/pcworld/latestnews");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url1), "UTF_8");
/* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
* However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
* As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
* so we should skip the "<title>" tag which is a child of "<channel>" tag,
* and take in consideration only "<title>" tag which is a child of "<item>"
*
* In order to achieve this, we will make use of a boolean variable.
*/
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
headlines.add(xpp.nextText()); //extract the headline
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); //extract the link of article
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next(); //move to next element
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Feed parsed!";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
}
in this code snippet i get an error:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Binding data
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
Error: The constructor ArrayAdapter(MainActivity.PostTask, int, List) is undefined.
Logcat:
01-26 20:55:53.811: E/AndroidRuntime(1830): FATAL EXCEPTION: AsyncTask #1
01-26 20:55:53.811: E/AndroidRuntime(1830): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.lang.Thread.run(Thread.java:856)
01-26 20:55:53.811: E/AndroidRuntime(1830): Caused by: java.lang.IllegalArgumentException
01-26 20:55:53.811: E/AndroidRuntime(1830): at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1615)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:343)
01-26 20:55:53.811: E/AndroidRuntime(1830): at com.mysoftware.mysoftwareos.mobile.MainActivity$PostTask.doInBackground(MainActivity.java:1)
01-26 20:55:53.811: E/AndroidRuntime(1830): at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-26 20:55:53.811: E/AndroidRuntime(1830): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-26 20:55:53.811: E/AndroidRuntime(1830): ... 5 more
Could anyone please look into my problem and come up with a solution? Or tell me if i should do anything different? Thanks a lot!
Change it to:
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, headlines);
this refers to the AsyncTask, so you have to explicitly reference MainActivity's this.
use Activity Context instead of AsyncTask to Create ArrayAdapter inside onPostExecute method as :
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(Your_Current_Activity.this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
EDIT :
after log posted also change
xpp.setInput(getInputStream(url1), "UTF_8");
to
xpp.setInput(url1.openConnection().getInputStream(), "UTF_8");