storing images from internet locally on Android - java

I need to store locally on android devices some images I get from the internet for faster display later
I wrote this code , I don't get any exceptions, however when I try to reload images, I get a FileNotFoundException
public String md5(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest
.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public boolean saveImage() {
fileName = this.md5(fullURL);
URL ulrn = new URL(fullURL);
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream is = con.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(is);
File f = new File(cacheImagePath, filename); // cacheImagePath is
// /data/data/com.mycompany.myapp/cache/
try {
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
bm.compress(Bitmap.CompressFormat.JPEG, 92, out);
out.flush();
out.close();
return true;
} catch (Exception e) {
Log.e("Exception", "saveImage " + filename);
e.printStackTrace();
return false;
}
}
Edit :
LogCat errors while trying to access the file :
06-20 14:39:11.965: W/System.err(560): java.io.FileNotFoundException: /data/data/com.accessdev.tellmeplus/cache/files/tagpromo-d3d908befad2892c35f3ba957d5c18 (No such file or directory)
06-20 14:39:11.965: W/System.err(560): at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
06-20 14:39:11.965: W/System.err(560): at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
06-20 14:39:11.965: W/System.err(560): at java.io.FileInputStream.<init>(FileInputStream.java:80)
06-20 14:39:11.965: W/System.err(560): at java.io.FileInputStream.<init>(FileInputStream.java:132)
06-20 14:39:11.965: W/System.err(560): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:362)
06-20 14:39:11.965: W/System.err(560): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:412)
06-20 14:39:11.965: W/System.err(560): at com.accessdev.tellmeplus.TMPOfferImageAdapter.createBitmap(TMPOfferImageAdapter.java:124)
06-20 14:39:11.970: W/System.err(560): at pl.polidea.coverflow.AbstractCoverFlowImageAdapter.getItem(AbstractCoverFlowImageAdapter.java:70)
06-20 14:39:11.970: W/System.err(560): at pl.polidea.coverflow.AbstractCoverFlowImageAdapter.getView(AbstractCoverFlowImageAdapter.java:111)
06-20 14:39:11.970: W/System.err(560): at pl.polidea.coverflow.AbstractCoverFlowImageAdapter.getView(AbstractCoverFlowImageAdapter.java:1)
06-20 14:39:11.970: W/System.err(560): at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:192)
06-20 14:39:11.970: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.970: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.970: W/System.err(560): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
06-20 14:39:11.970: W/System.err(560): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
06-20 14:39:11.970: W/System.err(560): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
06-20 14:39:11.970: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.975: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.975: W/System.err(560): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-20 14:39:11.975: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.975: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.975: W/System.err(560): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-20 14:39:11.975: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.975: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.975: W/System.err(560): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-20 14:39:11.975: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.975: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.975: W/System.err(560): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
06-20 14:39:11.975: W/System.err(560): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
06-20 14:39:11.975: W/System.err(560): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
06-20 14:39:11.980: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.980: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.980: W/System.err(560): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-20 14:39:11.980: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.980: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.980: W/System.err(560): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-20 14:39:11.980: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.980: W/System.err(560): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
06-20 14:39:11.980: W/System.err(560): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
06-20 14:39:11.985: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.985: W/System.err(560): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
06-20 14:39:11.985: W/System.err(560): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
06-20 14:39:11.985: W/System.err(560): at android.view.View.measure(View.java:8366)
06-20 14:39:11.985: W/System.err(560): at android.view.ViewRoot.performTraversals(ViewRoot.java:847)
06-20 14:39:11.985: W/System.err(560): at android.view.ViewRoot.handleMessage(ViewRoot.java:1868)
06-20 14:39:11.985: W/System.err(560): at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 14:39:11.985: W/System.err(560): at android.os.Looper.loop(Looper.java:130)
06-20 14:39:11.990: W/System.err(560): at android.app.ActivityThread.main(ActivityThread.java:3691)
06-20 14:39:11.990: W/System.err(560): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 14:39:11.990: W/System.err(560): at java.lang.reflect.Method.invoke(Method.java:507)
06-20 14:39:11.990: W/System.err(560): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
06-20 14:39:11.990: W/System.err(560): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
06-20 14:39:11.990: W/System.err(560): at dalvik.system.NativeStart.main(Native Method)

here is the code
try {
URL url = new URL(image_URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory().toString();
Log.v("LOG_TAG", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = image.jpg;
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
// Toast.makeText(this, "Downloaded Successfully", 600).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
put permissions in the manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this will store the image on sd card and then u can load it faster in your application.

You try to create a new file with f.createNewFile() but you don't create the directory.
do new File(cacheImagePath).mkdirs()

Related

How to store a single row data into a string array of sqlite database in android

I have called a function returnCurrentNameById() by passing the id of the particular row. But it gives an error.
String[] s1;
public String[] returnCurrentNameById(int k) throws SQLException{
String[] columns = new String[]{ KEY_ID1, KEY_NAME, Key_DOB, KEY_AGE, KEY_PHONE_NO, Key_EXPERIENCE, KEY_EMAIL, KEY_STATUS, KEY_STATUS};
SQLiteDatabase db3 = this.getReadableDatabase();
Cursor c = db3.query(DATA_BASE_TABLE_NAME1, columns, KEY_ID1 + "=" + k, null, null, null, null);
if (c != null){
c.moveToFirst();
for(int i = 0; i<=8; i++){
s1[i] = c.getString(i);
}
return s1;
}
return null;
}
The Log cat error report is:
02-15 16:38:13.424 1545-1545/world.com.my`enter code here`progect09 D/AndroidRuntime﹕ Shutting down VM
02-15 16:38:13.464 1545-1545/world.com.myprogect09 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x2bc9a300)
02-15 16:38:13.533 1545-1545/world.com.myprogect09 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3591)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.view.View$1.onClick(View.java:3586)
            at android.view.View.performClick(View.java:4084)
            at android.view.View$PerformClick.run(View.java:16966)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            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:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at world.com.myprogect09.DataBaseSQL.returnCurrentNameById1(DataBaseSQL.java:209)
at world.com.myprogect09.ThirdActivity.isClicked(ThirdActivity.java:74)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at android.view.View$1.onClick(View.java:3586)
            at android.view.View.performClick(View.java:4084)
            at android.view.View$PerformClick.run(View.java:16966)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            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:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
02-15 16:38:34.491 1545-1545/world.com.myprogect09 I/Process﹕ Sending signal. PID: 1545 SIG: 9
You have not initialized your s1 array.
Use
s1 = new String[9];
to allocate an array of 9 elements.
Also check the return value of moveToFirst() so you don't get an exception in case the query returns no rows.
Replace
Cursor c = db3.query(DATA_BASE_TABLE_NAME1, columns, KEY_ID1 + "=" + k, null, null, null, null);
with
Cursor c = db3.query(DATA_BASE_TABLE_NAME1, columns, KEY_ID1 + " = ?", new String[]{String.valueOf(k)}, null, null, null);

Java static Lists in Android

I have a static List in a model class:
public static List<HomePageOptions> homePageOptions = Arrays.asList(
new HomePageOptions("Title1_1", "Title2_1"),
new HomePageOptions("Title1_2!", "Title2_2"),
new HomePageOptions("Title1_3", "Title2_3"),
new HomePageOptions("Title1_4", "Title2_4")
);
where HomePageOptions is defined:
public class HomePageOptions
{
String Title1;
String Title2;
public HomePageOptions (String title1, String title2)
{
setTitle1(title1);
setTitle2(title2);
}
//regular setters and getters
}
I have an activity that opens as such:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
List<String> values = new ArrayList<String>();
for(HomePageOptions ho : PharmacyModel.homePageOptions){
values.add(ho.getTitle1());
}
}
The for loop is giving me an ExceptionInInitializationError. I come across no problems when i create a regular List right before the for loop, but I would like to keep this structure in the model class. I've been trying to find a solution as to why this is. My guess is the static modifier on the List homePageOptions. Can anyone help?
Here's what the debugger is saying
Thread [<1> main] (Suspended (exception ExceptionInInitializerError))
<VM does not provide monitor information>
HomeActivity.onCreate(Bundle) line: 33
HomeActivity(Activity).performCreate(Bundle) line: 4465
Instrumentation.callActivityOnCreate(Activity, Bundle) line: 1049
ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1920
ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1981
ActivityThread.access$600(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 123
ActivityThread$H.handleMessage(Message) line: 1147
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 137
ActivityThread.main(String[]) line: 4424
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 511
ZygoteInit$MethodAndArgsCaller.run() line: 784
ZygoteInit.main(String[]) line: 551
NativeStart.main(String[]) line: not available [native method]
and LogCat
06-20 04:08:06.274: E/AndroidRuntime(1580): FATAL EXCEPTION: main
06-20 04:08:06.274: E/AndroidRuntime(1580): java.lang.ExceptionInInitializerError
06-20 04:08:06.274: E/AndroidRuntime(1580): at com.allgoodpeopleus.rootsoflife.HomeActivity.onCreate(HomeActivity.java:24)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.app.Activity.performCreate(Activity.java:4465)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.os.Looper.loop(Looper.java:137)
06-20 04:08:06.274: E/AndroidRuntime(1580): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-20 04:08:06.274: E/AndroidRuntime(1580): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 04:08:06.274: E/AndroidRuntime(1580): at java.lang.reflect.Method.invoke(Method.java:511)
06-20 04:08:06.274: E/AndroidRuntime(1580): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-20 04:08:06.274: E/AndroidRuntime(1580): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-20 04:08:06.274: E/AndroidRuntime(1580): at dalvik.system.NativeStart.main(Native Method)
06-20 04:08:06.274: E/AndroidRuntime(1580): Caused by: java.lang.NullPointerException
06-20 04:08:06.274: E/AndroidRuntime(1580): at ROLModel.Parameter.setValue(Parameter.java:91)
06-20 04:08:06.274: E/AndroidRuntime(1580): at ROLModel.Parameter.<init>(Parameter.java:21)
06-20 04:08:06.274: E/AndroidRuntime(1580): at ROLModel.PharmacyModel.<clinit>(PharmacyModel.java:77)
06-20 04:08:06.274: E/AndroidRuntime(1580): ... 15 more
this
public HomePageOptions (String title1, String title2)
{
setTitle1(title1);
setTitle2(title2);
}
should be
public HomePageOptions (String title1, String title2) {
Title1 = title1;
Title2 = title2;
}
The class PharmacyModel contains the public static List homePageOptions. Elsewhere in the class, I have several instances of the class Parameter:
public static Parameter Age = new Parameter("Age", 30, "years");
where
public class Parameter {
public Object Value;
public Parameter(String name, Object defaultValue, String units) {
setValue(defaultValue);
//set others
}
ParameterChangedEvent listener;
public void addListener(ParameterChangedEvent event){
listener = event;
}
public void setValue(Object value) {
Value = value;
listener.ValueChanged();
}
Because calling setValue in the constructor, listener is null causing the problem. The error manifested itself in the List, but nothing was wrong with that List or HomePageOptions. The solution is to change to line
listener.ValueChanged();
to
if(listener != null) listener.ValueChanged();

How to solve NullPointerException in Bitmap decleration.

I'm getting an error here that says,
at android.graphics.Bitmap_Delegate.nativeWidth(Bitmap_Delegate.java:291)
at android.graphics.Bitmap.nativeWidth(Bitmap.java)
at android.graphics.Bitmap.getWidth(Bitmap.java:785)
The DDMS says I'm getting an error at line 66 of the ViewingWindow class which is where the int bitmapX is declared and initialized:
protected void onDraw(Canvas canvas) {
if (canvas == null) throw new NullPointerException();
Bitmap bitmap = null;
if (Monitor.getCurrent() == Monitor.TYPE.GREEN) bitmap = greenBitmap;
else bitmap = redBitmap;
int bitmapX = bitmap.getWidth() / 2;
int bitmapY = bitmap.getHeight() / 2;
int parentX = parentWidth / 2;
int parentY = parentHeight / 2;
int centerX = parentX - bitmapX;
int centerY = parentY - bitmapY;
matrix.reset();
matrix.postTranslate(centerX, centerY);
canvas.drawBitmap(bitmap, matrix, paint);
}
Why am I getting such an error? Any help is highly appreciated. Thanks.
Here is the initialized variables of greenBitmap and redBitmap:
private static Bitmap greenBitmap = null;
private static Bitmap redBitmap = null;
private static int parentWidth = 0;
private static int parentHeight = 0;
public ViewingWindow(Context context, AttributeSet attr) {
super(context, attr);
greenBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.green_icon);
redBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.red_icon);
}
public ViewingWindow(Context context) {
super(context);
greenBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.green_icon);
redBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.red_icon);
}
The full error from DDMS:
11-21 20:53:44.959: E/AndroidRuntime(521): FATAL EXCEPTION: main
11-21 20:53:44.959: E/AndroidRuntime(521): java.lang.NullPointerException
11-21 20:53:44.959: E/AndroidRuntime(521): at com.ali.nazzal.sciencefairheartrateproject.ViewingWindow.onDraw(ViewingWindow.java:66)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.View.draw(View.java:6740)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.View.draw(View.java:6743)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.widget.FrameLayout.draw(FrameLayout.java:352)
11-21 20:53:44.959: E/AndroidRuntime(521): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1842)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewRoot.draw(ViewRoot.java:1407)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewRoot.performTraversals(ViewRoot.java:1163)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.os.Handler.dispatchMessage(Handler.java:99)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.os.Looper.loop(Looper.java:123)
11-21 20:53:44.959: E/AndroidRuntime(521): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-21 20:53:44.959: E/AndroidRuntime(521): at java.lang.reflect.Method.invokeNative(Native Method)
11-21 20:53:44.959: E/AndroidRuntime(521): at java.lang.reflect.Method.invoke(Method.java:521)
11-21 20:53:44.959: E/AndroidRuntime(521): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-21 20:53:44.959: E/AndroidRuntime(521): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-21 20:53:44.959: E/AndroidRuntime(521): at dalvik.system.NativeStart.main(Native Method)
----------------------------New Error from DDMS---------------------------------
11-21 21:49:44.699: E/AndroidRuntime(551): FATAL EXCEPTION: main
11-21 21:49:44.699: E/AndroidRuntime(551): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ali.nazzal.sciencefairheartrateproject/com.ali.nazzal.sciencefairheartrateproject.Monitor}: android.view.InflateException: Binary XML file line #23: Error inflating class com.ali.nazzal.sciencefairheartrateproject.ViewingWindow
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.os.Handler.dispatchMessage(Handler.java:99)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.os.Looper.loop(Looper.java:123)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-21 21:49:44.699: E/AndroidRuntime(551): at java.lang.reflect.Method.invokeNative(Native Method)
11-21 21:49:44.699: E/AndroidRuntime(551): at java.lang.reflect.Method.invoke(Method.java:521)
11-21 21:49:44.699: E/AndroidRuntime(551): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-21 21:49:44.699: E/AndroidRuntime(551): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-21 21:49:44.699: E/AndroidRuntime(551): at dalvik.system.NativeStart.main(Native Method)
11-21 21:49:44.699: E/AndroidRuntime(551): Caused by: android.view.InflateException: Binary XML file line #23: Error inflating class com.ali.nazzal.sciencefairheartrateproject.ViewingWindow
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.createView(LayoutInflater.java:503)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.rInflate(LayoutInflater.java:621)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
11-21 21:49:44.699: E/AndroidRuntime(551): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:198)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.Activity.setContentView(Activity.java:1647)
11-21 21:49:44.699: E/AndroidRuntime(551): at com.ali.nazzal.sciencefairheartrateproject.Monitor.onCreate(Monitor.java:60)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
11-21 21:49:44.699: E/AndroidRuntime(551): ... 11 more
11-21 21:49:44.699: E/AndroidRuntime(551): Caused by: java.lang.NoSuchMethodException: ViewingWindow(Context,AttributeSet)
11-21 21:49:44.699: E/AndroidRuntime(551): at java.lang.Class.getMatchingConstructor(Class.java:660)
11-21 21:49:44.699: E/AndroidRuntime(551): at java.lang.Class.getConstructor(Class.java:477)
11-21 21:49:44.699: E/AndroidRuntime(551): at android.view.LayoutInflater.createView(LayoutInflater.java:475)
11-21
21:49:44.699: E/AndroidRuntime(551): ... 23 more
Add this constructor to ViewingWindow:
public ViewingWindow(Context context, AttributeSet attrs, int defStyle) {
super(context, attr, defStyle);
greenBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.green_icon);
redBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.red_icon);
}

Error receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS }

okay, the full error is
06-19 01:07:57.421: E/AndroidRuntime(4478): java.lang.RuntimeException: Error
receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS } in
com.blucalc.netfind.WiFiScanReceiver#40521ba0
com.blucalc.netfind is my package
WiFiScanReceiver is the class its crashing in.
the class is here:
package com.blucalc.netfind;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
public class WiFiScanReceiver extends BroadcastReceiver {
NetworkfinderActivity netfinder;
public WiFiScanReceiver(NetworkfinderActivity netfinder) {
super();
this.netfinder = netfinder;
}
#Override
public void onReceive(Context c, Intent intent) {
System.out.println("onReceive(Context=" + c.toString() + "Intent="
+ intent.toString());
List<ScanResult> results = netfinder.wifi.getScanResults();
netfinder.processResults(results);
}
}
NetworkfinderActivity is the main class thing.
the really strange thing about the error is, it only happens on the second time this function is called. whether thats because of the different data i dont know, i can't test.
can someone please help me?
edit1:
as requested, androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.blucalc.netfind"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".NetworkfinderActivity"
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>
</manifest>
here's the main class. where all the fun happens.
//some code borrowed from http://marakana.com/forums/android/examples/40.html
package com.blucalc.netfind;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.os.Bundle;
import android.net.wifi.*;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class NetworkfinderActivity extends Activity {
/** Called when the activity is first created. */
WifiManager wifi;
BroadcastReceiver receiver;
List<FrameLayout> netlist;
LinearLayout ll;
Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println("start of main constructor");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//a couple interface elements I want to access
ll = (LinearLayout)findViewById(R.id.networkList);
b = (Button)findViewById(R.id.refreshButton);
//initialisation of some memory
netlist=new ArrayList<FrameLayout>();
//where all network info comes from
wifi=(WifiManager)getSystemService(WIFI_SERVICE);
// Register Broadcast Receiver
receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {;
System.out.println("clicked");
ll.removeAllViews();
netlist.clear();
wifi.startScan();
}
});
System.out.println("end of main constructor");
}
#Override
public void onStop() {
unregisterReceiver(receiver);
}
public void processResults(List<ScanResult> results)
{
System.out.println("processResults(results "+results.toString());
ll.removeAllViews();
netlist.clear();
for (ScanResult result:results)
{
readResult(result);
}
System.out.println("end of processResults");
}
public void readResult(ScanResult result)
{
System.out.println("readResult(result "+result.toString());
FrameLayout frame=new FrameLayout(this);
TextView ssid=new TextView(this);
TextView strength=new TextView(this);
System.out.println("1");
int level=result.level;
System.out.println("level="+level);
int signal=WifiManager.calculateSignalLevel(level, 100)+1;
//signal will be strength of the signal as a percent (from 1 to 100)
System.out.println("signal="+signal);
strength.setText(new Integer(signal).toString());
ssid.setText(result.SSID);
TextView cheat=new TextView(this);
cheat.setText(result.toString());
// frame.addView(ssid);
// frame.addView(strength);
frame.addView(cheat);
netlist.add(frame);
ll.addView(netlist.get(netlist.size()-1));
System.out.println("end of readResults");
}
}
and last but not least, here's the entire output, plus all error messages.
06-20 20:40:06.835: I/ApplicationPackageManager(2399): cscCountry is not German : XSA
06-20 20:40:06.835: I/System.out(2399): start of main constructor
06-20 20:40:06.867: V/WifiProgressStore(2399): WifiProgressStore Created
06-20 20:40:06.867: I/System.out(2399): end of main constructor
06-20 20:40:16.765: I/System.out(2399): clicked
06-20 20:40:17.351: I/System.out(2399): onReceive(Context=com.blucalc.netfind.NetworkfinderActivity#40518050Intent=Intent { act=android.net.wifi.SCAN_RESULTS }
06-20 20:40:17.363: I/System.out(2399): processResults(results [SSID: BluCalculator, BSSID: f4:ec:38:a9:1d:56, capabilities: [WPA-PSK-TKIP+CCMP][WPA2-PSK-TKIP+CCMP][WPS], level: -51, frequency: 2412, SSID: BigAir, BSSID: 06:27:22:b3:41:7e, capabilities: , level: -72, frequency: 2437, SSID: BigAir, BSSID: 06:27:22:5f:56:d8, capabilities: , level: -87, frequency: 2437]
06-20 20:40:17.367: I/System.out(2399): readResult(result SSID: BluCalculator, BSSID: f4:ec:38:a9:1d:56, capabilities: [WPA-PSK-TKIP+CCMP][WPA2-PSK-TKIP+CCMP][WPS], level: -51, frequency: 2412
06-20 20:40:17.375: I/System.out(2399): 1
06-20 20:40:17.375: I/System.out(2399): level=-51
06-20 20:40:17.375: I/System.out(2399): signal=100
06-20 20:40:17.378: I/System.out(2399): end of readResults
06-20 20:40:17.382: I/System.out(2399): readResult(result SSID: BigAir, BSSID: 06:27:22:b3:41:7e, capabilities: , level: -72, frequency: 2437
06-20 20:40:17.390: I/System.out(2399): 1
06-20 20:40:17.390: I/System.out(2399): level=-72
06-20 20:40:17.394: D/AndroidRuntime(2399): Shutting down VM
06-20 20:40:17.394: W/dalvikvm(2399): threadid=1: thread exiting with uncaught exception (group=0x40015578)
06-20 20:40:17.402: E/AndroidRuntime(2399): FATAL EXCEPTION: main
06-20 20:40:17.402: E/AndroidRuntime(2399): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS } in com.blucalc.netfind.WiFiScanReceiver#40520ec0
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:722)
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.os.Handler.handleCallback(Handler.java:587)
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.os.Handler.dispatchMessage(Handler.java:92)
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.os.Looper.loop(Looper.java:123)
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.app.ActivityThread.main(ActivityThread.java:3687)
06-20 20:40:17.402: E/AndroidRuntime(2399): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 20:40:17.402: E/AndroidRuntime(2399): at java.lang.reflect.Method.invoke(Method.java:507)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
06-20 20:40:17.402: E/AndroidRuntime(2399): at dalvik.system.NativeStart.main(Native Method)
06-20 20:40:17.402: E/AndroidRuntime(2399): Caused by: java.lang.ArithmeticException: divide by zero
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.net.wifi.WifiManager.calculateSignalLevel(WifiManager.java:957)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.blucalc.netfind.NetworkfinderActivity.readResult(NetworkfinderActivity.java:79)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.blucalc.netfind.NetworkfinderActivity.processResults(NetworkfinderActivity.java:65)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.blucalc.netfind.WiFiScanReceiver.onReceive(WiFiScanReceiver.java:23)
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709)
06-20 20:40:17.402: E/AndroidRuntime(2399): ... 9 more
ANSWER UPDATED
If you look into your stack trace, you will find another exception that points out the real problem:
06-20 20:40:17.402: E/AndroidRuntime(2399): Caused by: java.lang.ArithmeticException: divide by zero
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.net.wifi.WifiManager.calculateSignalLevel(WifiManager.java:957)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.blucalc.netfind.NetworkfinderActivity.readResult(NetworkfinderActivity.java:79)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.blucalc.netfind.NetworkfinderActivity.processResults(NetworkfinderActivity.java:65)
06-20 20:40:17.402: E/AndroidRuntime(2399): at com.blucalc.netfind.WiFiScanReceiver.onReceive(WiFiScanReceiver.java:23)
06-20 20:40:17.402: E/AndroidRuntime(2399): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709)
06-20 20:40:17.402: E/AndroidRuntime(2399): ... 9 more
Note the part that says
6-20 20:40:17.402: E/AndroidRuntime(2399): Caused by: java.lang.ArithmeticException: divide by zero
The method you are attempting to access (calculateSignalLevel) has a known bug in it. You can find a post relating to the use calculateSignalLevel (that includes the code implementation of calculateSignalLevel) at this question (also note Ridcully's comment on Lars' answer).
The problem is most likely your use of 100 here:
WifiManager.calculateSignalLevel(level, 100);
When this number is greater than 45, you will get a divide by zero exception. Try stepping through the method with a value of 100 for partitionLevel and observe the outcome.

Unable to read the HTML contents from a URL in Android

I was trying to read the HTML contents from a url. I tried with many samples and code examples from many sites, but it didn't work for me. When I run the code it leaves the default text in textview. I even tried with edittext as well. I have even added permission in the manifest file.
One of the codes I used is here: I have added the complete code here. I tried with all the code below with no success.
package com.adn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class REEActivity extends Activity {
private static BufferedReader reader = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText ed = (EditText) findViewById(R.id.editText1);
try {
ed.append(getStringFromUrl("http://www.google.com"));
//getInputStreamFromUrl("").close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("Content stream is " + contentStream);
return contentStream;
}
public static String getStringFromUrl(String url) throws IOException{
reader = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuilder sb = new StringBuilder();
try{
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
getInputStreamFromUrl(url).close();
return sb.toString();
}
}
Here is the logcat:
06-20 21:25:18.022: E/AndroidRuntime(14095): FATAL EXCEPTION: main
06-20 21:25:18.022: E/AndroidRuntime(14095): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.adn/com.adn.REEActivity}: java.lang.NullPointerException
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.os.Handler.dispatchMessage(Handler.java:99)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.os.Looper.loop(Looper.java:137)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.main(ActivityThread.java:4424)
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.lang.reflect.Method.invoke(Method.java:511)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-20 21:25:18.022: E/AndroidRuntime(14095): at dalvik.system.NativeStart.main(Native Method)
06-20 21:25:18.022: E/AndroidRuntime(14095): Caused by: java.lang.NullPointerException
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.io.Reader.<init>(Reader.java:64)
06-20 21:25:18.022: E/AndroidRuntime(14095): at java.io.InputStreamReader.<init>(InputStreamReader.java:79)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.adn.REEActivity.getStringFromUrl(REEActivity.java:49)
06-20 21:25:18.022: E/AndroidRuntime(14095): at com.adn.REEActivity.onCreate(REEActivity.java:28)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.Activity.performCreate(Activity.java:4465)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-20 21:25:18.022: E/AndroidRuntime(14095): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
06-20 21:25:18.022: E/AndroidRuntime(14095): ... 11 more
Here is the Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adn"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".REEActivity"
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>
</manifest>
Can someone please help me with this. I am new to Android as well.
replace
StringBuffer sb = new StringBuffer();
with
StringBuffer sb = new StringBuilder();
and also close your InputStrem using close() method
try to use this code in your second method, hope this will solve the problem
public static String getStringFromUrl(String url) throws UnsupportedEncodingException{
BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuilder sb = new StringBuilder();
try{
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
getInputStreamFromUrl(url).close();
return sb.toString();
}
I tried your updated code and it works now, and this is what I get:
Can you try this code
public String getUrlContents(String url){
String content = "";
HttpClient hc = new DefaultHttpClient();
HttpGet hGet = new HttpGet(url);
ResponseHandler<String> rHand = new BasicResponseHandler();
try {
content = hc.execute(hGet,rHand);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

Categories