2014-02-07 195 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