将数据设置为全局变量

时间:2013-07-10 03:16:25

标签: java android global-variables

我目前正在为我的应用程序使用Koush / ion - https://github.com/koush/ion库。

我设置了全局变量 public static String content;

在AsyncTask中使用此方法

Ion.with(MainActivity.this, "http://google.com").asString().setCallback(new FutureCallback<String>() {

@Override

public void onCompleted(Exception e, String result) {


MainActivity.content = result.toString();

         }
    });

但是,当我尝试从AsyncTask访问变量内容时,我意识到它是空的。 我已经设置了一个全局变量并将数据设置为它。它有什么问题吗?

编辑:完整脚本

package dev.tst.app

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

public class MainActivity extends Activity {
    public static volatile String content;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv);
        new LongOperation().execute();
    }

    @Override
    public 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;
    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            Ion.with(MainActivity.this, "http://google.com").asString()
                    .setCallback(new FutureCallback<String>() {
                        @Override
                        public void onCompleted(Exception e, String result) {
                            MainActivity.content = result.toString();
                            Log.e("Count", content.length() + ".");
                        }
                    });
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            MainActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this, MainActivity.content,
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将变量设为volatile:

public static volatile String content;