Hi Please Can someone help me look at this code? Don't know what am doing wrong,But the try block doesn't run. instead it goes to the catch block.

public void onClick(View arg0) {
    //Toast.makeText(getBaseContext(), "connecting",Toast.LENGTH_SHORT).show();
    // TODO Auto-generated method stub
    httpclient = new DefaultHttpClient();
    htpost = new HttpPost("http://10.0.2.2/fanaticmobile/log_in.php");
    uname= username.getText().toString();
    pass= password.getText().toString();

    try {
        namearray = new ArrayList<NameValuePair>();

        namearray.add(new BasicNameValuePair("username", uname));
        namearray.add(new BasicNameValuePair("password", pass));
        htpost.setEntity(new UrlEncodedFormEntity(namearray));
        response= httpclient.execute(htpost);
        if(response.getStatusLine().getStatusCode()==200){
            entity= response.getEntity();

            if(entity != null){
                InputStream stream = entity.getContent();

                JSONObject jresponse = new JSONObject(ConvertInput(stream));
                String logged= jresponse.getString("logged");
                login_err.setText(""+logged);
                if(logged.equals("true")){
                    Toast.makeText(getBaseContext(), "Successfull",Toast.LENGTH_SHORT).show();
                    //String retname= jresponse.getString("name");
                    //String  retmail= jresponse.getString("email");
                }else if(logged.equals("false")){
                    String message=jresponse.getString("message");
                    Toast.makeText(getBaseContext(), message,Toast.LENGTH_SHORT).show();
                }

            }
        }else{

        }

    } 
    catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getBaseContext(), "Poor Connection",Toast.LENGTH_SHORT).show();
    }

}//

This is the function to read the json object

private static String ConvertInput(InputStream is){
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line ="";

    try {
        while((line = reader.readLine())!= null){
            sb.append("\n");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        try {
            is.close();
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
  return sb.toString();
}// end of convert function

Please am new to this and i followed a tutorial to this point,but mine is not working. Have set permission(internet) in the manifest file

有帮助吗?

解决方案

I have a suggestion Try to Use AsyncHttpclient for getting responses from server no need of this long codes.

http://loopj.com/android-async-http/

 AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
RequestParams params=new RequestParams();
        params.put("username", uname);
        params.put("password", pass);
            asyncHttpClient.post("http://10.0.2.2/fanaticmobile/log_in.php", params,new AsyncHttpResponseHandler(){
                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    // TODO Auto-generated method stub
                    super.onFailure(arg0, arg1);
                }
                @Override
                public void onSuccess(String arg0) {
                    // TODO Auto-generated method stub
                    super.onSuccess(arg0);
                }
            });

Just include the jar file in your project it will be simple to use.

其他提示

Like already been stated in the comments, you're running a network operation in your main thread (the UI thread). This is not only discouraged (lengthy operations should never use the Main Thread), but also forbidden in the case of networking.

response= httpclient.execute(htpost)

^ this fails.

Read how to move that code to an AsyncTask and do it the right way in the official google reference. Googling AsyncTask will help too.

A Pseudo Code version would be:

public class YourTask extends AsyncTask<Void, Void, Void>{
    YourListener mListener;
    public YourTask(final YourListener listener) {
        mListener = listener;
    }
    @Override
    protected Void doInBackground(final Void... params) {
        // do your lengthy operation here
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        mListener.onVeryLongTaskDone();
    }
    public interface YourListener {
        public void onVeryLongTaskDone();
    }
}

Then make your activity implement that "YourListener" interface and the method onVeryLongTaskDone() will be called.

How do you start the task?

in your onClick method:

(new YourTask(YourActivityName.this)).execute();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top