1

I got this in my logcat and I don't know how to fix it because I'm newbie and don't really understand it. May anyone give me the answer.. This is the only error in my 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.

here's the code public class AndroidImageUploadActivity extends Activity implements OnClickListener{ /** Called when the activity is first created. */ Button upload,add; TextView status; 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 code

<?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!";

} ?>

meruvi
  • 11
  • 8

3 Answers3

0

The issue is saying that in one of your logging methods, Log.e() or System.out.println() is trying to print a null value.

What I like to do instead of doing null checks is to create a class that helps with this issue and then make log calls to the helper class instead.

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

You can use it the same way:

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

By using the above wrapper, you can avoid checking for null each time you log.

Tamby Kojak
  • 2,129
  • 1
  • 14
  • 25
0

Instead of this line. getName() is giving you null.

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

use this

e.printStackTrace();

This will be helpful: Use e.getStackTrace(), go through this array searching classname with your package name (using StackTraceElement.getClassName()). Then get the method name with StackTraceElement.getMethodName()

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
  • it adds another error..The method e(String, String) in the type Log is not applicable for the arguments (String, StackTraceElement[]) – meruvi Dec 26 '14 at 20:55
  • I've tried and put new log cat.. and anyway, would like to explain me.. where could i find "./upload/" ? since i just copy paste others work :( – meruvi Dec 26 '14 at 21:07
  • This error simply means you are making http query in main thread. Use Async taks. This will help you http://stackoverflow.com/questions/9671546/asynctask-android-example – Rohit5k2 Dec 26 '14 at 21:09
  • Also consider posting a new question about it. Your old problem is solved here. – Rohit5k2 Dec 26 '14 at 21:11
  • but mine did't use JSON.. do mean. i need to use JSON? – meruvi Dec 26 '14 at 21:19
  • You are uploading some data using internet. For that you need Async task. – Rohit5k2 Dec 26 '14 at 21:20
0

The error means that your are trying to print null to logcat. Essentially this:

Log.e(TAG, xxx);

where xxx is either

  • null
  • null object reference
  • object method call returning null

There are several places in your code where you use this:

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

Exceptions are not required to have a message. You're trying to print null.

Option 1 - the wrong

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

null gets converted to string and printed. Pro tip: You can use this to print integers easily.

Option 2 - the better

e.printStackTrace() 

This will print the message (if present) and the whole stack trace so you (and we) know where to look for the error.

EDIT: In light of new events

NetworkOnMainThreadException means that you can't just query network from your UI thread. Google IntentService (an SDK class) and EventBus (library). Use the first to communicate with your server on a background thread. The second is to post the result back to the activity. Both are well documented. And make sure you read the documentation (otherwise you might forget to declare a service in the manifest like me).

Community
  • 1
  • 1
Eugen Pechanec
  • 37,669
  • 7
  • 103
  • 124