Search code examples
androidnetwork-programmingnanohttpd

android, Force Close in a NanoHTTPD project


I'm implementing a custom web server by using NanoHTTPD. I have BaseServer class that extends NanoHTTPD:

public class BaseServer extends NanoHTTPD {

public BaseServer(int port) {
    super(port);
    // TODO Auto-generated constructor stub
}

@Override
public Response serve(String uri, Method method,
        Map<String, String> header, Map<String, String> parms,
        Map<String, String> files) {

    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    sb.append("<head><title>Debug Server</title></head>");
    sb.append("<body>");
    sb.append("<h1>Response</h1>");
    sb.append("<p><blockquote><b>URI -</b> ").append(uri).append("<br />");
    sb.append("<b>Method -</b> ").append(method)
            .append("</blockquote></p>");
    sb.append("<h3>Headers</h3><p><blockquote>").append(header)
            .append("</blockquote></p>");
    sb.append("<h3>Parms</h3><p><blockquote>").append(parms)
            .append("</blockquote></p>");
    sb.append("<h3>Files</h3><p><blockquote>").append(files)
            .append("</blockquote></p>");
    sb.append("</body>");
    sb.append("</html>");
    return new Response(sb.toString());

}

}

and an activity that use this class by this code:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        bs.start();
        Toast.makeText(this, "Server Started", 1).show();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Toast.makeText(this, e.getMessage(), 3).show();
    }
}

My server start correctly, but when I send a request from my browser, I have force close in my app !

when below code was executed(it is in try block), pointer go to final block!!! (Not cache) and I send a Force Close to my phone !!

ByteBuffer fbuf = f.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f.length());

f is null (no file sent!) and this code should handle this condition !, dosn't it?!


Solution

  • When you run on Android, and write temp files, you need to add a permission to your application. Without the permission, opening the file will throw an exception and bad things will result. Off the top of my head, I think the permission you need to add to your AndroidManifest.xml is

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    Try it and see!