Somebody please explain the error - java

I am new to android programming.I have been trying to establish connection between two emulators.While my server emulator is up and running,client has a problem.Here is the code and logcat error description.Please tell me the error in this.
public class SocketClient extends Activity
{
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "192.168.0.5";
private static final int REDIRECTED_SERVERPORT = 5000;
public void connect()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
tv.setText((CharSequence) serverAddr);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
System.out.println("Here");
}
catch (IOException e1)
{
e1.printStackTrace();
System.out.println("Here too");
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
connect();
bt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception e)
{
tv.setText("Error3");
e.printStackTrace();
}
}
}
);
}
}
The logcat error is
01-31 04:42:51.170: W/dalvikvm(529): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-31 04:42:51.187: E/AndroidRuntime(529): FATAL EXCEPTION: main
01-31 04:42:51.187: E/AndroidRuntime(529): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.ServerClient/com.app.ServerClient.SocketClient}: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.access$600(ActivityThread.java:123)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Handler.dispatchMessage(Handler.java:99)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.os.Looper.loop(Looper.java:137)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invokeNative(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): at java.lang.reflect.Method.invoke(Method.java:511)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-31 04:42:51.187: E/AndroidRuntime(529): at dalvik.system.NativeStart.main(Native Method)
01-31 04:42:51.187: E/AndroidRuntime(529): Caused by: java.lang.ClassCastException: java.net.Inet4Address cannot be cast to java.lang.CharSequence
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.connect(SocketClient.java:25)
01-31 04:42:51.187: E/AndroidRuntime(529): at com.app.ServerClient.SocketClient.onCreate(SocketClient.java:48)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Activity.performCreate(Activity.java:4465)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
01-31 04:42:51.187: E/AndroidRuntime(529): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
01-31 04:42:51.187: E/AndroidRuntime(529): ... 11 more
Thanks in advance.
Thank You David and Jitendra.
I corrected the error and I get a nullPointerException in one part of the code.What did I do wrong?
public void onClick(View v)
{
try // The error is in this block
{
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
}
catch (UnknownHostException e)
{
tv.setText("Error1");
e.printStackTrace();
}
catch (IOException e)
{
tv.setText("Error2");
e.printStackTrace();
}
catch (Exception f) // I get the error here. java.lang.NullPointerException
{
tv.setText("Error3");
tv.setText(f.toString());
f.printStackTrace();
}
}

Your error is on this line:
tv.setText((CharSequence) serverAddr);
serverAddr is of type InetAddress, and you're trying to cast it to a CharSequence which cannot be done. Perhaps you meant:
tv.setText(serverIpAddress);

Exception is in following line:
tv.setText((CharSequence) serverAddr);
and it is because you are trying to cast serverAddr into CharSequence.
If you really want to print serverAddr use
tv.setText((CharSequence) serverAddr.toString());

Related

The api isApiSupported return true but SipManager newInstance still return null in Android native Sip

I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282) 
at android.app.ActivityThread.access$600(ActivityThread.java:147) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5265) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 
at dalvik.system.NativeStart.main(Native Method) 

App force closes when I try to implement an EditText search in a Listview

I am new to android. I have created an app which was a pull parser in order to extract items from an Rss feed, into a ListView. Unfortunately my app seems to force close when I try and place code in order implement some sort of filtering mechanism in my ListView. This is the code I have so far, and I have no idea why it seems to crash. Any help would be appreciated.
public class RssFeed extends ListActivity {
// Listview Adapter
ArrayAdapter<string> adapter;
EditText SearchBox;
List titles;
public static List description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rss);
// Initialising instance variables
titles = new ArrayList();
description = new ArrayList();
try {
URL url = new URL("http://my.url");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
/** While the rss feed has not displayed end_document, pull the title and description information */
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem)
titles.add(xpp.nextText());
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem)
description.add(xpp.nextText());
}
}else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
insideItem=false;
}
eventType = xpp.next();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
/**
* Enabling Search Filter
* */
SearchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
RssFeed.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
}
And the LogCat:
04-12 20:43:00.792: D/dalvikvm(324): GC freed 7597 objects / 316440 bytes in 88ms
04-12 20:43:00.852: D/AndroidRuntime(324): Shutting down VM
04-12 20:43:00.852: W/dalvikvm(324): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
04-12 20:43:00.852: E/AndroidRuntime(324): Uncaught handler: thread main exiting due to uncaught exception
04-12 20:43:00.862: E/AndroidRuntime(324): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.me.myandroidstuff.simpleRssReader/org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed}: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.os.Looper.loop(Looper.java:123)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invokeNative(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): at java.lang.reflect.Method.invoke(Method.java:521)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-12 20:43:00.862: E/AndroidRuntime(324): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-12 20:43:00.862: E/AndroidRuntime(324): at dalvik.system.NativeStart.main(Native Method)
04-12 20:43:00.862: E/AndroidRuntime(324): Caused by: java.lang.NullPointerException
04-12 20:43:00.862: E/AndroidRuntime(324): at org.me.myandroidstuff.TrafficScotlandPrototype.RssFeed.onCreate(RssFeed.java:142)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-12 20:43:00.862: E/AndroidRuntime(324): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-12 20:43:00.862: E/AndroidRuntime(324): ... 11 more
04-12 20:43:00.892: I/dalvikvm(324): threadid=7: reacting to signal 3
04-12 20:43:00.892: E/dalvikvm(324): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
First of all: the class you posted doesn't have 142 lines, be sure to post the whole class.
Second: SearchBox is null here.
That is because you declared it with
EditText SearchBox;
but never assigned it which you would usually do from your layout like
SearchBox = (EditText) findViewById(R.id.searchBox);
(just an example)
SeachBox does not have an assigned value at this point so you can't use any methods on it.
Third: Use lower case names like searchBox, it'll make your code easier to read for others and yourself.

my application crashes when i start new thread [duplicate]

This question already has an answer here:
Application crashes while starting the new thread
(1 answer)
Closed 9 years ago.
I have a class where I have implemented runnable and I start the thread in one of the function of this class, and I call this function from the main activity,I create the object of this class and call the method of thread class.My main activity code from where I call this class method is:
broadcast broadcastobject.threadfunc(messages);
My class where I create threads is:
public class broadcast {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public void threadfunc(String message){
str=message;
new Thread(new ClientThread()).start();
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
class ClientThread implements Runnable {
#Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My log cat is:
08-31 21:55:56.277: D/gralloc_goldfish(1669): Emulator without GPU emulation detected.
08-31 21:56:02.467: D/AndroidRuntime(1669): Shutting down VM
08-31 21:56:02.467: W/dalvikvm(1669): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
08-31 21:56:02.517: E/AndroidRuntime(1669): FATAL EXCEPTION: main
08-31 21:56:02.517: E/AndroidRuntime(1669): java.lang.NullPointerException
08-31 21:56:02.517: E/AndroidRuntime(1669): at soft.b.peopleassist.Send$1.onClick(Send.java:113)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View.performClick(View.java:3480)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.view.View$PerformClick.run(View.java:13983)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.handleCallback(Handler.java:605)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Handler.dispatchMessage(Handler.java:92)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.os.Looper.loop(Looper.java:137)
08-31 21:56:02.517: E/AndroidRuntime(1669): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 21:56:02.517: E/AndroidRuntime(1669): at java.lang.reflect.Method.invoke(Method.java:511)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-31 21:56:02.517: E/AndroidRuntime(1669): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-31 21:56:02.517: E/AndroidRuntime(1669): at dalvik.system.NativeStart.main(Native Method)
This simply means that the emulator you are using does not have GPU emulation enabled. In Android SDK Tools R15 you can enable GPU emulation.You need to create a new emulator virtual device and set GPU emulation to true in Hardware properties.

NetworkOnMainThreadException Android within Async

I am getting the exceptions unless I delete this:
android:targetSdkVersion="15"
I found that in another thread here on SO.
However, I have had this running with that targetSdkVersion in there for a few days. Here is my code:
public class MainActivity extends BaseActivity {
private TextView textView;
private String url = "http://www.backcountryskiers.com/sac/sac-full.html";
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.todaysReport);
image = (ImageView) findViewById(R.id.dangerRose);
fetcher task = new fetcher();
task.execute();
}
public static Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception", e.getMessage());
return null;
}
}
class fetcher extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
private Document doc = null;
private Elements content = null;
private Document parse = null;
private String results = null;
private Element dangerRatingImg = null;
private String dangerRatingSrc = null;
private Bitmap bimage;
#Override
protected String doInBackground(String... params) {
try {
// bimage = getBitmapFromURL(drUrl);
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
content = doc.select("#content");
parse = Jsoup.parse(doc.html());
results = doc.select("#content").outerHtml();
return results;
}
#Override
protected void onPostExecute(String result) {
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
// find rating image...
dangerRatingImg = doc.select("img").first();
dangerRatingSrc = dangerRatingImg.absUrl("src");
// Get the rating image
bimage = getBitmapFromURL(dangerRatingSrc);
image.setImageBitmap(bimage);
image.setPadding(10, 10, 10, 10);
image.setScaleType(ScaleType.FIT_XY);
// return the summary
results = parse.select("#reportSummary").outerHtml();
textView.setText(Html.fromHtml(results));
textView.setPadding(10, 10, 10, 10);
// ditch the dialog, it's all loaded.
dialog.dismiss();
}
#Override
protected void onPreExecute() {
// before we get the async results show this
dialog.setMessage("Loading Latest Update from the Sierra Avalanche Center...");
dialog.show();
}
}
}
I have network connection and can see the results fine taking that targetSdkVersion out... but I know that is not right. Thanks everyone.
EDIT:
11-09 08:24:55.316: D/dalvikvm(9165): GC_CONCURRENT freed 148K, 3% free 11365K/11655K, paused 12ms+12ms, total 39ms
11-09 08:24:55.410: D/dalvikvm(9165): GC_CONCURRENT freed 331K, 5% free 11484K/11975K, paused 1ms+1ms, total 20ms
11-09 08:24:55.418: E/Jsoup(9165): ...is working...
11-09 08:24:55.558: D/dalvikvm(9165): GC_CONCURRENT freed 465K, 5% free 11506K/12103K, paused 12ms+12ms, total 39ms
11-09 08:24:55.558: E/src(9165): http://www.sierraavalanchecenter.org/sites/default/files/images/danger_icons_and_bars/0_nodangerrate.png
11-09 08:24:55.558: D/AndroidRuntime(9165): Shutting down VM
11-09 08:24:55.558: W/dalvikvm(9165): threadid=1: thread exiting with uncaught exception (group=0x40bc2300)
11-09 08:24:55.566: E/AndroidRuntime(9165): FATAL EXCEPTION: main
11-09 08:24:55.566: E/AndroidRuntime(9165): android.os.NetworkOnMainThreadException
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
11-09 08:24:55.566: E/AndroidRuntime(9165): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.backcountryskiers.avalanche.report.norcal.MainActivity.getBitmapFromURL(MainActivity.java:49)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.backcountryskiers.avalanche.report.norcal.MainActivity$fetcher.onPostExecute(MainActivity.java:102)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.backcountryskiers.avalanche.report.norcal.MainActivity$fetcher.onPostExecute(MainActivity.java:1)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.AsyncTask.finish(AsyncTask.java:631)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.Handler.dispatchMessage(Handler.java:99)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.os.Looper.loop(Looper.java:137)
11-09 08:24:55.566: E/AndroidRuntime(9165): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.lang.reflect.Method.invokeNative(Native Method)
11-09 08:24:55.566: E/AndroidRuntime(9165): at java.lang.reflect.Method.invoke(Method.java:511)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-09 08:24:55.566: E/AndroidRuntime(9165): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11-09 08:24:55.566: E/AndroidRuntime(9165): at dalvik.system.NativeStart.main(Native Method)
You're calling getBitmapFromURL from onPostExecute:
bimage = getBitmapFromURL(dangerRatingSrc);
onPreExecute and onPostExecute run on the UI thread. You need this code to be within doInBackground (as that's the part that runs on the new thread).
UPDATE: You can reorganize your code like this (as described in comments):
#Override
protected String doInBackground(String... params) {
try {
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
content = doc.select("#content");
parse = Jsoup.parse(doc.html());
results = doc.select("#content").outerHtml();
// find rating image...
dangerRatingImg = doc.select("img").first();
dangerRatingSrc = dangerRatingImg.absUrl("src");
// Get the rating image
bimage = getBitmapFromURL(dangerRatingSrc);
return results;
}
#Override
protected void onPostExecute(String result) {
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
// Set the rating image
image.setImageBitmap(bimage);
image.setPadding(10, 10, 10, 10);
image.setScaleType(ScaleType.FIT_XY);
// return the summary
results = parse.select("#reportSummary").outerHtml();
textView.setText(Html.fromHtml(results));
textView.setPadding(10, 10, 10, 10);
// ditch the dialog, it's all loaded.
dialog.dismiss();
}

FileInputStream in Another class?

I'm loading a file that has been saved by another class via the FileOutputstream method. Anyway, I want to load that file in another class, but it either gives me syntax errors or crashes my App.
The only tutorials I could find where they saved and loaded the file in the same class, but I want to load it up in another class and couldn't find how to solve the problem of loading into another class.
Thanks
My Code:
public class LogIn extends Activity implements OnClickListener {
EditText eTuser;
EditText eTpassword;
CheckBox StaySignedIn;
Button bSubmit;
String user;
String pass;
FileOutputStream fos;
FileInputStream fis = null;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
eTuser = (EditText) findViewById(R.id.eTuser);
eTpassword = (EditText) findViewById(R.id.eTpassword);
StaySignedIn = (CheckBox) findViewById(R.id.Cbstay);
bSubmit = (Button) findViewById(R.id.bLogIn);
bSubmit.setOnClickListener(this);
File file = getBaseContext().getFileStreamPath(FILENAME);
if (file.exists()) {
Intent i = new Intent(LogIn.this, ChatService.class);
startActivity(i);
}
// if if file exist close bracket
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch bracket
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch
} // create ends here
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
String user = eTuser.getText().toString();
String pass = eTpassword.getText().toString();
Bundle userandpass = new Bundle();
userandpass.putString("user", user);
userandpass.putString("pass", pass);
Intent login = new Intent(LogIn.this, logincheck.class);
login.putExtra("pass", user);
login.putExtra("user", pass);
startActivity(login);
if (StaySignedIn.isChecked())
;
String userstaysignedin = eTuser.getText().toString();
String passstaysignedin = eTpassword.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(userstaysignedin.getBytes());
fos.write(passstaysignedin.getBytes());
fos.close();
} catch (IOException e) {
// end of try bracket, before the Catch IOExceptions e.
e.printStackTrace();
} // end of catch bracket
} // switch and case ends here
}// Click ends here
}// main class ends here
Class B( Class that loads the data.)
public class ChatService extends Activity {
String collected = null;
FileInputStream fis = null;
String FILENAME;
TextView userandpass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
userandpass = (TextView) findViewById(R.id.textView1);
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] dataArray = null;
try {
dataArray = new byte[fis.available()];
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (fis.read(dataArray) != -1)
;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
// while statement
}
userandpass.setText(collected);
}// create ends here
}// class ends here
LogCat:
03-03 21:03:34.725: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-03 21:03:34.725: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.makeFilename(ContextImpl.java:1599)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.openFileInput(ContextImpl.java:399)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:25)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-03 21:03:34.725: E/AndroidRuntime(279): ... 11 more
The FILENAME string in the ChatService class is null. So you get a NullPointerException when you try to load a file using fis = openFileInput(FILENAME).
Also, your read loop throws away the data:
while (fis.read(dataArray) != -1)
;
It needs to collect the data and set the value of your collected String.
The stack trace tells you everything you need to know.
The error is a NullPointerException (meaning that you pass a null reference to a method expecting a non null reference, or that you call a method on a null reference).
The error occurs inside some android code (ContextWrapper.openFileInput()), which is called by your ChatService.onCreate() method, on line 25.
The line 25 is the following line:
fis = openFileInput(FILENAME);
So the error is clear: FILENAME is null. You haven't initialized it before this method is called.
I'm not sure about your program flow and if your two classes are running in the same thread, but it looks like you have a program flow issue. You are trying to open the file and getting a NullPointerException. Make sure the file is created and you have the correct reference to it before attempting to read.
If they are running in separate threads then you might try something like this:
try {
int waitTries=1;
fis = openFileInput(FILENAME);
while(fis.available()<EXPECTEDSIZE && waitTries++<10)
Tread.sleep(50);
}
If you know how large the file should be (EXPECTEDSIZE is some constant you will set), then this may be what you are looking for.

Categories