Working on a project with google maps in it.I am trying to retrieve bitmap images from a URL and it works fine ,but not all the time
The code i am using to retrieve the url is inside a async class.
The async class:
public class retrieveimage extends AsyncTask<String,Void,Void>
{
Store_data s;
MarkerOptions marker;
Bitmap pinbit;
public retrieveimage(Store_data s) {
this.s=s;
}
#Override
protected Void doInBackground(String... arg0) {
try {
marker = new MarkerOptions().position(new LatLng(Double.parseDouble(s.store_latitude),Double.parseDouble(s.store_longitude))).title(s.store_name);
String url1=arg0[0];
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap= BitmapFactory.decodeStream(input);
pinbit=bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
View custom_layout = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout,null);
ImageView iv_category_logo=(ImageView) custom_layout.findViewById(R.id.iv_category_logo);
pinbit=Bitmap.createScaledBitmap(pinbit,68,62,false);
iv_category_logo.setImageBitmap(pinbit);
//pinbit=MainActivity.getCroppedBitmap(pinbit, 10);
marker.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(StoreFinal.this, custom_layout)));
// adding marker
googleMap.addMarker(marker);
}
}
I am calling the async class as:
new retrieveimage(sobj).execute(URL_image+sobj.category+".png");
The problem is that the variable pinbit gets NPE randomly.Many times the desired result is seen.But sometimes out of random i get NPE.So i think there is something wrong with the doInBackground method where the web operation takes place.How do i ensure that the code with the web operation doesnt break?
The LOGCAT:
07-18 18:26:20.289: E/AndroidRuntime(27803): FATAL EXCEPTION: main
07-18 18:26:20.289: E/AndroidRuntime(27803): java.lang.NullPointerException
07-18 18:26:20.289: E/AndroidRuntime(27803): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:344)
07-18 18:26:20.289: E/AndroidRuntime(27803): at com.igloo.storelocater.StoreFinal$retrieveimage.onPostExecute(StoreFinal.java:177)
07-18 18:26:20.289: E/AndroidRuntime(27803): at com.igloo.storelocater.StoreFinal$retrieveimage.onPostExecute(StoreFinal.java:1)
07-18 18:26:20.289: E/AndroidRuntime(27803): at android.os.AsyncTask.finish(AsyncTask.java:417)
07-18 18:26:20.289: E/AndroidRuntime(27803): at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-18 18:26:20.289: E/AndroidRuntime(27803): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-18 18:26:20.289: E/AndroidRuntime(27803): at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 18:26:20.289: E/AndroidRuntime(27803): at android.os.Looper.loop(Looper.java:130)
07-18 18:26:20.289: E/AndroidRuntime(27803): at android.app.ActivityThread.main(ActivityThread.java:3689)
07-18 18:26:20.289: E/AndroidRuntime(27803): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 18:26:20.289: E/AndroidRuntime(27803): at java.lang.reflect.Method.invoke(Method.java:507)
07-18 18:26:20.289: E/AndroidRuntime(27803): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
07-18 18:26:20.289: E/AndroidRuntime(27803): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-18 18:26:20.289: E/AndroidRuntime(27803): at dalvik.system.NativeStart.main(Native Method)
Just try integrating AQuery library and use its callback method which will give you bitmap along with URL which it belongs. Hope it helps!
Related
I have a LinearLayout to which i populated other views using addview(); but when i try to get the height of the Linear layout, it returns 0.
I used ((LinearLayout)findViewById(R.id.linearId)).getHeight();
view i am adding, also has child views. How do i get the height of the Linearlayout including all the children?
EDIT -
actual code i used to adding view to my linear layout -
final ViewTreeObserver viewTreeObserver = earningsContainer.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
// read height with myLinearLayout.getHeight() etc.
Log.e(TAG, "$$$$$height "+earningsContainer.getHeight());
// remember to remove the listener if possible
if (viewTreeObserver.isAlive()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
viewTreeObserver.removeOnGlobalLayoutListener(this);
} else {
viewTreeObserver.removeGlobalOnLayoutListener(this);
}
}
}
});
earningsContainer.addView(getRowTaxEarningsTitle());
for (int i = 0; i < taxMainObject.getTaxEarnings().size(); i++) {
earningsContainer.addView(getTaxEarningsRow(taxMainObject
.getTaxEarnings().get(i)));
totalEarnings += taxMainObject.getTaxEarnings().get(i)
.getTotalAmount();
}
earningsContainer.addView(getTaxTotalRow("GROSS TOTAL SALARY",
totalEarnings + ""));
Stacktrace after using ViewTreeObserver -
07-18 13:40:59.936: E/AndroidRuntime(10058): FATAL EXCEPTION: main
07-18 13:40:59.936: E/AndroidRuntime(10058): Process: com.synthesize.paysal, PID: 10058
07-18 13:40:59.936: E/AndroidRuntime(10058): java.lang.IllegalStateException: This ViewTreeObserver is not alive, call getViewTreeObserver() again
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.ViewTreeObserver.checkIsAlive(ViewTreeObserver.java:720)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.ViewTreeObserver.removeOnGlobalLayoutListener(ViewTreeObserver.java:529)
07-18 13:40:59.936: E/AndroidRuntime(10058): at com.synthesize.paysal.TaxinfoActivity$1.onGlobalLayout(TaxinfoActivity.java:125)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.ViewTreeObserver.dispatchOnGlobalLayout(ViewTreeObserver.java:815)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1782)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.Choreographer.doFrame(Choreographer.java:544)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.os.Handler.handleCallback(Handler.java:733)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.os.Handler.dispatchMessage(Handler.java:95)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.os.Looper.loop(Looper.java:136)
07-18 13:40:59.936: E/AndroidRuntime(10058): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-18 13:40:59.936: E/AndroidRuntime(10058): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 13:40:59.936: E/AndroidRuntime(10058): at java.lang.reflect.Method.invoke(Method.java:515)
07-18 13:40:59.936: E/AndroidRuntime(10058): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-18 13:40:59.936: E/AndroidRuntime(10058): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-18 13:40:59.936: E/AndroidRuntime(10058): at dalvik.system.NativeStart.main(Native Method)
After adding a child to your LinearLayout it doesn't perform measure and layout immediately, so at that moment its size is still unknown. You need to wait for for a layout phase to know the dimensions.
You can do it by subclassing your LinearLayout and read it's size in onSizeChanged method etc.
OR you can achieve it without subclassing LinearLayout by setting a OnGlobalLayoutListener on ViewTreeObserver:
myLinearLayout = ((LinearLayout)findViewById(R.id.linearId);
and then add an OnGlobalLayoutListener right before adding your views:
myLinearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
// read height with myLinearLayout.getHeight() etc.
// remember to remove the listener if possible
ViewTreeObserver viewTreeObserver = myLinearLayout.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
viewTreeObserver.removeOnGlobalLayoutListener(this);
} else {
viewTreeObserver.removeGlobalOnLayoutListener(this);
}
}
}
});
mLinearLayout.addView(view);
I wrote an android program. This has multiple tab.. I want when I clicked a tab(Tab1), the tab's special view(GalleryDemoActivity.java) was shown.. But the Program has stopped working and does'nt work truly !
The code is:
src/Tab.java:
package com.AdMd.Plant;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Tabs extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.tabs);
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabSpec spec1=tabHost.newTabSpec("Tab 1");
Intent photosIntent = new Intent(this, GalleryDemoActivity.class);
spec1.setContent(photosIntent);
spec1.setIndicator("اطلاعات گیاه");
TabSpec spec2=tabHost.newTabSpec("Tab 2");
spec2.setIndicator("گالری تصاویر");
spec2.setContent(R.id.tab2);
TabSpec spec3=tabHost.newTabSpec("Tab 3");
spec3.setIndicator("گیاهان مشابه");
spec3.setContent(R.id.tab3);
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
}
}
The logcat messages are:
07-18 08:32:37.402: D/gralloc_goldfish(1068): Emulator without GPU emulation detected.
07-18 08:32:40.272: D/AndroidRuntime(1068): Shutting down VM
07-18 08:32:40.272: W/dalvikvm(1068): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
07-18 08:32:40.344: E/AndroidRuntime(1068): FATAL EXCEPTION: main
07-18 08:32:40.344: E/AndroidRuntime(1068): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.AdMd.Plant/com.AdMd.Plant.Tabs}: java.lang.IllegalStateException: Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.ActivityThread.access$600(ActivityThread.java:123)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.os.Looper.loop(Looper.java:137)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-18 08:32:40.344: E/AndroidRuntime(1068): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 08:32:40.344: E/AndroidRuntime(1068): at java.lang.reflect.Method.invoke(Method.java:511)
07-18 08:32:40.344: E/AndroidRuntime(1068): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-18 08:32:40.344: E/AndroidRuntime(1068): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-18 08:32:40.344: E/AndroidRuntime(1068): at dalvik.system.NativeStart.main(Native Method)
07-18 08:32:40.344: E/AndroidRuntime(1068): Caused by: java.lang.IllegalStateException: Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:680)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.widget.TabHost.setCurrentTab(TabHost.java:346)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.widget.TabHost.addTab(TabHost.java:236)
07-18 08:32:40.344: E/AndroidRuntime(1068): at com.AdMd.Plant.Tabs.onCreate(Tabs.java:32)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.Activity.performCreate(Activity.java:4465)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
07-18 08:32:40.344: E/AndroidRuntime(1068): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
07-18 08:32:40.344: E/AndroidRuntime(1068): ... 11 more
As you see in logcat, it said to me to have a activity Group, But when I use it, the program has some warning and it does'nt work again!
The warning are:
1.The method onCreate(Bundle) from the type ActivityGroup is deprecated
2.The type ActivityGroup is deprecated
What should I've done?
Thanks..
you have to provide action for every tab
just try this code
public class Tabs extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().hide();
setContentView(R.layout.tabs);
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
TabSpec spec1=tabHost.newTabSpec("Tab 1");
spec1.setIndicator("اطلاعات گیاه");
spec1.setContent(new Intent(this,GalleryDemoActivity.class));
TabSpec spec2=tabHost.newTabSpec("Tab 2");
spec2.setIndicator("گالری تصاویر");
spec2.setContent(new Intent(this,GalleryDemoActivity.class));
TabSpec spec3=tabHost.newTabSpec("Tab 3");
spec3.setIndicator("گیاهان مشابه");
spec3.setContent(new Intent(this,GalleryDemoActivity.class));
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
}
}
I am trying to create a custom marker in google maps.I want to add a custom layout as the marker
So i used the following code inside a webservice:
protected void onPostExecute(Void result) {
View custom_layout = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout,null);
ImageView iv_category_logo=(ImageView) custom_layout.findViewById(R.id.iv_category_logo);
pinbit=Bitmap.createScaledBitmap(pinbit,75,56,false);
iv_category_logo.setImageBitmap(pinbit);
//pinbit=MainActivity.getCroppedBitmap(pinbit, 10);
marker.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(getApplicationContext(), custom_layout)));
// adding marker
googleMap.addMarker(marker);
}
public static Bitmap createDrawableFromView(Context context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
But a classcastexception is shown in the following line:
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
The logcat is shown below:
07-18 16:08:07.617: E/AndroidRuntime(22114): FATAL EXCEPTION: main
07-18 16:08:07.617: E/AndroidRuntime(22114): java.lang.ClassCastException: android.app.Application
07-18 16:08:07.617: E/AndroidRuntime(22114): at com.igloo.storelocater.MainActivity.createDrawableFromView(MainActivity.java:610)
07-18 16:08:07.617: E/AndroidRuntime(22114): at com.igloo.storelocater.MainActivity$retrieveimage.onPostExecute(MainActivity.java:600)
07-18 16:08:07.617: E/AndroidRuntime(22114): at com.igloo.storelocater.MainActivity$retrieveimage.onPostExecute(MainActivity.java:1)
07-18 16:08:07.617: E/AndroidRuntime(22114): at android.os.AsyncTask.finish(AsyncTask.java:417)
07-18 16:08:07.617: E/AndroidRuntime(22114): at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-18 16:08:07.617: E/AndroidRuntime(22114): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-18 16:08:07.617: E/AndroidRuntime(22114): at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 16:08:07.617: E/AndroidRuntime(22114): at android.os.Looper.loop(Looper.java:130)
07-18 16:08:07.617: E/AndroidRuntime(22114): at android.app.ActivityThread.main(ActivityThread.java:3689)
07-18 16:08:07.617: E/AndroidRuntime(22114): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 16:08:07.617: E/AndroidRuntime(22114): at java.lang.reflect.Method.invoke(Method.java:507)
07-18 16:08:07.617: E/AndroidRuntime(22114): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
07-18 16:08:07.617: E/AndroidRuntime(22114): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-18 16:08:07.617: E/AndroidRuntime(22114): at dalvik.system.NativeStart.main(Native Method)
}
please help!!
The problem is in using of getApplicationContext() method. It is strongly recommended to avoid using it when you're working with some screen local stuff. See documentation for this method. It does not return an Activity object. I would suggest you to use inter-process communication (IPC) to pass data between your Service and Activity. One possible way is here. For another ways you can read Developers page.
I am developing app with Jsoup. The problem is it is not working when I am calling it from other class with the help of Getters. But it is running when I call it within Single Activity. I am not able to find why exactly it is not working, as it should.
Here are the logCat files with all the activities.
LogCat
11-14 20:16:52.063: E/AndroidRuntime(1871): FATAL EXCEPTION: AsyncTask #1
11-14 20:16:52.063: E/AndroidRuntime(1871): java.lang.RuntimeException: An error occured while executing doInBackground()
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.lang.Thread.run(Thread.java:856)
11-14 20:16:52.063: E/AndroidRuntime(1871): Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
11-14 20:16:52.063: E/AndroidRuntime(1871): at org.jsoup.Jsoup.connect(Jsoup.java:73)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
11-14 20:16:52.063: E/AndroidRuntime(1871): at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
11-14 20:16:52.063: E/AndroidRuntime(1871): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-14 20:16:52.063: E/AndroidRuntime(1871): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-14 20:16:52.063: E/AndroidRuntime(1871): ... 4 more
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(getApplicationContext(), LineGraph.class);
startActivity(i);
}
}
LineGraph
public class LineGraph extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsoupAct mJsoupAct = new jsoupAct();
String parseStrings;
parseStrings = mJsoupAct.getOutput();
Log.d("xstring", parseStrings + "");
}
}
jsoupAct
public class jsoupAct extends Activity {
String output = "00";
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
url = "www.google.com";
}
public void mExecute() {
new Parsee().execute();
}
public class Parsee extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
try {
Document doc = Jsoup.connect(url).get();
String body = doc.body().text();
output = body.toString();
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(output);
}
}
public String getOutput() {
mExecute();
return output;
}
public void setOutput(String output) {
this.output = output;
}
}
You are specifying the URL in a string local to the jsoupAct activity. The string will be null if you try to access from other Activities. To solve it move the string inside the AsyncTask class and it will work
Or add empty constructor to the jsonAct activity and assign the value of url in it. onCreate() is called only when to start an activity using the startActivity()
You have already answered your own question:
Caused by: java.lang.IllegalArgumentException: Must supply a valid URL
at org.jsoup.helper.Validate.notEmpty(Validate.java:102)
at org.jsoup.helper.HttpConnection.url(HttpConnection.java:57)
at org.jsoup.helper.HttpConnection.connect(HttpConnection.java:27)
at org.jsoup.Jsoup.connect(Jsoup.java:73)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:30)
at com.example.frgbdf.jsoupAct$Parsee.doInBackground(jsoupAct.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more
I'm getting a force close error when attempting to follow this tutorial:
http://www.bango29.com/go/blog/2011/android-asynctask-is-a-beauty-part-2
Any suggestions? I'm really not sure where I went wrong in this.
MY SOURCE:
public class HttpGetAndroidExample {
// The url of the website. This is just an example
private static final String webSiteURL = "http://www.supercars.net/gallery/119513/2841/5.html";
// The path of the folder that you want to save the images to
private static final String folderPath = "<FOLDER PATH>";
public static void main(String[] args) {
try {
// Connect to the website and get the html
Document doc = Jsoup.connect(webSiteURL).get();
// Get all elements with img tag ,
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
// for each element get the srs url
String src = el.absUrl("src");
System.out.println("Image Found!");
System.out.println("src attribute is : " + src);
getImages(src);
}
} catch (IOException ex) {
System.err.println("There was an error");
Logger.getLogger(HttpGetAndroidExample.class.getName()).log(Level.SEVERE,
null, ex);
}
}
private static void getImages(String src) throws IOException {
String folder = null;
// Exctract the name of the image from the src attribute
int indexname = src.lastIndexOf("/");
if (indexname == src.length()) {
src = src.substring(1, indexname);
}
indexname = src.lastIndexOf("/");
String name = src.substring(indexname, src.length());
System.out.println(name);
// Open a URL Stream
URL url = new URL(src);
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream(
folderPath + name));
for (int b; (b = in.read()) != -1;) {
out.write(b);
}
out.close();
in.close();
}
}
Logcat:
07-18 17:22:06.449: D/ActivityThread(11404): setTargetHeapUtilization:0.25
07-18 17:22:06.449: D/ActivityThread(11404): setTargetHeapIdealFree:8388608
07-18 17:22:06.449: D/ActivityThread(11404): setTargetHeapConcurrentStart:2097152
07-18 17:22:06.469: W/dalvikvm(11404): threadid=1: thread exiting with uncaught exception (group=0x41e1f438)
07-18 17:22:06.469: E/AndroidRuntime(11404): FATAL EXCEPTION: main
07-18 17:22:06.469: E/AndroidRuntime(11404): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.httpgetandroidexample/com.example.httpgetandroidexample.HttpGetAndroidExample}: java.lang.ClassCastException: com.example.httpgetandroidexample.HttpGetAndroidExample cannot be cast to android.app.Activity
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2012)
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2113)
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.app.ActivityThread.access$700(ActivityThread.java:139)
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.os.Looper.loop(Looper.java:137)
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.app.ActivityThread.main(ActivityThread.java:4918)
07-18 17:22:06.469: E/AndroidRuntime(11404): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 17:22:06.469: E/AndroidRuntime(11404): at java.lang.reflect.Method.invoke(Method.java:511)
07-18 17:22:06.469: E/AndroidRuntime(11404): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
07-18 17:22:06.469: E/AndroidRuntime(11404): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
07-18 17:22:06.469: E/AndroidRuntime(11404): at dalvik.system.NativeStart.main(Native Method)
07-18 17:22:06.469: E/AndroidRuntime(11404): Caused by: java.lang.ClassCastException: com.example.httpgetandroidexample.HttpGetAndroidExample cannot be cast to android.app.Activity
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
07-18 17:22:06.469: E/AndroidRuntime(11404): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2003)
07-18 17:22:06.469: E/AndroidRuntime(11404): ... 11 more
MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.httpgetandroidexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.httpgetandroidexample.HttpGetAndroidExample"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
There are two issues:
In manifest, you've declared the HttpGetAndroidExample class as an activity. Contradictory to that, the HttpGetAndroidExample class does not extend the Activiy class. So, its not an activity. That's why the exception HttpGetAndroidExample cannot be cast to android.app.Activity. Either extend it to be an Activity and create the required functions or remove it from the manifest if its not an activity.
Also, there is no where on the tutorial link I could see this class.