代码在HttpResponse之后没有执行

时间:2014-02-07 11:28:49

标签: android json web-services

我刚刚开始使用webservices.I刚刚在教程中使用了代码表单并在我的项目中实现它。以下是我的代码,但它不能正常工作,

LoginScreen.java

            public class LoginScreen extends Activity implements OnClickListener
            {
                EditText edittextloginusername;
                EditText edittextloginpassword;
                // Progress Dialog
                private ProgressDialog pDialog;
                // JSON parser class
                JSONParser jsonParser = new JSONParser();
                //PHP Login script location
                private static final String LOGIN_URL = "http://xxx.xxx.x.xxx/Json_Login/login.php";
                private static final String TAG_SUCCESS = "success";
                @Override
                protected void onCreate(Bundle savedInstanceState)
                {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_login_screen);
                    initialize();
                }
                //Initialization of components
                private void initialize() {
                    //Getting the reference of font from assets folder
                    String fontPath = "Font/Arsenal-Regular.otf";
                    Typeface tf = Typeface.createFromAsset(getAssets(),fontPath);
                  //Getting the reference of EditText
                    edittextloginusername=(EditText)findViewById(R.id.editTextLoginusername);
                    edittextloginpassword=(EditText)findViewById(R.id.editTextLoginpassword);
                    //Getting references of buttons
                    Button buttonlogin=(Button)findViewById(R.id.buttonlogin);
                       //set on click listener on buttons
                    buttonlogin.setOnClickListener(this);
                }//end of Initialization
                //on click method   
                @Override
                public void onClick(View v) {
                    if(v.getId()==R.id.buttonlogin){
                        new AttemptLogin().execute();
                        Intent intent=new Intent(LoginScreen.this,MenuScreen.class);
                        startActivity(intent);
                        finish();
                     }
                    }//end of on click
                @Override
                public void onBackPressed(){
                    finish();
                    super.onBackPressed();
                }

                //AsyncTask is a separate thread than the thread that runs the GUI
                //Any type of networking should be done with asynctask.
                public class AttemptLogin extends AsyncTask<String, String, String> 
                {
                        //three methods get called, first preExecture, then do in background, and once do
                        //in back ground is completed, the onPost executer method will be called.
                        // Before starting background thread Show Progress Dialog
                        @Override
                        protected void onPreExecute() 
                        {
                                super.onPreExecute();
                                pDialog = new ProgressDialog(LoginScreen.this);
                                pDialog.setMessage("Attempting login...");
                                pDialog.setIndeterminate(false);
                                pDialog.setCancelable(true);
                                pDialog.show();
                        }
                        @Override
                        protected String doInBackground(String... args) 
                        {
                            // Check for success tag
                            int success;
                            String username = edittextloginusername.getText().toString();
                            String password = edittextloginpassword.getText().toString();
                            try{
                                    // Building Parameters
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair("userName", username));
                                    params.add(new BasicNameValuePair("userPassword", password));
                                    Log.d("request!", "starting");
                                    // getting login details by making HTTP request
                                    JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
                                    // check your log for json response
                                    Log.d("Login attempt", "Login attempt: "+json.toString());

                                    // json success tag
                                    success = json.getInt(TAG_SUCCESS);
                                    Log.d("Log in background","success"+success);
                                    if (success == 1) {
                                        Log.d("Login Successful!", json.toString());
                                        Intent i = new Intent(LoginScreen.this, MenuScreen.class);
                                        finish();
                                        startActivity(i);
                                        return json.getString("Login Successful");
                                    }else{
                                        Log.d("Login Failure!","Login Fail...");
                                        return "Fail";
                                    }
                            }catch(JSONException e){
                                e.printStackTrace();
                            }
                            return null;
                        }
                        //After completing background task Dismiss the progress dialog
                        protected void onPostExecute(String file_url) 
                        {
                            // dismiss the dialog once product deleted
                            pDialog.dismiss();
                            Toast.makeText(getApplicationContext(),file_url,Toast.LENGTH_SHORT).show();
                        }
                }

            }

JSONParser.java

            public class JSONParser {
                static InputStream is = null;
                static JSONObject jObj = null;
                static String json = "";
                // constructor
                public JSONParser() {
                }
                public JSONObject getJSONFromUrl(final String url) {
                    // Making HTTP request
                    try {
                        // Construct the client and the HTTP request.
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost httpPost = new HttpPost(url);

                        // Execute the POST request and store the response locally.
                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        // Extract data from the response.
                        HttpEntity httpEntity = httpResponse.getEntity();
                        // Open an inputStream with the data content.
                        is = httpEntity.getContent();

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        // Create a BufferedReader to parse through the inputStream.
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                        // Declare a string builder to help with the parsing.
                        StringBuilder sb = new StringBuilder();
                        // Declare a string to store the JSON object data in string form.
                        String line = null;
                       // Build the string until null.
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                       // Close the input stream.
                        is.close();
                        // Convert the string builder data to an actual string.
                        json = sb.toString();
                    } catch (Exception e) {
                        Log.e("Buffer Error", "Error converting result " + e.toString());
                    }
                    // Try to parse the string to a JSON object
                    try {
                        jObj = new JSONObject(json);
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    }
                    // Return the JSON Object.
                    return jObj;
                }
                // function get json from url
                // by making HTTP POST or GET mehtod
                public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
                    // Making HTTP request
                    try {
                        // check for request method
                        if(method == "POST"){
                            // request method is POST
                            // defaultHttpClient
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            HttpPost httpPost = new HttpPost(url);
                            httpPost.setEntity(new UrlEncodedFormEntity(params));
                            HttpResponse httpResponse = httpClient.execute(httpPost);
                            HttpEntity httpEntity = httpResponse.getEntity();
                            is = httpEntity.getContent();
                        }else if(method == "GET"){
                            // request method is GET
                            Log.d("Log in background","4.1");
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            String paramString = URLEncodedUtils.format(params, "utf-8");
                            Log.d("Log in background","4.2");
                            url += "?" + paramString;
                            Log.d("Log in background","4.3");
                            HttpGet httpGet = new HttpGet(url);
                            Log.d("Log in background","4.4");
                            HttpResponse httpResponse = httpClient.execute(httpGet);
                            Log.d("Log in background","4.5");
                            HttpEntity httpEntity = httpResponse.getEntity();
                            is = httpEntity.getContent();
                        }           
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();
                        json = sb.toString();
                    } catch (Exception e) {
                        Log.e("Buffer Error", "Error converting result " + e.toString());
                    }
                    // try parse the string to a JSON object
                    try {
                        jObj = new JSONObject(json);
                    } catch (JSONException e) {
                        Log.e("JSON Parser", "Error parsing data " + e.toString());
                    }
                    // return JSON String
                    return jObj;
                }
            }

我不知道我在里面缺少什么,

1 个答案:

答案 0 :(得分:0)

这里要理解的主要是你无法从后台线程调用startActivity()方法,因为它可能会导致奇怪的竞争条件。相反,您需要将runnable发布到主线程的消息队列以在主线程上执行。您还在清单文件中添加了INTERNET权限。

相关问题