Why does this FileOutputStream give a NullPointerException? - java

so I am running an app that creates a NullPointerException when I try to write a file.
My first activity (see below) calls the NewSet activity when the user presses the new set button. When I try to write the input in the NewSet activity, it throws a NullPointerException. Printing out fileOut displays me with it having a value of null, which it shouldn't. fileOut is declared globally, but initialized in onCreate. The Two classes are below. (... represents omitted code due to being irrelevant.)
public class MainActivity extends Activity {
static ArrayList sets;
FileOutputStream fileOut;
BufferedReader read;
String line;
ArrayAdapter<String> adapter;
ListView listView;
Intent newSetIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
newSetIntent=new Intent(this,NewSet.class);
listView=(ListView)findViewById(R.id.setList);
sets=new ArrayList();
try {
read=new BufferedReader(new BufferedReader(new InputStreamReader(openFileInput("SETS.txt"))));
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
System.out.println("File not found");
try {
fileOut.write("".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOE");
// TODO Auto-generated catch block
e.printStackTrace();
}
getSets();
toList();
super.onCreate(savedInstanceState);
}
...
public void newSet(String newSetName){
System.out.println(newSetName);
sets.add(newSetName);
try {
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
fileOut.write(newSetName.getBytes());
fileOut.write("\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException NPE){
System.out.println(fileOut);
NPE.printStackTrace();
}
}
}
public class NewSet extends Activity {
EditText input;
String setName;
MainActivity main;
...
public void submit(View view){
setName=input.getText().toString();
System.out.println("CREATING SET:"+setName);
main.newSet(setName);
finish();
}
}
The full stack trace
03-03 23:08:42.183: W/System.err(8435): java.lang.NullPointerException
03-03 23:08:42.183: W/System.err(8435): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:173)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.MainActivity.newSet(MainActivity.java:112)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.NewSet.submit(NewSet.java:35)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$1.onClick(View.java:3594)
03-03 23:08:42.193: W/System.err(8435): at android.view.View.performClick(View.java:4204)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$PerformClick.run(View.java:17355)
03-03 23:08:42.193: W/System.err(8435): at android.os.Handler.handleCallback(Handler.java:725)
03-03 23:08:42.203: W/System.err(8435): at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 23:08:42.203: W/System.err(8435): at android.os.Looper.loop(Looper.java:137)
03-03 23:08:42.203: W/System.err(8435): at android.app.ActivityThread.main(ActivityThread.java:5226)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-03 23:08:42.203: W/System.err(8435): at dalvik.system.NativeStart.main(Native Method)

Exception is getting thrown in android.content.ContextWrapper class. Method is:
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException
{
return mBase.openFileOutput(name, mode); // Line number 173
}
Here, the only possibility I see which could result in NullPointerException is data member mBase of type Context is NULL.
Can you check if Context data member is non-null.

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) 

Google Places API on Android: No route to host

I am using google places api in my application to show nearby food locations.
I'm using the following code:
public class Background extends AsyncTask<String, Integer, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected String doInBackground(String... params) {
pfr = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
lctn = "location=" + latitude + "," + longitude;
key = "&key=my key";
type = "&types=" + pfr.getString("type", "food");
radius = "&radius=" + pfr.getString("radius", "500");
sensor = "&sensor=false";
StringBuilder requesturl = new StringBuilder(googlegives);
requesturl.append(lctn);
requesturl.append(radius);
requesturl.append(type);
requesturl.append(key);
requesturl.append(sensor);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet req = new HttpGet(requesturl.toString());
Log.d("create", "0");
try {
HttpResponse res = client.execute(req);
HttpEntity jsonentity = res.getEntity();
String data = EntityUtils.toString(jsonentity);
JSONObject jsonobj = new JSONObject(data);
JSONArray resarray = jsonobj.getJSONArray("results");
if (resarray.length() == 0) {
Toast.makeText(getApplicationContext(), "nothing found",
Toast.LENGTH_LONG).show();
} else {
int len = resarray.length();
for (int j = 0; j < len; j++) {
lon = resarray.getJSONObject(j).getJSONObject("geometry")
.getJSONObject("location").getDouble("lng");
lat = resarray.getJSONObject(j).getJSONObject("geometry")
.getJSONObject("location").getDouble("lat");
LatLng latLng = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title(
resarray.getJSONObject(j).getJSONObject("name")
.toString())
.snippet(
resarray.getJSONObject(j)
.getJSONObject("formatted_address")
.toString()));
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
getting latitude and longitude as global variable for getting the user's current location, on running this application on my phone following appear in log cat
03-03 16:52:37.859: W/System.err(4780): java.net.SocketException: No route to host
03-03 16:52:37.906: W/System.err(4780): at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
03-03 16:52:37.906: W/System.err(4780): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
03-03 16:52:37.906: W/System.err(4780): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
03-03 16:52:37.914: W/System.err(4780): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
03-03 16:52:37.914: W/System.err(4780): at java.net.Socket.connect(Socket.java:1002)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-03 16:52:37.921: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-03 16:52:37.921: W/System.err(4780): at com.abhishekbietcs.locomap.Mapme$Background.doInBackground(Mapme.java:258)
03-03 16:52:37.921: W/System.err(4780): at com.abhishekbietcs.locomap.Mapme$Background.doInBackground(Mapme.java:1)
03-03 16:52:37.921: W/System.err(4780): at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-03 16:52:37.921: W/System.err(4780): at java.lang.Thread.run(Thread.java:1019)
Why is this exception being thrown? How can I get rid of it?
java.net.SocketException: No route to host.
This exception occur when there is no route to connect to host.
I found your problem here.
key = "&key=my key";
Replace this with
String APIKEY="AIzaSyDcLMS0IKQL3N76rO-aD2thfO46r96OCQI";
key = "&key=" + APIKEY;
and you have made wrong link.
Your link:
https://maps.googleapis.com/maps/api/place/nearbysearch/output?jsonlocation=25.4509294,78.630043&radius=15000&types=food&key=key&sensor=false
Link must be like:
String url = https://maps.googleapis.com/maps/api/place/search/json?location=25.4509294,78.630043&radius=15000&types=food&key=AIzaSyDcLMS0IKQL3N76rO-aD2thfO46r96OCQI&sensor=false
To get JSON you can use my code.
String data = getUrlContents(url); //Calling method
Definition of Method.
private String getUrlContents(String Url)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(Url);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}

setText causing a crash

For the better part of every day for the past week, I have been working on this project of controlling a textfield with the input of a potentiometer, and my setText command keeps crashing the program. I'm tired of tinkering and debugging but getting very little accomplished, and I need some help badly.
If you need to see all of the projects files, I can upload them as well.
Search for "This line causes a crash"
package edu.uidaho.pong;
import java.io.IOException;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import android.app.Activity;
import android.view.SurfaceHolder;
public class GameThread extends Thread {
/** Handle to the surface manager object we interact with */
private SurfaceHolder _surfaceHolder;
private Paint _paint;
private GameState _state;
public PongActivity _pong;
public GameThread(SurfaceHolder surfaceHolder, Context context,
Handler handler) {
_surfaceHolder = surfaceHolder;
_paint = new Paint();
_state = new GameState();
_pong = new PongActivity();
}
// #Override
public void run() {
while (true) {
Canvas canvas = _surfaceHolder.lockCanvas();
_state.update(_pong);
_state.draw(canvas, _paint);
_surfaceHolder.unlockCanvasAndPost(canvas);
int ret = 0;
byte[] buffer = new byte[16384];
int i;
int tempdebug = 0;
//while (true) { // read data
while (tempdebug++ < 10){
// try {
// ret = _pong.mInputStream.read(buffer);
// } catch (IOException e) {
// break;
// }
ret = 5; // let's pretend there's a 5 every time since I can't test the usb
i = 0;
while (i < ret) {
int len = ret - i;
if (len >= 1) {
Message m = Message.obtain(_pong.mHandler);
int value = (int)buffer[i];
// 'f' is the flag, use for your own logic
// value is the value from the arduino
m.obj = new ValueMsg('f', value);
_pong.mHandler.sendMessage(m);
}
i += 1; // number of bytes sent from arduino
}
}
//_pong.mResponseField.setText("Reading: "); This line causes a crash
}
}
public GameState getGameState() {
return _state;
}
}
Logcat output -
03-03 22:45:49.639: W/dalvikvm(381): threadid=9: thread exiting with uncaught exception (group=0x40015560)
03-03 22:45:49.639: E/AndroidRuntime(381): FATAL EXCEPTION: Thread-10
03-03 22:45:49.639: E/AndroidRuntime(381): java.lang.NullPointerException
03-03 22:45:49.639: E/AndroidRuntime(381): at edu.uidaho.pong.GameThread.run(GameThread.java:70)
03-03 22:45:50.189: E/global(381): Deprecated Thread methods are not supported.
03-03 22:45:50.189: E/global(381): java.lang.UnsupportedOperationException
03-03 22:45:50.189: E/global(381): at java.lang.VMThread.stop(VMThread.java:85)
03-03 22:45:50.189: E/global(381): at java.lang.Thread.stop(Thread.java:1280)
03-03 22:45:50.189: E/global(381): at java.lang.Thread.stop(Thread.java:1247)
03-03 22:45:50.189: E/global(381): at edu.uidaho.pong.GameView.surfaceDestroyed(GameView.java:46)
03-03 22:45:50.189: E/global(381): at android.view.SurfaceView.reportSurfaceDestroyed(SurfaceView.java:587)
03-03 22:45:50.189: E/global(381): at android.view.SurfaceView.updateWindow(SurfaceView.java:481)
03-03 22:45:50.189: E/global(381): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:213)
03-03 22:45:50.189: E/global(381): at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewRoot.performTraversals(ViewRoot.java:782)
03-03 22:45:50.189: E/global(381): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
03-03 22:45:50.189: E/global(381): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 22:45:50.189: E/global(381): at android.os.Looper.loop(Looper.java:130)
03-03 22:45:50.189: E/global(381): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-03 22:45:50.189: E/global(381): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 22:45:50.189: E/global(381): at java.lang.reflect.Method.invoke(Method.java:507)
03-03 22:45:50.189: E/global(381): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-03 22:45:50.189: E/global(381): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-03 22:45:50.189: E/global(381): at dalvik.system.NativeStart.main(Native Method)
I can't say exactly since there is no logcat, but this is probably happening because you're trying to change your TextView from a separate thread, which is prohibited in Android. One of the solutions to this problem is to put a reference to your Activity inside the class that runs a separate thread and place any View changing code inside the Activity.runOnUiThread() method, which takes a Runnable as the argument. Hope this helps.
EDIT
_pong.runOnUiThread(new Runnable() {
#Override
public void run() {
_pong.mResponseField.setText("Reading: ");
}
});

Somebody please explain the error

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

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