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

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.

Related

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

An error appear when execute android app

I try to reproduce some videos in a sequence, this is the code, and the error message. I create the sd card in eclipse with the option Run -> Debug Configurations, is a 2GB sd card. I copied some videos to the sd card. So, I appreciate your help. Thanks.
MovieG.java
package com.example.movieg;
import java.io.File;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.MediaController;
import android.widget.VideoView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MovieG extends Activity {
public VideoView videoView;
public String ex_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_g);
ex_name = getIntent().getExtras().getString("video_name");
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(new MediaController(this));
handler.sendEmptyMessage(1);
}
#SuppressLint("HandlerLeak")
Handler handler = new Handler(){
public void handleMessage(Message msg){
int pos=msg.what;
if (pos == 1){
File ex_name = null;
videoView.setVideoPath(Environment.getExternalStorageDirectory()+"/"+ex_name+".mp4");
videoView.requestFocus();
videoView.start();
Log.d("Before Video Finish", "i m in before video finish");
videoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
finish();
}
});
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movie_g, menu);
return true;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.movieg"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.movieg.MovieG"
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>
Error Message
02-24 21:42:54.916: D/AndroidRuntime(278): Shutting down VM
02-24 21:42:54.916: W/dalvikvm(278): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-24 21:42:54.946: E/AndroidRuntime(278): FATAL EXCEPTION: main
02-24 21:42:54.946: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.movieg/com.example.movieg.MovieG}: java.lang.NullPointerException
02-24 21:42:54.946: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-24 21:42:54.946: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
02-24 21:42:54.946: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
02-24 21:42:54.946: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-24 21:42:54.946: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-24 21:42:54.946: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
02-24 21:42:54.946: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
02-24 21:42:54.946: E/AndroidRuntime(278): at com.example.movieg.MovieG.onCreate(MovieG.java:28)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-24 21:42:54.946: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-24 21:42:54.946: E/AndroidRuntime(278): ... 11 more
You should verify that getIntent() has extras:
if (getIntent().getExtras() != null)
ex_name = getIntent().getExtras().getString("video_name");
You then need to cater for ex_name being null later in the code.
Second thing is, you never initialise videoView variable. You need to create an instance of it before it's used in onCreate().
You have not initialize the videoview:
videoView =(VideoView)findViewById(R.id.your_id);
before 28 th line

android application error 5

I try to implement an application based on rscm (middleware). When I try to run on emulator, I get the errors listed below:
Error :03-27 16:58:20.490: E/Trace(1508): error opening trace file: No
such file or directory (2)
03-27 21:53:21.610: D/AndroidRuntime(3803): Shutting down VM 03-27
21:53:21.610: W/dalvikvm(3803): threadid=1: thread exiting with
uncaught exception (group=0x40a71930) 03-27 21:53:21.760:
E/AndroidRuntime(3803): FATAL EXCEPTION: main 03-27 21:53:21.760:
E/AndroidRuntime(3803): java.lang.RuntimeException: Unable to
instantiate activity
ComponentInfo{com.example.context_application/com.example.context_application.MyContextAwareActivity}:
java.lang.ClassNotFoundException: Didn't find class
"com.example.context_application.MyContextAwareActivity" on path:
/data/app/com.example.context_application-2.apk 03-27 21:53:21.760:
E/AndroidRuntime(3803): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-27 21:53:21.760: E/AndroidRuntime(3803): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-27 21:53:21.760: E/AndroidRuntime(3803): at
android.app.ActivityThread.access$600(ActivityThread.java:141) 03-27
21:53:21.760: E/AndroidRuntime(3803): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-27 21:53:21.760: E/AndroidRuntime(3803): at
android.os.Handler.dispatchMessage(Handler.java:99) 03-27
21:53:21.760: E/AndroidRuntime(3803): at
android.os.Looper.loop(Looper.java:137) 03-27 21:53:21.760:
E/AndroidRuntime(3803): at
android.app.ActivityThread.main(ActivityThread.java:5041) 03-27
21:53:21.760: E/AndroidRuntime(3803): at
java.lang.reflect.Method.invokeNative(Native Method) 03-27
21:53:21.760: E/AndroidRuntime(3803): at
java.lang.reflect.Method.invoke(Method.java:511) 03-27 21:53:21.760:
E/AndroidRuntime(3803): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-27 21:53:21.760: E/AndroidRuntime(3803): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 03-27
21:53:21.760: E/AndroidRuntime(3803): at
dalvik.system.NativeStart.main(Native Method) 03-27 21:53:21.760:
E/AndroidRuntime(3803): Caused by: java.lang.ClassNotFoundException:
Didn't find class
"com.example.context_application.MyContextAwareActivity" on path:
/data/app/com.example.context_application-2.apk 03-27 21:53:21.760:
E/AndroidRuntime(3803): at
dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
03-27 21:53:21.760: E/AndroidRuntime(3803): at
java.lang.ClassLoader.loadClass(ClassLoader.java:501) 03-27
21:53:21.760: E/AndroidRuntime(3803): at
java.lang.ClassLoader.loadClass(ClassLoader.java:461) 03-27
21:53:21.760: E/AndroidRuntime(3803): at
android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-27 21:53:21.760: E/AndroidRuntime(3803): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
03-27 21:53:21.760: E/AndroidRuntime(3803): ... 11 more
Can anyone help?
package com.example.context;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import org.aspectsense.rscm.ContextValue;
import org.aspectsense.rscm.context.client.ContextListenerActivity;
import org.json.JSONException;
import java.util.Date;
public class MyContextAwareActivity extends ContextListenerActivity
{
#Override public String[] getRequestedScopes()
{
return new String[] { "battery.level" };
}
private TextView messageTextView;
#Override protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
messageTextView = new TextView(this);
setContentView(messageTextView);
appendMessage("Activity created");
}
private void appendMessage(final String message)
{
final String currentMessage = messageTextView.getText().toString();
messageTextView.setText(currentMessage + "\n" + message);
}
#Override public void onContextValueChanged(ContextValue contextValue)
{
try
{
appendMessage(new Date() + ": The battery level is " + contextValue.getValueAsInteger() + "%");
}
catch (JSONException jsone)
{
Toast.makeText(this, "Error while displaying context event: " + contextValue, Toast.LENGTH_SHORT).show();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.context"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.context.MyContextAwareActivity"
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>
You are telling it to write to external storage. Have you set up an SD card in eclipse?
Do any of these answers help? error opening trace file: No such file or directory (2)

storing images from internet locally on Android

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

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