在2个活动android之间传递数据

时间:2014-05-09 15:48:36

标签: android variables android-intent

所以我有这个问题在我的android项目中通过2个活动传递数据,我不知道我做错了什么病我试着以简单的方式解释我的问题。我有2个活动,我想将2个不同的值传递给不同的活动。我做了这个

1活动:

 public class Linhas_pesagem extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

ListAdapter adapter;

String id2;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products =   "http://10.0.2.2/webprojecto4/ler_linha_doc.php";

 // url to get all products list
 private static String url_delete_products = "http://10.0.2.2/webprojecto4/eliminar_linha.php";


// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "lin_doc";
private static final String TAG_ID = "id";
private static final String TAG_ESTAB = "estab";
private static final String TAG_DATA = "dt";
private static final String TAG_HORA = "hr";
private static final String TAG_QTD = "quantidade";

// products JSONArray
JSONArray products = null;

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

    Intent i = getIntent();

    // getting product id (pid) from intent
    id2 = i.getStringExtra(TAG_ID);


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

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

        @Override
        public void onClick(View view) {
            // creating new product in background thread
            Intent in = new Intent(getApplicationContext(),
                    Newlin_ProductActivity.class);

            in.putExtra(TAG_ID, id2);



            startActivity(in);
        }
    });



    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    registerForContextMenu(lv);
    // on seleting single product
    // launching Edit Product Screen
    // on seleting single product
    // launching Edit Product Screen



}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Linhas_pesagem.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters


        try {
             List<NameValuePair> params = new ArrayList<NameValuePair>();
             params.add(new BasicNameValuePair("id", id2));
             // getting JSON string from URL
             JSONObject json = jParser.makeHttpRequest(url_all_products, "POST", params);

             // Check your log cat for JSON reponse
             Log.d("All Products: ", json.toString());
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);


                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String id_estab = c.getString(TAG_ESTAB);                    
                    String dt = c.getString(TAG_DATA);
                    String hr = c.getString(TAG_HORA);
                    String quantidade = c.getString(TAG_QTD);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();
                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_ESTAB, id_estab);
                    map.put(TAG_DATA, dt);
                    map.put(TAG_HORA, hr);
                    map.put(TAG_QTD, quantidade);
                    // adding HashList to ArrayList
                    productsList.add(map);
                } 
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getApplicationContext(),
                        Newlin_ProductActivity.class);
                // Closing all previous activities


                i.putExtra(TAG_ID, id2);



                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
            adapter = new SimpleAdapter(
                        Linhas_pesagem.this, productsList,
                        R.layout.list_lin_items, new String[] { TAG_ID,
                                TAG_ESTAB, TAG_DATA, TAG_HORA, TAG_QTD},
                        new int[] { R.id.id, R.id.id_estab, R.id.dt, R.id.hr, R.id.quantidade});
                // updating listview
                setListAdapter(adapter);



                EditText inputSearch = (EditText)findViewById(R.id.editText1);

                /**
                 * Enabling Search Filter
                 * */
                inputSearch.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                        // When user changed the Text
                        ((SimpleAdapter)    Linhas_pesagem.this.adapter).getFilter().filter(cs);   
                    }

                    @Override
                    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                            int arg3) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void afterTextChanged(Editable arg0) {
                        // TODO Auto-generated method stub                          
                    }

                });


            }
        });

    }

}



/*****************************************************************
 * Background Async Task to Delete Product
 * */
class DeleteProduct extends AsyncTask<String, String, String> {

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

    /**
     * Deleting product
     * */
    protected String doInBackground(String... args) {
         String id = args[0];
        // Check for success tag
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id", id));

            // getting product details by making HTTP request
            JSONObject json = jParser.makeHttpRequest(
                    url_delete_products, "POST", params);

            // check your log for json response
            Log.d("Delete Product", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // product successfully deleted
                // notify previous activity by sending code 100
                Intent i = getIntent();
                // send result code 100 to notify about product deletion
                setResult(100, i);
                finish();
            }
        } 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();

    }

}



@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
    getMenuInflater().inflate(R.menu.context, menu);


}

public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
    case R.id.item1:
        HashMap <String, String> product2 = productsList.get(info.position);
        String id9 = product2.get("id");
        String id3 = product2.get(TAG_DATA);
        String id4 = product2.get(TAG_ESTAB);
        String id5 = product2.get(TAG_HORA);
        String id6 = product2.get(TAG_QTD);



        Intent in = new Intent(this,
                Edit_linha_prod.class);

        in.putExtra("id", id9);
           in.putExtra(TAG_DATA, id3);
           in.putExtra(TAG_HORA, id5);
           in.putExtra(TAG_ESTAB, id4);
           in.putExtra(TAG_QTD, id6);
           in.putExtra("TAG_ID", id2);

           Toast.makeText(getApplicationContext(), id9,
                   Toast.LENGTH_LONG).show();
           Toast.makeText(getApplicationContext(), id2,
                   Toast.LENGTH_LONG).show();

        startActivity(in);

         // sending pid to next activity


                      return true;


    case R.id.item2:

        HashMap <String, String> product = productsList.get(info.position);
        String id = product.get(TAG_ID);


        // Starting new intent

        new DeleteProduct().execute(id);



        Intent in3 = new Intent(getApplicationContext(),
               Linhas_pesagem.class);
         in3.putExtra(TAG_ID, id2);

         Toast.makeText(getApplicationContext(), id2,
                   Toast.LENGTH_LONG).show();


        startActivity(in3);


        return true;
    default:
          return super.onContextItemSelected(item);
    }
}


}

2活动:

 public class Edit_linha_prod extends Activity {

EditText inputdtestab;
EditText inputdata;
EditText inputhora;
EditText quantidade;
Button btnSave;

String id9;
String id3;
String id4;
String id5;
String id6;
String id2;
// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();


// url to update product
private static final String url_update_product =  "http://10.0.2.2/webprojecto4/actualizar_linha.php";



// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "lin_doc";
private static final String TAG_ID = "id";
private static final String TAG_ESTAB = "estab";
private static final String TAG_DATA = "dt";
private static final String TAG_HORA = "hr";
private static final String TAG_QTD = "quantidade";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_linha);

    // save button
    btnSave = (Button) findViewById(R.id.button1);
    // getting product details from intent
    Intent i = getIntent();

    // getting product id (pid) from intent
    id9 = i.getStringExtra("id");
    id3 = i.getStringExtra(TAG_DATA);
    id4 = i.getStringExtra(TAG_ESTAB);
    id5 = i.getStringExtra(TAG_HORA);
    id6 = i.getStringExtra(TAG_QTD);

    id2= i.getStringExtra(TAG_ID);

   Toast.makeText(getApplicationContext(), id9,
           Toast.LENGTH_LONG).show();
   Toast.makeText(getApplicationContext(), id2,
           Toast.LENGTH_LONG).show();


    inputdata = (EditText) findViewById(R.id.editdata);
    inputdtestab = (EditText) findViewById(R.id.editestab);
    inputhora = (EditText) findViewById(R.id.edithora);
    quantidade = (EditText) findViewById(R.id.editquantidade);

    // display product data in EditText
    inputdata.setText(id3);
    inputdtestab.setText(id4);
    inputhora.setText(id5);
    quantidade.setText(id6);
    // Getting complete product details in background thread


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

        @Override
        public void onClick(View arg0) {
            // starting background task to update product
            new SaveProductDetails().execute();
        }
    });




}



/**
 * Background Async Task to  Save product Details
 * */
class SaveProductDetails extends AsyncTask<String, String, String> {

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

    /**
     * Saving product
     * */
    protected String doInBackground(String... args) {

        // getting updated data from EditTexts
        String data = inputdata.getText().toString();
        String estab = inputdtestab.getText().toString();
        String hora = inputhora.getText().toString();
        String quantidades = quantidade.getText().toString();



        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id", id9)); 
        params.add(new BasicNameValuePair("id_produto", "00000"));
        params.add(new BasicNameValuePair("id_tipo_produto", "00"));
        params.add(new BasicNameValuePair("id_estab", estab));
        params.add(new BasicNameValuePair("quantidade", quantidades));//ir buscar criar
        params.add(new BasicNameValuePair("dt", data));
        params.add(new BasicNameValuePair("hr", hora));




        // sending modified data through http request
        // Notice that update product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_update_product,
                "POST", params);

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

            if (success == 1) {
                // successfully updated
                Intent i = getIntent();
                Intent i2 = new Intent(getApplicationContext(), Linhas_pesagem.class);
                i2.putExtra("TAG_ID", id2);

                startActivity(i2);

                // send result code 100 to notify about product update
                setResult(100, i);
                finish();
            } else {
                // failed to update 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 product uupdated
        pDialog.dismiss();
    }
}

}

所以在我的1活动中,我在上下文菜单项1中传递了我想要id9和id2的值,香港专业教育学院敬酒,看看他们传递了什么值,并且他们传递了我想要的方式637和8

public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch(item.getItemId()) {
    case R.id.item1:
        HashMap <String, String> product2 = productsList.get(info.position);
        String id9 = product2.get("id");
        String id3 = product2.get(TAG_DATA);
        String id4 = product2.get(TAG_ESTAB);
        String id5 = product2.get(TAG_HORA);
        String id6 = product2.get(TAG_QTD);



        Intent in = new Intent(this,
                Edit_linha_prod.class);

        in.putExtra("id", id9);
           in.putExtra(TAG_DATA, id3);
           in.putExtra(TAG_HORA, id5);
           in.putExtra(TAG_ESTAB, id4);
           in.putExtra(TAG_QTD, id6);
           in.putExtra("TAG_ID", id2);

           Toast.makeText(getApplicationContext(), id9,
                   Toast.LENGTH_LONG).show();
           Toast.makeText(getApplicationContext(), id2,
                   Toast.LENGTH_LONG).show();

        startActivity(in);

         // sending pid to next activity


                      return true;

在我的2活动中,我得到了这两个变量的值,但它们是相同的637和637而不是637和8

  Intent i = getIntent();

    // getting product id (pid) from intent
    id9 = i.getStringExtra("id");
    id3 = i.getStringExtra(TAG_DATA);
    id4 = i.getStringExtra(TAG_ESTAB);
    id5 = i.getStringExtra(TAG_HORA);
    id6 = i.getStringExtra(TAG_QTD);

    id2= i.getStringExtra(TAG_ID);

   Toast.makeText(getApplicationContext(), id9,
           Toast.LENGTH_LONG).show();
   Toast.makeText(getApplicationContext(), id2,
           Toast.LENGTH_LONG).show();

2 个答案:

答案 0 :(得分:0)

in.putExtra("id", id9);
in.putExtra(TAG_DATA, id3);
in.putExtra(TAG_HORA, id5);
in.putExtra(TAG_ESTAB, id4);
in.putExtra(TAG_QTD, id6);
in.putExtra("TAG_ID", id2);

看起来你已经存储了&#34; TAG_ID&#34;作为关键,而不是变量TAG_ID

答案 1 :(得分:0)

因为你对id9和id2使用相同的密钥,这是&#34; id&#34; (请注意,常量TAG_ID的值为&#34; id&#34;),因此只需确保您使用的所有键都不同。

所以你的活动1应该是这样的,(注意我删除了常量TAG_ID周围的引号)

in.putExtra("id9", id9);
in.putExtra(TAG_DATA, id3);
in.putExtra(TAG_HORA, id5);
in.putExtra(TAG_ESTAB, id4);
in.putExtra(TAG_QTD, id6);
in.putExtra(TAG_ID, id2);

和活动2:

id9 = i.getStringExtra("id9");
id3 = i.getStringExtra(TAG_DATA);
id4 = i.getStringExtra(TAG_ESTAB);
id5 = i.getStringExtra(TAG_HORA);
id6 = i.getStringExtra(TAG_QTD);
id2= i.getStringExtra(TAG_ID);