Android development: loading data through interface callback (source code sharing)

Source: Internet
Author: User

Android development: simple implementation of loading data through the interface callback mechanism, in actual development, the call back method is much more frequently used to obtain network-loaded data than to load data by directly enabling threads or asynchronous tasks, the code in this article will simply implement this smart call and understand the essence of callback.

MainActivity code

Package com. example. f07_callback01; import com. example. f07_callback01.A.Callback; import android. OS. bundle; import android. app. activity; import android. util. log; import android. view. menu; import android. view. view; import android. widget. button; public class MainActivity extends Activity {private Button button; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) this. findViewById (R. id. button1); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View arg0) {// TODO Auto-generated method stubA getString = new A (); // call the interface to obtain the data getString. loadString ("", new Callback () {@ Overridepublic void get (String result) {// TODO Auto-generated method stubLog. I ("TAG", "-------->" + result) ;}}) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

Method of the callback Interface Class

Package com. example. f07_callback01; public class A {// simulate obtaining the public void loadString (String path, final Callback callback) {new Thread (new Runnable () {@ Overridepublic void run () from the server () {// TODO Auto-generated method stubString msg = "call data through interfaces"; callback. get (msg );}}). start () ;}public interface Callback {public void get (String result );}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.