【问题标题】:pass value from first activity to fourth activity in android在android中将值从第一个活动传递到第四个活动
【发布时间】:2012-09-03 12:46:32
【问题描述】:

您好,这是我的单身活动:

public class SingleMenuItemActivity extends ExpandableListActivity {


Button btninsert;
String selectedItem;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.particular);

 Button btninsert = (Button) findViewById(R.id.btn_insert);
 btninsert.setOnClickListener(new View.OnClickListener() {



   public void onClick(View v) {
 // Switching to Register screen
 Intent i = new Intent(getApplicationContext(), InsertionExample.class);
  String s1= getIntent().getStringExtra("orderid");

  i.putExtra(KEY_NAME, orderid);
  startActivity(i);
   } 
  });    


    // Construct Expandable List
    final String NAME1 = "payment_method1";
    final String NAME = "payment_method";
    final String TOTAL = "total";
    final String TOTAL1 = "total1";
   final String ID = "orderid";
    final String ID1 = "orderid1";
    final String IMAGE = "image"; 
    final String FNAME1 = "firstname1";

    final String FNAME = "firstname";
    final String LNAME1 = "lastname1";
    final String LNAME = "lastname";

    final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final ArrayList<HashMap<String, String>> headerData = new ArrayList<HashMap<String, String>>();

    final HashMap<String, String> group1 = new HashMap<String, String>();
    group1.put(NAME, "OrderInfo");
    headerData.add( group1 );

    final HashMap<String, String> group2 = new HashMap<String, String>();
    group2.put(NAME, "CustomerInfo");
    headerData.add( group2);

  // final HashMap<String, String> group3 = new HashMap<String, String>();
   // group3.put(NAME, "Group 3");
   // headerData.add( group3);


    final ArrayList<ArrayList<HashMap<String, Object>>> childData = new ArrayList<ArrayList<HashMap<String, Object>>>();

    final ArrayList<HashMap<String, Object>> group1data = new ArrayList<HashMap<String, Object>>();
    childData.add(group1data);

    final ArrayList<HashMap<String, Object>> group2data = new ArrayList<HashMap<String, Object>>();
    childData.add(group2data);

  //  final ArrayList<HashMap<String, Object>> group3data = new ArrayList<HashMap<String, Object>>();
  //  childData.add(group3data);

    // Set up some sample data in both groups
    for( int i=0; i<1; ++i) {
        final HashMap<String, Object> map = new HashMap<String,Object>();
        String s= getIntent().getStringExtra("payment_method");
        String s1= getIntent().getStringExtra("total");
        String selectedItem= getIntent().getStringExtra("selectedItem");
        String s5= getIntent().getStringExtra("orderid");
        map.put(NAME1, "Payment_method:");
        map.put(NAME, s );
        map.put(TOTAL1, "Total:");
        map.put(TOTAL, s1);
        map.put(ID1, "Total:");
        map.put(ID, s5);
        group1data.add(map);
     //  map.put(IMAGE, getResources().getDrawable((i%3==0? R.drawable.color_green : R.drawable.color_red)));
      //  ( i%2==0 ? group1data : group2data ).add(map);
    }
    final HashMap<String, Object> map = new HashMap<String,Object>();
    String s1= getIntent().getStringExtra("firstname");
    String s2= getIntent().getStringExtra("lastname");

    map.put(FNAME, s1);
    map.put(FNAME1, "Firstname:");
    map.put(LNAME, s2);
    map.put(LNAME1, "Lastname:");

 //  map.put(IMAGE, getResources().getDrawable(R.drawable.color_yellow));
    group2data.add(map);

    setListAdapter( new SimpleExpandableListAdapter(
            this,
            headerData,
            R.layout.group_row,
            new String[] { NAME, FNAME },    // the names of the data
            new int[] { R.id.order },   // the text field to populate with the field data
            childData,
            0,
            null,
            new int[] {}
        ) {
            @Override
            public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
                final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);

              //  Spinner spinner = (Spinner) findViewById(R.id.spnMusketeers);

                // Populate your custom view here
                ((TextView)v.findViewById(R.id.payment_method1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(NAME1) );
                ((TextView)v.findViewById(R.id.payment_method)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(NAME) );
                ((TextView)v.findViewById(R.id.firstname)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(FNAME) );
                ((TextView)v.findViewById(R.id.firstname1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(FNAME1) );
                ((TextView)v.findViewById(R.id.total1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(TOTAL1) );
                ((TextView)v.findViewById(R.id.total)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(TOTAL) );
                ((TextView)v.findViewById(R.id.lastname)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(LNAME) );
                ((TextView)v.findViewById(R.id.lastname1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(LNAME1) );


                return v;
            }

            @Override
            public View newChildView(boolean isLastChild, ViewGroup parent) {

                 return layoutInflater.inflate(R.layout.expandable_list_item_with_image,null, false);

            }
        }
    );
    ExpandableListView list = (ExpandableListView) findViewById(android.R.id.list);
    list.setOnChildClickListener(new OnChildClickListener(){
        public boolean onChildClick(ExpandableListView parent, View v,
                int groupPosition, int childPosition, long id) {
            System.out.println("Group:"+groupPosition+", Child: "+childPosition);
            return true;
        }
    });


}} 

这是我的插入示例.java

public class InsertionExample extends Activity {
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://192.168.1.168:8089/XcartLogin/services/update?wsdl";
private final String SOAP_ACTION = "http://xcart.com/insertData";
private final String METHOD_NAME = "insertData";
Button btninsert;
String selectedItem;

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

    //get reference to the spinner from the XML layout
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    btninsert = (Button)findViewById(R.id.btn_insert1);
    btninsert.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            EditText Orderid = (EditText) findViewById(R.id.orderid);
            String orderid = Orderid.getText().toString();
            TextView tv = (TextView) findViewById(R.id.textView1);
            tv.setText("Welcome ,"+getIntent().getExtras().getString("orderid"));
            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
            PropertyInfo unameProp =new PropertyInfo();
            unameProp.setName("Status");//Define the variable name in the web service method
           unameProp.setValue(selectedItem);//Define value for fname variable
            unameProp.setType(String.class);//Define the type of the variable
            request.addProperty(unameProp);


              SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
              envelope.setOutputSoapObject(request);
              HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

              try{
               androidHttpTransport.call(SOAP_ACTION, envelope);
                  SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

                 TextView result = (TextView) findViewById(R.id.textView2);
                  result.setText(response.toString());

           }
           catch(Exception e){

           }



        }
    });

    //attach the listener to the spinner
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

    //Dynamically generate a spinner data 
    createSpinnerDropDown();

}

//Add animals into spinner dynamically
private void createSpinnerDropDown() {

    //get reference to the spinner from the XML layout
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    //Array list of animals to display in the spinner
    List<String> list = new ArrayList<String>();

    list.add("Q");
    list.add("P");
    list.add("F");
    list.add("I");
    list.add("C");

    //create an ArrayAdaptar from the String Array
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);
    //set the view for the Drop down list
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    //set the ArrayAdapter to the spinner
    spinner.setAdapter(dataAdapter);
    //attach the listener to the spinner
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

}

public class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

         selectedItem = parent.getItemAtPosition(pos).toString();

 }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }



    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Do nothing.
    }
}

我怀疑orderid是从xml解析中解析出来的……更新操作是通过soap调用执行的……现在我必须从orderid更新状态……该怎么做……这是我的更新查询.

"UPDATE `xcart_orders` set `status` = '"+Status+"' where `orderid` = '"+Orderid+"'"

请帮助我...更新状态如何取决于来自 xml 解析的 orderid..如何更改我的代码...如何做...请帮助我

【问题讨论】:

  • 为此使用SharedPreferences..
  • 尝试保存共享偏好并重新获取它
  • 请阅读我更新的问题...正是我需要回答这个问题。这是可能的
  • 第一个singlemenuactivity是执行xml解析......插入示例是执行soap调用......但我希望从xml解析中获取orderid并在插入示例中的更新状态中使用它

标签: android android-intent pass-data


【解决方案1】:

使用shared preferencesApplication class

Shared preferences example

Application class example

【讨论】:

    【解决方案2】:

    您有两种方法可以做到这一点:

    1- 使用公共静态值存储用户名和密码(不推荐)

    2- 使用 sharedPreferences 如下:

    在您的第一个活动中,保存用户名和密码:

    SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    data.edit().putString("UserName", userName).commit();
    data.edit().putString("Password", password).commit();
    

    在第四个活动中找回用户名和密码:

    SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String userName = data.getString("UserName", "THIS IS DEFAULT VALUE");
    String password = data.getString("Password", "THIS IS DEFAULT VALUE");
    

    【讨论】:

      【解决方案3】:

      您可以使用Getterssetters 方法执行此操作。

      创建一个类:

      public class SelectedAnswer {
      
      public static String uname;
      
      public static String getAnswer() {
          return uname;
      }
      
      public static void setAnswer(String answer) {
          uname = answer;
      }
      
      }
      

      然后将用户名值设置为您的第一个活动。

       SelectedAnswer.setAnswer(uName);
      

      并将值放入第四个活动中。

      String answer = SelectedAnswer.getAnswer();
      

      【讨论】:

        【解决方案4】:

        您还可以使用 setter getter 类在应用程序中的任何位置设置数据和访问数据,只需为该类创建对象即可。在您的情况下,这可能很有用。

        【讨论】:

          【解决方案5】:

          要么使用一些静态变量来存储它,要么使用共享首选项。如果您有多个活动需要传输数据,最好使用静态字典,这将帮助您保存活动特定数据。

          例如:

          我们可以为此创建一个简单的数据缓存器类:

          public class MyActivityDataCacher {
          
          private static HashMap<String, String> mDataCacher;
          
              static{
              mDataCacher=new HashMap<String, String>();
          }
          
          public static void putDataFor(String className, String data) {
              mDataCacher.put(className, data);
          }
          
          public static String getDataFor(String className) {
              if (mDataCacher.containsKey(className)) {
                  return mDataCacher.get(className);
              } else {
                  return "";
              }
          }
          }
          

          用于存储特定活动的数据(比如 MainActivity):

          MyActivityDataCacher.putDataFor(MainActivity.class.getName(), "Test Data");
          

          用于检索存储的数据:

          MyActivityDataCacher.getDataFor(MainActivity.class.getName());
          

          【讨论】:

            【解决方案6】:

            如果您有必须从应用程序的不同部分访问的数据,您可以使用Singleton 模式作为数据持有者。

            【讨论】:

              猜你喜欢
              • 2012-12-08
              • 1970-01-01
              • 2020-01-13
              • 2017-06-14
              • 2012-08-30
              • 1970-01-01
              • 1970-01-01
              • 2016-06-17
              • 1970-01-01
              相关资源
              最近更新 更多