2

These codes are executed after a button is pressed. I'm trying to send the strings data to the php file in my server. But the application has stopped after i pressed the button. Can i know whats the problem here? Any helps are really appreciated :D

        HttpClient client = new DefaultHttpClient();
        HttpPost hpost = new HttpPost("http://myservername.com/postTest.php");
        status = mStatus.getText().toString();
        event = mEvent.getText().toString();
        time = mTime.getText().toString();
        try{
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("status", status));
            nameValuePairs.add(new BasicNameValuePair("event", event));
            nameValuePairs.add(new BasicNameValuePair("time", time));
            hpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            client.execute(hpost);
            mStatus.setText("");
            mEvent.setText("");
            mTime.setText("");
        }catch (UnsupportedEncodingException e){
            Toast.makeText(this, "Unsupported Encoding Exception " + e.getMessage(), Toast.LENGTH_LONG).show();
        }catch (ClientProtocolException e){
            Toast.makeText(this, "Client Protocol Exception " + e.getMessage(), Toast.LENGTH_LONG).show();
        }catch (IOException e){
            Toast.makeText(this, "IO Exception "+e.getMessage(), Toast.LENGTH_LONG).show();
        }
Masukami
  • 17
  • 1

2 Answers2

2

put your code to thread

new Thread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        // do something
    }
}).start();

and check your AndroidManifest.xml permission

<uses-permission android:name="android.permission.INTERNET"/>
henry4343
  • 3,871
  • 5
  • 22
  • 30
0

Probably problems is:

  1. You Trying to send data from UI Thread. It can be resolved by using Thread class:

    new Thread(){ @Override public void run(){ // your sending code herre } }.start();

  2. If you using another thread you can't show Toast in your Thread. It can be resolved using runOnUIThread(Runnable) method of Activity

    }catch (UnsupportedEncodingException e){ runOnUITehread(new Runnable(){ @Override public void run(){ Toast.makeText(this, "Unsupported Encoding Exception " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); }

    Or using Handler

  3. You have an NullPointerException

Roman Black
  • 3,501
  • 1
  • 22
  • 31