如何从activity返回数据

如何从activity返回数据,第1张

1、在实际应用中,我们不仅要向Activity中传数据,也要从Activity中返回数据。虽然传递数据和返回数据类似,也可以采用前面四篇中提到的4种方法,但是一般建议采用Intent对象的方式来返回数据,使用这种方式返回数据,需要使用startActivityForResult方法来显示Activity;

2、新建Android项目“android_intent_forresult”,打开布局文件“activity_mainxml”,添加“LinearLayout”、“TextView”、“EditView”等标签,代码如下:

<LinearLayout xmlns:android=">

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="horizontal" >

<EditText

android:id="@+id/one"

android:layout_width="20dp"

android:layout_height="wrap_content" >

</EditText>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text=" + " >

</TextView>

<EditText

android:id="@+id/two"

android:layout_width="20dp"

android:layout_height="wrap_content" >

</EditText>

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text=" = " >

</TextView>

<EditText

android:id="@+id/result"

android:layout_width="20dp"

android:layout_height="wrap_content" >

</EditText>

</LinearLayout>

<Button

android:id="@+id/button"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="计算结果" >

</Button>

</LinearLayout>

3、新建布局文件“otherxml”,添加“TextView”、“EditView”、“Button”标签,代码如下:

<xml version="10" encoding="utf-8">

<LinearLayout xmlns:android=">

4、新建“OtherActivityjava”文件,并使其继承“Activity”,添加“onCreate”方法,代码如下:package comandroidmyintent;

import androidappActivity;

import androidosBundle;

public class OtherActivity extends Activity {

 @Override

 protected void onCreate(Bundle savedInstanceState) {

   // TODO Auto-generated method stub

   superonCreate(savedInstanceState);

   setContentView(Rlayoutother);

 }

}

5、在“AndroidManifestxml”清单文件中加入“Activity”,加入代码:<activity android:name="OtherActivity" >

       </activity>

6、在“Mainjava”中添加Button成员和“setOnClickListener”,实现两个Button的跳转,点击第一个Activity后,出现第二个Activity;在此方法内部创建意图,用“startActivityForResult”启动意图,并在Main类里重写“onActivityResult”;添加“EditText”成员,实现数据的输入并传入Intent中。代码如下:

package comandroidmyintent;

import androidRinteger;

import androidosBundle;

import androidappActivity;

import androidcontentIntent;

import androidviewMenu;

import androidviewView;

import androidwidgetButton;

import androidwidgetEditText;

public class Main extends Activity {

 private Button button;

 private final static int REQUESTCODE = 1;// 表示返回的结果码

 private EditText one, two, result; // 数据输入

 @Override

 protected void onCreate(Bundle savedInstanceState) {

   superonCreate(savedInstanceState);

   setContentView(Rlayoutactivity_main);

   one = (EditText) thisfindViewById(Ridone);

   two = (EditText) thisfindViewById(Ridtwo);

   result = (EditText) thisfindViewById(Ridresult);

   button = (Button) thisfindViewById(Ridbutton);

   buttonsetOnClickListener(new ViewOnClickListener() {

     @Override

     public void onClick(View arg0) {

       // TODO Auto-generated method stub

       // 点击后获得用户录入的值

       int a = IntegerparseInt(onegetText()toString());

       int b = IntegerparseInt(twogetText()toString());

       // 创建意图

       Intent intent = new Intent(Mainthis, OtherActivityclass);

       // 将值传入意图

       intentputExtra("a", a);

       intentputExtra("b", b);

       startActivityForResult(intent, REQUESTCODE);// 表示可以返回结果

     }

   });

 }

 // 再重写一个onActivityResult方法,作用是将当前Activity中的数据传递到另一个Activity的意图中后,实现跳转,再回传回来。

 @Override

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {

   // TODO Auto-generated method stub

   superonActivityResult(requestCode, resultCode, data);

 }

 @Override

 public boolean onCreateOptionsMenu(Menu menu) {

   // Inflate the menu; this adds items to the action bar if it is present

   getMenuInflater()inflate(Rmenumain, menu);

   return true;

 }

}

7、在“OtherActivityjava”文件中添加Button和TextView成员,获取意图中的数据,代码如下:package comandroidmyintent;

import androidappActivity;

import androidcontentIntent;

import androidosBundle;

import androidwidgetButton;

import androidwidgetTextView;

public class OtherActivity extends Activity {

 private Button button;

 private TextView textView;

 @Override

 protected void onCreate(Bundle savedInstanceState) {

   // TODO Auto-generated method stub

   superonCreate(savedInstanceState);

   setContentView(Rlayoutother);

   // 实例化button和textview

   button = (Button) thisfindViewById(Ridbutton2);

   textView = (TextView) thisfindViewById(Ridmsg);

   Intent intent = getIntent(); // 获取Intent

   // 取出Intent中的值

   int a = intentgetIntExtra("a", 0);

   int b = intentgetIntExtra("b", 0);

   textViewsetText(a + " + " + b + " = " + " ");

 }

}

运行一下,看下效果:

点击“计算结果”,跳转到第二个Activity:

8、回到“Mainjava”文件中,从OtherActivity中获取数据并显示,代码如下:

package comandroidmyintent;

import androidRinteger;

import androidosBundle;

import androidappActivity;

import androidcontentIntent;

import androidviewMenu;

import androidviewView;

import androidwidgetButton;

import androidwidgetEditText;

public class Main extends Activity {

 private Button button;

 private final static int REQUESTCODE = 1;// 表示返回的结果码

 private EditText one, two, result; // 数据输入

 @Override

 protected void onCreate(Bundle savedInstanceState) {

   superonCreate(savedInstanceState);

   setContentView(Rlayoutactivity_main);

   one = (EditText) thisfindViewById(Ridone);

   two = (EditText) thisfindViewById(Ridtwo);

   result = (EditText) thisfindViewById(Ridresult);

   button = (Button) thisfindViewById(Ridbutton);

   buttonsetOnClickListener(new ViewOnClickListener() {

     @Override

     public void onClick(View arg0) {

       // TODO Auto-generated method stub

       // 点击后获得用户录入的值

       int a = IntegerparseInt(onegetText()toString());

       int b = IntegerparseInt(twogetText()toString());

       // 创建意图

       Intent intent = new Intent(Mainthis, OtherActivityclass);

       // 将值传入意图

       intentputExtra("a", a);

       intentputExtra("b", b);

       startActivityForResult(intent, REQUESTCODE);// 表示可以返回结果

     }

   });

 }

 // 再重写一个onActivityResult方法,作用是将当前Activity中的数据传递到另一个Activity的意图中后,实现跳转,再回传回来。

 @Override

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {

   // TODO Auto-generated method stub

   superonActivityResult(requestCode, resultCode, data);

   if (resultCode == 2) {// 如果第二个Activity(OtherActivity)正常结束(“2”为返回码resultCode)。

     if (requestCode == REQUESTCODE) {// 如果返回状态为1,即成功返回,就在意图的返回值中取出数据。

       int three = datagetIntExtra("three", 0);// 从第二个Activity中返回意图中的数据。

       resultsetText(StringvalueOf(three));

     }

   }

 }

 @Override

 public boolean onCreateOptionsMenu(Menu menu) {

   // Inflate the menu; this adds items to the action bar if it is present

   getMenuInflater()inflate(Rmenumain, menu);

   return true;

 }

}

9、在“OtherActivityjava”文件中,添加点击Button事件,使数据回传~,代码如下:package comandroidmyintent;

import androidappActivity;

import androidcontentIntent;

import androidosBundle;

import androidviewView;

import androidwidgetButton;

import androidwidgetEditText;

import androidwidgetTextView;

public class OtherActivity extends Activity {

 private Button button;

 private TextView textView;

 private EditText editText;

 @Override

 protected void onCreate(Bundle savedInstanceState) {

   // TODO Auto-generated method stub

   superonCreate(savedInstanceState);

   setContentView(Rlayoutother);

   // 实例化button和textview

   button = (Button) thisfindViewById(Ridbutton2);

   textView = (TextView) thisfindViewById(Ridmsg);

   editText = (EditText) thisfindViewById(Ridthree);

   Intent intent = getIntent(); // 获取Intent

   // 取出Intent中的值

   int a = intentgetIntExtra("a", 0);

   int b = intentgetIntExtra("b", 0);

   textViewsetText(a + " + " + b + " = " + " ");

   // 添加点击事件并回传数据

   buttonsetOnClickListener(new ViewOnClickListener() {

     @Override

     public void onClick(View arg0) {

       // TODO Auto-generated method stub

       Intent intent = new Intent();// 重新声明一个意图。

       int three = IntegerparseInt(editTextgetText()toString());// 获取输入的值。

       intentputExtra("three", three); // 将three回传到意图中。

       // 通过Intent对象返回结果,调用setResult方法。

       setResult(2, intent);// resultCode为大于1的数,随意选取,为2即可。

       finish();// 结束当前Activity的生命周期。

     }

   });

 }

}

10、运行,结果:

(1)输入2和3:

(2)单击“计算结果”,跳转:

(3)输入5,单击“返回结果”,数据回传:

实现要点:

(1)在“Mainjava”中,创建Intent并启动Activity,调用“startActivityForResult”,并定义当前请求码;

(2)重写“onActivityResult”方法,并设置条件,若满足返回码值,则将第二个Activity中的数据传回来,赋给当前Activity的“result”编辑框;

(3)在“OtherActivityjava”中,再创建一个意图,将数据填写到意图中,通过意图将结果回传(通过“setResult”方法);

(4)结束当前Activity生命周期;

首先,尽量不要用try{}catch去捕捉能用判断规避的异常,那样会影响效率,每次出现异常,虚拟机要抓错误调用堆栈。所以,最好的方式是通过判断去规避。

按你的思路,可以先判断getIntentgetExtras()是否为null。

Intent

_getIntent

=

thisgetIntent();

if(

_getIntentgetExtras()

!=

null){

Logi("YuryLog","理论上只有点了确认键才执行");

receiveName

=

_getIntentgetExtras()getString("sendName");

receiveEatSomething

=

_getIntentgetExtras()getString("sendeatSomething");

receiveCopies

=

_getIntentgetExtras()getString("sendcopies");

要指出的是,上述代码,最好使用getXXXExtra这类方法,它不会出现空指针(除了少数几个,比方说getStringExtra)。

需要设定默认值的,在没有值时它会返回默认值;没有设置默认值的,在没有值时会返回null,针对这类判空一下。

可以看下getBooleanExtra的源码:

public

boolean

getBooleanExtra(String

name,

boolean

defaultValue)

{

return

mExtras

==

null

defaultValue

:

mExtrasgetBoolean(name,

defaultValue);

}

而getExtras()在没有值时会返回null,看下源码:

public

Bundle

getExtras()

{

return

(mExtras

!=

null)

new

Bundle(mExtras)

:

null;

}

所以,最好不要用getIntent()getExtras()这种方式,换用getIntent()getXXXExtras(),这样针对有设置默认值的就不需要判空了。

activity之间传值,是没有机制可以确定哪个activity传过来的。这是考虑到代码的可扩展性,解耦。要确定哪个activity发过来,在intent创建那里多传个布尔值就行,比方说下面的代码。

发送

intentputExtra("fromXXActivity",

true);

接收

if

(getIntent()getBooleanExtra("fromXXActivity",

false))

{

//

这里,你就可以安全的接收那个activity发过来的所有值。

}

getExtras()返回的是Bundle的对象,我来给楼主写个小例子,你一看就懂了:

现在我们要从MainActivity跳转到SecondActivity,并且携带一个参数过去,那么MainActivity里跳转界面的代码这样写:

Intent intent=new Intent(this,SecondActivityclass);

Bundle bundle=new Bundle();

bundleputString("test", "楼主采纳我吧");

intentputExtras(bundle);

startActivity(intent);

可以看到new出了一个bundle,在bundle里面放置了一个key为"test",值为"楼主采纳我吧"的键值对,然后把bundle放到intent里,intent携带了一个bundle对象,就开始跳转界面了,那么在SecondActivity里接收参数,就应该这么写:

String params=thisgetIntent()getExtras()getString("test");

这时候params的值就是“楼主采纳我吧”。

service类必须实现一个接收方法,接收中传递的是intent

@Override

public IBinder onBind(Intent intent) {

Bundle bundle = intentgetExtras();

String stringVal = bundlegetString("stringValue"); //用于接收字符串

int numVal = bundlegetInt("intValue"); //用于接收int类型数据

byte[] bytes = bundlegetByteArray("bytesValue"); //用于接收字节流,你可以把文件放入字节流

return null;

}

你可以用Bundle来接受你从Activity发过来的数据,然后使用Bundle提供各个方法来接受数据。

如果仅仅是字符串之类的,

使用getStringExtra方法直接接收即可。

@Override

public IBinder onBind(Intent intent) {

String str1 = intentgetStringExtra("str1");

String str2 = intentgetStringExtra("str2");

return null;

}

 1

intent

Intent(意图)主要是解决Android应用的各项组件之间的通讯。

Intent负责对应用中一次 *** 作的动作、动作涉及数据、附加数据进行描述,Android则根据此Intent的描述,负责找到对应的组件,将 Intent传递给被调用的组件,并完成组件的调用。

因此,Intent在这里起着一个媒体中介的作用,专门提供组件互相调用的相关信息,实现调用者与被调用者之间的解耦。

例如,在一个联系人维护的应用中,当我们在一个联系人列表屏幕(假设对应的Activity为listActivity)上,点击某个联系人后,希望能够跳出此联系人的详细信息屏幕(假设对应的Activity为detailActivity)

为了实现这个目的,listActivity需要构造一个 Intent,这个Intent用于告诉系统,我们要做“查看”动作,此动作对应的查看对象是“某联系人”,然后调用startActivity (Intent intent),将构造的Intent传入,系统会根据此Intent中的描述,到ManiFest中找到满足此Intent要求的Activity,系统会调用找到的 Activity,即为detailActivity,最终传入Intent,detailActivity则会根据此Intent中的描述,执行相应的 *** 作。

使用方法:通过Intent对象调用来使用,两者区别如下:

一、作用不同

1、getExtra():获取页面传递过来的单个参数。

2、getExtras():获取页面传递过来的参数数组。

二、使用方法不同

1、getExtra():通过Intent对象直接引用,比如:IntentgetExtra();

2、getExtras():通过声明Intent对象方式直接使用,比如: Intent iin= getIntent();  Bundle b = iingetExtras();

三、底层处理方式不同

1、getExtra():接收到的参数存储到单个变量中。

2、getExtras():接收到的参数存储到一个数组变量中。

参考资料来源:百度百科-Android

以上就是关于如何从activity返回数据全部的内容,包括:如何从activity返回数据、Android Intent 如何接收到指定的Intent传递过来的值呢、getExtras()是不是得到intent传来的信息的意思android开发等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9539346.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-29
下一篇 2023-04-29

发表评论

登录后才能评论

评论列表(0条)

保存