2014-02-07 49 views
1

我刚开始工作webservices.I刚上任代码形式的教程和特林实现它在我的project.Following是我的代码,但它不工作,因为我想,,,代码不执行

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

Log.d(“登录后台”,“4.5”);不执行手段有问题一些与“HttpResponse httpResponse = HttpClient.execute(httpGet);”。 – Akshay

回答

0

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

+0

谢谢先生,我从来没有想过这个.. – Akshay