Android java.lang.NullPointerException(2318):println需要一条消息

时间:2014-12-26 20:40:50

标签: android println

我在我的logcat中得到了这个,我不知道如何解决它,因为我是新手并且不太了解它。 愿任何人给我答案.. 这是我的logcat中唯一的错误

 12-27 03:50:53.953: D/libEGL(2370): loaded /system/lib/egl/libEGL_genymotion.so
12-27 03:50:53.957: D/libEGL(2370): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
12-27 03:50:53.961: D/libEGL(2370): loaded /system/lib/egl/libGLESv2_genymotion.so
12-27 03:50:54.061: W/EGL_genymotion(2370): eglSurfaceAttrib not implemented
12-27 03:50:54.065: E/OpenGLRenderer(2370): Getting MAX_TEXTURE_SIZE from GradienCache
12-27 03:50:54.077: E/OpenGLRenderer(2370): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
12-27 03:50:54.081: D/OpenGLRenderer(2370): Enabling debug mode 0
12-27 03:50:54.581: I/Choreographer(2370): Skipped 45 frames!  The application may be doing too much work on its main thread.
12-27 03:50:57.965: W/IInputConnectionWrapper(2370): showStatusIcon on inactive InputConnection
12-27 03:51:05.857: D/dalvikvm(2370): GC_FOR_ALLOC freed 70K, 7% free 4279K/4576K, paused 7ms, total 8ms
12-27 03:51:05.941: I/dalvikvm-heap(2370): Grow heap (frag case) to 31.387MB for 28311564-byte allocation
12-27 03:51:05.953: D/dalvikvm(2370): GC_FOR_ALLOC freed 1K, 1% free 31926K/32228K, paused 10ms, total 10ms
12-27 03:51:06.761: D/dalvikvm(2370): GC_FOR_ALLOC freed 2014K, 7% free 30922K/33220K, paused 5ms, total 5ms
12-27 03:51:06.945: D/dalvikvm(2370): GC_FOR_ALLOC freed 510K, 6% free 31434K/33220K, paused 3ms, total 3ms
12-27 03:51:06.945: I/dalvikvm-heap(2370): Grow heap (frag case) to 32.904MB for 2095116-byte allocation
12-27 03:51:07.033: D/dalvikvm(2370): GC_FOR_ALLOC freed 1026K, 8% free 32453K/35268K, paused 2ms, total 2ms
12-27 03:51:07.037: I/dalvikvm-heap(2370): Grow heap (frag case) to 33.110MB for 1266788-byte allocation
12-27 03:51:07.045: D/dalvikvm(2370): GC_FOR_ALLOC freed 0K, 8% free 33691K/36508K, paused 4ms, total 4ms
12-27 03:51:07.077: E/java.lang.NullPointerException(2370): println needs a message
12-27 03:51:07.081: I/Choreographer(2370): Skipped 74 frames!  The application may be doing too much work on its main thread.

这里是代码     公共类AndroidImageUploadActivity扩展Activity实现OnClickListener {     /** 在第一次创建活动时调用。 * /     按钮上传,添加;     TextView状态;     EditText nama;

//variable for upload data into http
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;

Bitmap bm;

static String pathToOurFile = "",format;
String urlServer = "http://10.0.3.2/imageupload/upload.php";
String lineEnd = "\r\n",twoHyphens = "--",boundary =  "*****";

private static final int SELECT_PICTURE = 0;

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    upload=(Button)findViewById(R.id.btnChooseImage);
    upload.setOnClickListener(this);
    add=(Button)findViewById(R.id.btnAddImage);
    add.setOnClickListener(this);
    status=(TextView)findViewById(R.id.txtStatusGambar);
    nama=(EditText)findViewById(R.id.editNama); 
   }

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.btnChooseImage:
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"),SELECT_PICTURE);
        break;
    case R.id.btnAddImage:
        try {
            bm = BitmapFactory.decodeFile(pathToOurFile);
            executeMultipartPost();
            } catch (Exception e) {
                Log.e(e.getClass().getName(),e.getMessage());
            }
        break;
    default:
        break;
    }
    } 

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        status.setText(data.getData().toString());
        String[] projection = { MediaStore.Images.Media.DATA };

        Cursor cursor = managedQuery(data.getData(), projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(column_index);
        cursor.close();
        pathToOurFile=filePath;
        format = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
    }
   }    
        public void executeMultipartPost() throws Exception {
           try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.JPEG, 75, bos);
        byte[] data = bos.toByteArray();
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(urlServer);
        ByteArrayBody bab = new ByteArrayBody(data, nama.getText().toString()+"."+format);
        MultipartEntity reqEntity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("uploaded", bab);
                reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
                postRequest.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                        String sResponse;
                        StringBuilder s = new StringBuilder();

                        while ((sResponse = reader.readLine()) != null) {
                            s = s.append(sResponse);
                        }
                        Toast.makeText(this, "Penambahan data berhasil", 1).show();
                        System.out.println("Response:—————————————————————————————————————————-> " + s);
      } catch (Exception e) {
        // handle exception here
        Log.e(e.getClass().getName(), e.getMessage());
    }
  }
  }

new logcat

12-27 04:00:53.481: W/System.err(2825): android.os.NetworkOnMainThreadException
12-27 04:00:53.485: W/System.err(2825):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-27 04:00:53.485: W/System.err(2825):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
12-27 04:00:53.485: W/System.err(2825):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-27 04:00:53.485: W/System.err(2825):     at libcore.io.IoBridge.connect(IoBridge.java:112)
12-27 04:00:53.485: W/System.err(2825):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-27 04:00:53.493: W/System.err(2825):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-27 04:00:53.493: W/System.err(2825):     at java.net.Socket.connect(Socket.java:842)
12-27 04:00:53.493: W/System.err(2825):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-27 04:00:53.493: W/System.err(2825):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
 12-27 04:00:53.493: W/System.err(2825):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
 12-27 04:00:53.493: W/System.err(2825):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
 12-27 04:00:53.493: W/System.err(2825):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
 12-27 04:00:53.493: W/System.err(2825):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-27 04:00:53.493: W/System.err(2825):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-27 04:00:53.493: W/System.err(2825):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-27 04:00:53.493: W/System.err(2825):     at com.eepis.android.AndroidImageUploadActivity.executeMultipartPost(AndroidImageUploadActivity.java:124)
12-27 04:00:53.493: W/System.err(2825):     at com.eepis.android.AndroidImageUploadActivity.onClick(AndroidImageUploadActivity.java:84)
12-27 04:00:53.493: W/System.err(2825):     at android.view.View.performClick(View.java:4240)
12-27 04:00:53.493: W/System.err(2825):     at android.view.View$PerformClick.run(View.java:17721)
12-27 04:00:53.493: W/System.err(2825):     at android.os.Handler.handleCallback(Handler.java:730)
12-27 04:00:53.493: W/System.err(2825):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-27 04:00:53.493: W/System.err(2825):     at android.os.Looper.loop(Looper.java:137)
12-27 04:00:53.493: W/System.err(2825):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-27 04:00:53.493: W/System.err(2825):     at java.lang.reflect.Method.invokeNative(Native Method)
12-27 04:00:53.493: W/System.err(2825):     at java.lang.reflect.Method.invoke(Method.java:525)
12-27 04:00:53.493: W/System.err(2825):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-27 04:00:53.493: W/System.err(2825):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-27 04:00:53.493: W/System.err(2825):     at dalvik.system.NativeStart.main(Native Method)
12-27 04:00:53.493: I/Choreographer(2825): Skipped 51 frames!  The application may be doing too much work on its main thread.

PHP代码

<?php
$target_path  = "./upload/";
$target_path = $target_path . basename( $_FILES['uploaded']['name']);
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target_path)) {
echo "The file ".  basename( $_FILES['uploaded']['name']).
" has been uploaded";
} else{
 echo "Gagal Bung!";

}    ?&GT;

3 个答案:

答案 0 :(得分:0)

问题在于,在您的某种日志记录方法中,Log.e()System.out.println()正在尝试打印null值。

我喜欢做的不是做空检查,而是创建一个帮助解决这个问题的类,然后对helper类进行日志调用。

public class TKLog {
    public static void d(String TAG, Object... messages) {
        for (Object message : messages) {
            Log.d(TAG, getToPrintFromObject(message));
        }
    }

    public static void e(String TAG, Object... messages) {
        for (Object message : messages) {
            Log.e(TAG, getToPrintFromObject(message));
        }
    }

    public static void i(String TAG, Object... messages) {
        for (Object message : messages) {
            Log.i(TAG, getToPrintFromObject(message));
        }
    }

    public static void v(String TAG, Object... messages) {
        for (Object message : messages) {
            Log.v(TAG, getToPrintFromObject(message));
        }
    }

    public static void w(String TAG, Object... messages) {
        for (Object message : messages) {
            Log.w(TAG, getToPrintFromObject(message));
        }
    }

    private static String getToPrintFromObject(Object object) {
        return (String) ((object == null) ? "null" : ((object instanceof String) ? object : object.toString()));
    }
}

你可以用同样的方式使用它:

TKLog.e(TAG, "Test Log");

通过使用上面的包装器,您可以避免每次登录时检查null。

答案 1 :(得分:0)

而不是这一行。 getName()给你null。

Log.e(e.getClass().getName(),e.getMessage());

使用此

e.printStackTrace();

这会有所帮助: 使用e.getStackTrace(),使用您的包名称(使用StackTraceElement.getClassName())查看此数组搜索类名。然后使用StackTraceElement.getMethodName()

获取方法名称

答案 2 :(得分:0)

错误意味着您正在尝试将null打印到logcat。基本上就是这样:

Log.e(TAG, xxx);

其中xxx

  • null对象引用
  • 对象方法调用返回null

您的代码中有几处使用它:

Log.e(e.getClass().getName(), e.getMessage()); // just... don't

获取消息不需要例外。您正在尝试打印null

选项1 - 错误的

Log.e(e.getClass().getName(), e.getMessage() + ""); // will print the message or "null"

null转换为字符串并打印。专业提示:您可以使用它轻松打印整数。

选项2 - 更好

e.printStackTrace() 

这将打印消息(如果存在)和整个堆栈跟踪,以便您(以及我们)知道在哪里查找错误。

编辑:根据新事件

NetworkOnMainThreadException意味着您不能只从UI线程中查询网络。 Google IntentService(SDK类)和EventBus(库)。使用第一个在后台线程上与您的服务器通信。第二种是将结果发布回活动。两者都有很好的记录。并确保您阅读文档(否则您可能忘记在清单中声明服务,如我)。