2014-02-20 58 views
0

我對Android開發相當陌生。我仍然在學習,並與我可以在網上找到的示例代碼相處。示例代碼作爲活動但不作爲片段

我在試圖讓這個示例代碼在一個片段Activity中工作時遇到了一些麻煩,但是它可以作爲一個活動無縫地工作。我不知道我錯過了什麼。

Eclipse中保持突出的代碼的異常部位,因此很難調試

任何幫助,將不勝感激。

我會後兩個工作代碼和一個帶有錯誤:錯誤會粗體

//工作代碼

  package com.example.androidhive; 

      import java.util.ArrayList; 
      import java.util.List; 
      import org.apache.http.NameValuePair; 
      import org.apache.http.message.BasicNameValuePair; 
      import org.json.JSONException; 
      import org.json.JSONObject; 
      import android.app.Activity; 
      import android.app.ProgressDialog; 
      import android.content.Intent; 
      import android.os.AsyncTask; 
      import android.os.Bundle; 
      import android.util.Log; 
      import android.view.View; 
      import android.widget.Button; 
      import android.widget.EditText; 

      public class NewProductActivity extends Activity { 

       // Progress Dialog 
       private ProgressDialog pDialog; 

       JSONParser jsonParser = new JSONParser(); 
       EditText inputName; 
       EditText inputPrice; 
       EditText inputDesc; 

       // url to create new product 
       private static String url_create_product = "http://10.0.2.2/android_connect/create_product.php"; 

       // JSON Node names 
       private static final String TAG_SUCCESS = "success"; 

       @Override 
        public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.add_product); 

        // Edit Text 
        inputName = (EditText) findViewById(R.id.inputName); 
        inputPrice = (EditText) findViewById(R.id.inputPrice); 
        inputDesc = (EditText) findViewById(R.id.inputDesc); 

        // Create button 
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct); 

        // button click event 
        btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

         @Override 
         public void onClick(View view) { 
          // creating new product in background thread 
          new CreateNewProduct().execute(); 
         } 
        }); 
       } 

       /** 
       * Background Async Task to Create new product 
       * */ 
       class CreateNewProduct extends AsyncTask<String, String, String> { 

        /** 
        * Before starting background thread Show Progress Dialog 
        * */ 
        @Override 
        protected void onPreExecute() { 
         super.onPreExecute(); 
         pDialog = new ProgressDialog(NewProductActivity.this); 
         pDialog.setMessage("Creating Product.."); 
         pDialog.setIndeterminate(false); 
         pDialog.setCancelable(true); 
         pDialog.show(); 
        } 

        /** 
        * Creating product 
        * */ 
        protected String doInBackground(String... args) { 
         String name = inputName.getText().toString(); 
         String price = inputPrice.getText().toString(); 
         String description = inputDesc.getText().toString(); 

         // Building Parameters 
         List<NameValuePair> params = new ArrayList<NameValuePair>(); 
         params.add(new BasicNameValuePair("name", name)); 
         params.add(new BasicNameValuePair("price", price)); 
         params.add(new BasicNameValuePair("description", description)); 

         // getting JSON Object 
         // Note that create product url accepts POST method 
         JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
           "POST", params); 

         // check log cat fro response 
         Log.d("Create Response", json.toString()); 

         // check for success tag 
         try { 
          int success = json.getInt(TAG_SUCCESS); 

          if (success == 1) { 
           // successfully created product 
           Intent i = new Intent(getApplicationContext(), AllProductsActivity.class); 
           startActivity(i); 

           // closing this screen 
           finish(); 
          } else { 
           // failed to create product 
          } 
         } 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 done 
         pDialog.dismiss(); 
        } 

       } 
      } 

//非工作的代碼,把它變成一個片段後,

  package com.example.androidhive; 

      import android.app.Fragment; 
      import android.os.Bundle; 
      import android.view.LayoutInflater; 
      import android.view.View; 
      import android.view.ViewGroup; 
      import java.util.ArrayList; 
      import java.util.List; 
      import org.apache.http.NameValuePair; 
      import org.apache.http.message.BasicNameValuePair; 
      import org.json.JSONException; 
      import org.json.JSONObject; 
      import android.app.Activity; 
      import android.app.ProgressDialog; 
      import android.content.Intent; 
      import android.os.AsyncTask; 
      import android.os.Bundle; 
      import android.util.Log; 
      import android.view.View; 
      import android.widget.Button; 
      import android.widget.EditText; 


      public class AddProductsFragment extends **Fragment** { 

       public final int ARG_SECTION_NUMBER = 0; 

       @Override 
       public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
        View rootView = inflater.inflate(R.layout.add_product, 
          container, false); 

        return rootView; 
       } 

       // Progress Dialog 
       private ProgressDialog pDialog; 

       JSONParser jsonParser = new JSONParser(); 
       EditText inputName; 
       EditText inputPrice; 
       EditText inputDesc; 

       // url to create new product 
       private static String url_create_product = "http://10.0.2.2/android_connect/create_product.php"; 

       // JSON Node names 
       private static final String TAG_SUCCESS = "success"; 

       @Override 
       public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        **setContentView**(R.layout.add_product); 

        // Edit Text 
        inputName = (EditText) **findViewById**(R.id.inputName); 
        inputPrice = (EditText) **findViewById**(R.id.inputPrice); 
        inputDesc = (EditText) **findViewById**(R.id.inputDesc); 

        // Create button 
        Button btnCreateProduct = (Button) **findViewById**(R.id.btnCreateProduct); 

        // button click event 
        btnCreateProduct.setOnClickListener(new View.OnClickListener() { 

         @Override 
         public void onClick(View view) { 
          // creating new product in background thread 
          new CreateNewProduct().execute(); 
         } 
        }); 
       } 

       /** 
       * Background Async Task to Create new product 
       * */ 
       class CreateNewProduct extends AsyncTask<String, String, String> { 

        /** 
        * Before starting background thread Show Progress Dialog 
        * */ 
        @Override 
        protected void onPreExecute() { 
         super.onPreExecute(); 
         pDialog = new ProgressDialog(**AddProductFragment**.this); 
         pDialog.setMessage("Creating Product.."); 
         pDialog.setIndeterminate(false); 
         pDialog.setCancelable(true); 
         pDialog.show(); 
        } 

        /** 
        * Creating product 
        * */ 
        protected String doInBackground(String... args) { 
         String name = inputName.getText().toString(); 
         String price = inputPrice.getText().toString(); 
         String description = inputDesc.getText().toString(); 

         // Building Parameters 
         List<NameValuePair> params = new ArrayList<NameValuePair>(); 
         params.add(new BasicNameValuePair("name", name)); 
         params.add(new BasicNameValuePair("price", price)); 
         params.add(new BasicNameValuePair("description", description)); 

         // getting JSON Object 
         // Note that create product url accepts POST method 
         JSONObject json = jsonParser.makeHttpRequest(url_create_product, 
           "POST", params); 

         // check log cat fro response 
         Log.d("Create Response", json.toString()); 

         // check for success tag 
         try { 
          int success = json.getInt(TAG_SUCCESS); 

          if (success == 1) { 
           // successfully created product 
           Intent i = new Intent(**getApplicationContext**(), AllProductsActivity.class); 
           startActivity(i); 

           // closing this screen 
           **finish**(); 
          } else { 
           // failed to create product 
          } 
         } 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 done 
         pDialog.dismiss(); 
        } 

       } 
      } 

//我可能無法導入某些資產,事情是我不知道在哪裏可以糾正這個開始。

再次感謝您的時間和幫助。

親切的問候 埃德姆

+0

您應該首先了解片段:developer.android.com/guide/components/fragments.html –

回答

0

在片段,你應該得到的參考你的視覺元素onCreateView()方法,例如:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.add_product, container, false); 
    inputName = (EditText) view.findViewById(R.id.inputName); 
    return view; 
} 

如果你想使用findViewById()onCreateView()作爲已經被稱爲(稍後在片段的生命週期中),您可以使用getView()方法:

inputName = (EditText) getView().findViewById(R.id.inputName); 
+1

非常感謝! @Szymon它澄清了一點代碼,在編寫背景異步任務時,我是否需要覆蓋新的ProgressDialog(AddProductFragment.this);不同。在創建和調用新方法時仍然存在錯誤。再次感謝您的幫助。 – Royalty