1

I am trying to get the response code for the HttpReponse. I have changed the method for getting the response but it is not working.

Before I used this try & catch: (url is parameter for function)

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);

        if (params != null) {
            method.setEntity(new UrlEncodedFormEntity(params));
        }

        HttpResponse response = httpclient .execute(method);

        InputStream inputStream = response.getEntity().getContent();
        String result = convertInputStreamToString(inputStream);

        return result;
    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

But this code gave me a runtime error in HttpResponse response = httpclient .execute(method);

So I changed my code:

public class RegisterActivity extends Activity {

String      username;
String      password;
InputStream is     = null;
String      result = null;
String      line   = null;
int         code;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);
    final EditText usernamefield = (EditText) findViewById(R.id.username_reg);
    final EditText passwordfield = (EditText) findViewById(R.id.password_reg);
    Button reg_btn = (Button) findViewById(R.id.reg_btn);
    reg_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            username = usernamefield.getText().toString();
            password = passwordfield.getText().toString();
            insert();
            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", usernamefield.getText().toString()));
            params.add(new BasicNameValuePair("password", passwordfield.getText().toString()));
            params.add(new BasicNameValuePair("action", "insert"));

        }
    });

}


public void insert()
{
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    nameValuePairs.add(new BasicNameValuePair("action", "insert"));

    try
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.10/ferdos/service.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("pass 1", "connection success ");
    }
    catch (Exception e)
    {
        Log.e("Fail 1", e.toString());
        Toast.makeText(getApplicationContext(), "Invalid IP Address",
                Toast.LENGTH_LONG).show();
    }

    try
    {
        BufferedReader reader = new BufferedReader
                (new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
        Log.e("pass 2", "connection success ");
    }
    catch (Exception e)
    {
        Log.e("Fail 2", e.toString());
    }

    try
    {
        JSONObject json_data = new JSONObject(result);
        code = (json_data.getInt("code"));

        if (code == 1)
        {
            Toast.makeText(getBaseContext(), "Inserted Successfully",
                    Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(getBaseContext(), "Sorry, Try Again",
                    Toast.LENGTH_LONG).show();
        }
    }
    catch (Exception e)
    {
        Log.e("Fail 3", e.toString());
    }
}}

Please help me with this code to solve my problem.

Theo
  • 57,719
  • 8
  • 24
  • 41
kamal
  • 330
  • 3
  • 13

2 Answers2

2

Thats what Google says.

To avoid creating an unresponsive UI, don't perform network operations on the UI thread. By default, Android 3.0 (API level 11) and higher requires you to perform network operations on a thread other than the main UI thread; if you don't, a NetworkOnMainThreadException is thrown.

You need to execute your HTTP requests in separate thread. This can be done in a AsyncTask.

In your case you need to update UI after the downloading is finished. Use a listener to notify the UI thread

public interface ResultsListener {
    public void onResultsSucceeded(String result);
}

This is an example from Google developers guide. I edited it and it calls the listener when the result is finished.

 private class HttpRequestTask extends AsyncTask<URL, Integer, String> {

      public void setOnResultsListener(ResultsListener listener) {
           this.listener = listener;
      }

      protected String doInBackground(URL... urls) {
         int count = urls.length;
         for (int i = 0; i < count; i++) {
             String httpResult = // Do your HTTP requests here
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return httpResult;
     }

     // use this method if you need to show the progress (eg. in a progress bar in your UI)
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
     // this method is called after the download finished.
     protected void onPostExecute(String result) {
         showDialog("Downloaded " + result);
         listener.onResultsSucceded(result);
     }
 }

Now you can execute the task by calling new HttpRequestTask().execute(url) in your Activity. Your activity needs to implement the ResultsListener. Inside the onResultsSucceeded method you can update your UI elements.

You see, you can use the AsyncTask in your example pretty well. You just need some reformatting of your code.

Alina J
  • 155
  • 1
  • 10
0

I use AsyncTask but dont working again please check my code

public class RegisterActivity extends Activity {

EditText editusername;
EditText editpassword;
String   username;
String   password;


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);
    editusername = (EditText) findViewById(R.id.username_reg);
    editpassword = (EditText) findViewById(R.id.password_reg);

    Button reg_btn = (Button) findViewById(R.id.reg_btn);
    reg_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            username = editusername.getText().toString();
            password = editpassword.getText().toString();
            new RegisterAsyncTask().execute();
        }
    });
}


class RegisterAsyncTask extends AsyncTask<Void, Void, Boolean> {

    private void postData(String username, String password) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("myurl");

        try {
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));
            nameValuePairs.add(new BasicNameValuePair("action", "insert"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
        }
        catch (Exception e)
        {
            Log.e("log_tag", "Error:  " + e.toString());
        }
    }


    @Override
    protected Boolean doInBackground(Void... params) {
        postData(username, password);
        return null;
    }
}}
kamal
  • 330
  • 3
  • 13