1

I'm currently using Koush/ion - https://github.com/koush/ion library for my app.

I have a Global Variable set up public static String content;

And using this method in an 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();

         }
    });

However, when I try to access the variable content out of AsyncTask, I realized that it's null. I've set a global variable and set data to it. Is there anything wrong with it?

EDIT: Full script

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();
                }
            });
        }
    }
}
4

1 回答 1

0

尝试将变量设置为 volatile:

public static volatile String content;
于 2013-07-10T03:18:21.013 回答