Java static Lists in Android - java

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

Related

NullPointerException on MrNom

I was trying to execute Mr Nom(from the book Begining Android Games by Mario Zechner). but it doesn't work. My first atemp was create 2 different projects, one called framework where are com.badlogic.androidgames.framework and com.badlogic.androidgames.framework files and other project called mrnom (com.badlogic.androidgames.mrnom)with the rest of files. the framework project was added mrnom project/java build path/project/add and the result was this:
logcat
11-07 15:21:55.573: W/dalvikvm(641): Unable to resolve superclass of Lcom/badlogic/androidgames/mrnom/MrNom; (445)
11-07 15:21:55.573: W/dalvikvm(641): Link of class 'Lcom/badlogic/androidgames/mrnom/MrNom;' failed
11-07 15:21:55.573: D/AndroidRuntime(641): Shutting down VM
11-07 15:21:55.573: W/dalvikvm(641): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-07 15:21:55.583: E/AndroidRuntime(641): FATAL EXCEPTION: main
11-07 15:21:55.583: E/AndroidRuntime(641): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.badlogic.androidgames.mrnom/com.badlogic.androidgames.mrnom.MrNom}: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.os.Looper.loop(Looper.java:137)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 15:21:55.583: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-07 15:21:55.583: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-07 15:21:55.583: E/AndroidRuntime(641): at dalvik.system.NativeStart.main(Native Method)
11-07 15:21:55.583: E/AndroidRuntime(641): Caused by: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:21:55.583: E/AndroidRuntime(641): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-07 15:21:55.583: E/AndroidRuntime(641): ... 11 more
11-07 15:24:06.602: E/Trace(662): error opening trace file: No such file or directory (2)
11-07 15:24:06.902: W/dalvikvm(662): Unable to resolve superclass of Lcom/badlogic/androidgames/mrnom/MrNom; (445)
11-07 15:24:06.902: W/dalvikvm(662): Link of class 'Lcom/badlogic/androidgames/mrnom/MrNom;' failed
11-07 15:24:06.902: D/AndroidRuntime(662): Shutting down VM
11-07 15:24:06.932: W/dalvikvm(662): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-07 15:24:06.952: E/AndroidRuntime(662): FATAL EXCEPTION: main
11-07 15:24:06.952: E/AndroidRuntime(662): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.badlogic.androidgames.mrnom/com.badlogic.androidgames.mrnom.MrNom}: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.os.Looper.loop(Looper.java:137)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 15:24:06.952: E/AndroidRuntime(662): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-07 15:24:06.952: E/AndroidRuntime(662): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-07 15:24:06.952: E/AndroidRuntime(662): at dalvik.system.NativeStart.main(Native Method)
11-07 15:24:06.952: E/AndroidRuntime(662): Caused by: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:24:06.952: E/AndroidRuntime(662): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-07 15:24:06.952: E/AndroidRuntime(662): ... 11 more
later I removed the framework from mrnom and added it using a jar file, the result was the same
Now, I copy the com.badlogic.androidgames.framework and com.badlogic.androidgames.framework files into mr project then I have com.badlogic.androidgames.mrnom, com.badlogic.androidgames.framework and com.badlogic.androidgames.framework in the same project but now the error is
logcat
12-05 15:42:43.510: D/dalvikvm(582): GC_EXTERNAL_ALLOC freed 57K, 53% free 2569K/5379K, external 1925K/2137K, paused 239ms
12-05 15:42:43.860: D/dalvikvm(582): GC_EXTERNAL_ALLOC freed 3K, 53% free 2569K/5379K, external 2515K/2701K, paused 36ms
12-05 15:42:44.100: W/dalvikvm(582): threadid=11: thread exiting with uncaught exception (group=0x40015560)
12-05 15:42:44.100: E/AndroidRuntime(582): FATAL EXCEPTION: Thread-12
12-05 15:42:44.100: E/AndroidRuntime(582): java.lang.NullPointerException
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.mrnom.Settings.load(Settings.java:18)
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.mrnom.LoadingScreen.update(LoadingScreen.java:41)
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.framework.impl.AndroidFastRenderView.run(AndroidFastRenderView.java:36)
12-05 15:42:44.100: E/AndroidRuntime(582): at java.lang.Thread.run(Thread.java:1019)
Settings
package com.badlogic.androidgames.mrnom;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import com.balogic.androidgames.framework.FileIO;
public class Settings {
public static boolean soundEnable=true;
public static int[] highscores=new int[]{100,80,50,30,10};
public static void load(FileIO files){
BufferedReader in=null;
try{
in=new BufferedReader(new InputStreamReader(files.readFile(".mrnom")));// line 18 error here
soundEnable=Boolean.parseBoolean(in.readLine());
for(int i=0; i<5;i++){
highscores[i]=Integer.parseInt(in.readLine());
}
}catch(IOException e){
// :( vale,trabajamos con valores predeterminados
}catch(NumberFormatException e){
// :/ vale, estos valores nos han salvado el día
}finally{
try{
if(in!=null)
in.close();
}catch(IOException e){
//nada
}
}
}
public static void save(FileIO files){
BufferedWriter out=null;
try{
out=new BufferedWriter(new OutputStreamWriter(files.writeFile(".mrnom")));
out.write(Boolean.toString(soundEnable));
for(int i=0; i<5; i++){
out.write(Integer.toString(highscores[i]));
}
}catch(IOException e){
//nada
}finally{
try{
if(out!=null)
out.close();
}catch(IOException e){
//nada
}
}
}
public static void addScore(int score){
for(int i=0;i<5;i++){
if(highscores[i]<score){
for(int j=4;j>i;j--)
highscores[j]=highscores[j-1];
highscores[i]=score;
break;
}
}
}
}
Loadingsceen
package com.badlogic.androidgames.mrnom;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.framework.Graphics.PixmapFormat;
import com.badlogic.androidgames.framework.Screen;
public class LoadingScreen extends Screen{
public LoadingScreen(Game game){
super(game);
}
#Override
public void update(float deltaTime){
Graphics g=game.getGraphics();
Assets.background = g.newPixmap("background.png", PixmapFormat.RGB565);
Assets.logo = g.newPixmap("logo.png", PixmapFormat.ARGB4444);
Assets.mainMenu = g.newPixmap("mainmenu.png", PixmapFormat.ARGB4444);
Assets.buttons = g.newPixmap("buttons.png", PixmapFormat.ARGB4444);
Assets.help1 = g.newPixmap("help1.png", PixmapFormat.ARGB4444);
Assets.help2 = g.newPixmap("help2.png", PixmapFormat.ARGB4444);
Assets.help3 = g.newPixmap("help3.png", PixmapFormat.ARGB4444);
Assets.numbers = g.newPixmap("numbers.png", PixmapFormat.ARGB4444);
Assets.ready = g.newPixmap("ready.png", PixmapFormat.ARGB4444);
Assets.pause = g.newPixmap("pausemenu.png", PixmapFormat.ARGB4444);
Assets.gameOver = g.newPixmap("gameover.png", PixmapFormat.ARGB4444);
Assets.headUp = g.newPixmap("headup.png", PixmapFormat.ARGB4444);
Assets.headLeft = g.newPixmap("headleft.png", PixmapFormat.ARGB4444);
Assets.headDown = g.newPixmap("headdown.png", PixmapFormat.ARGB4444);
Assets.headRight = g.newPixmap("headright.png", PixmapFormat.ARGB4444);
Assets.tail = g.newPixmap("tail.png", PixmapFormat.ARGB4444);
Assets.stain1 = g.newPixmap("stain.png", PixmapFormat.ARGB4444);
Assets.stain2 = g.newPixmap("stain2.png", PixmapFormat.ARGB4444);
Assets.stain3 = g.newPixmap("stain3.png", PixmapFormat.ARGB4444);
Assets.click = game.getAudio().newSound("click.ogg");
Assets.eat = game.getAudio().newSound("eat.ogg");
Assets.bitten = game.getAudio().newSound("bitten.ogg");
Settings.load(game.getFileIO()); //line 41 error here
game.setScreen(new MainMenuScreen(game));
}
#Override
public void present(float deltaTime) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
AndroidFastRenderView
package com.badlogic.androidgames.framework.impl;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class AndroidFastRenderView extends SurfaceView implements Runnable{
AndroidGame game;
Bitmap framebuffer;
Thread renderThread=null;
SurfaceHolder holder;
volatile boolean running=false;
public AndroidFastRenderView(AndroidGame game,Bitmap framebuffer){
super(game);
this.game=game;
this.framebuffer=framebuffer;
this.holder=getHolder();
}
public void resume(){
running=true;
renderThread=new Thread(this);
renderThread.start();
}
public void run(){
Rect dstRect=new Rect();
long startTime=System.nanoTime();
while(running){
if(!holder.getSurface().isValid())
continue;
float deltaTime=(System.nanoTime()-startTime)/1000000000.0f;
startTime=System.nanoTime();
game.getCurrentScreen().update(deltaTime);//line 36 error here
game.getCurrentScreen().present(deltaTime);
Canvas canvas=holder.lockCanvas();
canvas.getClipBounds(dstRect);
canvas.drawBitmap(framebuffer, null, dstRect,null);
holder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
running=false;
while(true){
try{
renderThread.join();
break;
}catch(InterruptedException e){
//vuelve a intentarlo
}
}
}
}
Eclipse doesn't showme any mistake on code but on the emulator just say "Sorry! the application mrnom (process com.badlogic.androidgames.mrnom) has stopped unexpectedly. Please try again"
Can you help me with this? No idea what's happening :( Thank you so much.

Geocoder initialization fails

I am getting a NullPointerException when trying to declare the Geocoder in my application. I have the following declaration :
public class MainActivity extends Activity {
private Geocoder geocoder = new Geocoder(this, Locale.getDefault());
...
}
I get the following LogCat :
03-20 10:48:55.729: D/AndroidRuntime(604): Shutting down VM
03-20 10:48:55.729: W/dalvikvm(604): threadid=1: thread exiting with uncaught exception
(group=0x40a71930)
03-20 10:48:56.209: E/AndroidRuntime(604): FATAL EXCEPTION: main
03-20 10:48:56.209: E/AndroidRuntime(604): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coord/com.example.coord.MainActivity}: java.lang.NullPointerException
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.os.Looper.loop(Looper.java:137)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-20 10:48:56.209: E/AndroidRuntime(604): at dalvik.system.NativeStart.main(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): Caused by: java.lang.NullPointerException
03-20 10:48:56.209: E/AndroidRuntime(604): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.example.coord.MainActivity.<init>(MainActivity.java:21)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.Class.newInstanceImpl(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.Class.newInstance(Class.java:1319)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
Line 21 is my Geocoder declaration. What is wrong with my code?
The context is only available when the activity is started so you cannot initialize the geocoder in the class body. Try to initialize it in the onCreate or onResume method instead...
public class MainActivity extends Activity {
private Geocoder mGeocoder;
#Override
protected void onCreate(Bundle _icicle) {
super.onCreate(_icicle);
mGeocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
}
}
Add this permissions in to manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and use getApplicationContext() insted of this
It is recommended to use the GeoCode in Background or on separate thread as defined by Google Developers page.
new Thread(new Runnable()
{
#Override
public void run()
{
//Do things.
Geocoder geocoder = new Geocoder(getBaseContext());
try {
// Getting a maximum of 5 Address that matches the input text
addresses = geocoder.getFromLocationName(addressText,5);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

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

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