0

I am using this code, but it catches an error in a try-catch. Where is a mistake?

When I print a error, content.setText(ex.getMessage()); is empty.

Here is the relevant code:

public class MainActivity extends Activity {

    TextView content;
    EditText fname, email;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        content = (TextView) findViewById(R.id.content);
        Button saveme = (Button) findViewById(R.id.save);
        saveme.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getBaseContext(), "Please wait, connecting to server.", Toast.LENGTH_LONG).show();

                try {
                    String loginValue = URLEncoder.encode("ffa", "UTF-8");
                    String fnameValue = URLEncoder.encode("fdsfdb", "UTF-8");

                    HttpClient Client = new DefaultHttpClient();
                    String URL = "http://mysite/app.php?a=" + loginValue + "&b=" + fnameValue;

                    try {
                        String SetServerString;
                        HttpGet httpget = new HttpGet(URL);
                        ResponseHandler<String> responseHandler = new BasicResponseHandler();
                        SetServerString = Client.execute(httpget, responseHandler);
                        content.setText(SetServerString);
                    } catch (Exception ex) {
                        content.setText(ex.getMessage());
                    }
                } catch (UnsupportedEncodingException ex) {
                    content.setText(ex.getMessage());
                }
            }
        });
    }
}
Chris Forrence
  • 10,042
  • 11
  • 48
  • 64

3 Answers3

0

I think you get NetworkOnMainThreadException. You should perform network communication on background thread. Consider using IntentService or AsyncTask.

Nickolai Astashonok
  • 2,878
  • 3
  • 20
  • 23
0

I have same opinion with Nickolai.

Work around:

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

Use code above, only when you are writing code for yourself.


If your application are produced to others,you need a better way.

Better way:

You should use a handle to access http-request, more info in developer.android.com

Ninja
  • 2,479
  • 3
  • 23
  • 32
0

I use this myself:

ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
Etienne Bruines
  • 2,848
  • 3
  • 17
  • 25