Java 变量值不';Don’我不能从后台出来
有人可以解释为什么变量Java 变量值不';Don’我不能从后台出来,java,android,android-asynctask,Java,Android,Android Asynctask,有人可以解释为什么变量picture的值只出现在OnInBackground()中 当我在OnPostExecute中访问它时,该值丢失 public class GetPostAsync extends AsyncTask<Void, Integer, String> { String picture=""; public GetPostAsync(Context context){ c=context; } protected
picture
的值只出现在OnInBackground()
中
当我在OnPostExecute
中访问它时,该值丢失
public class GetPostAsync extends AsyncTask<Void, Integer, String>
{
String picture="";
public GetPostAsync(Context context){
c=context;
}
protected void onPreExecute (){
}
protected String doInBackground(Void...arg0) {
try {
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/myquery",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
try {
JSONObject jobj = response.getJSONObject();
picture = jobj.getString("picture");
Log.i("TEST","pic: "+picture); //return the right value
} catch (JSONException e) {
e.printStackTrace();
}
}
});
request.executeAsync();
}
catch(Exception e) {
}
return picture;
}
protected void onProgressUpdate(Integer...a){
}
protected void onPostExecute(String result) {
Log.i("TEST","pic: "+picture); //return empty
}
}
公共类GetPostAsync扩展异步任务
{
字符串图片=”;
公共GetPostAsync(上下文){
c=上下文;
}
受保护的void onPreExecute(){
}
受保护的字符串doInBackground(无效…arg0){
试一试{
GraphRequest请求=GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
“/myquery”,
新建GraphRequest.Callback(){
@凌驾
未完成公共空白(图形响应){
试一试{
JSONObject jobj=response.getJSONObject();
picture=jobj.getString(“picture”);
Log.i(“TEST”,“pic:+picture);//返回正确的值
}捕获(JSONException e){
e、 printStackTrace();
}
}
});
request.executeAsync();
}
捕获(例外e){
}
返回图片;
}
受保护的void onProgressUpdate(整数…a){
}
受保护的void onPostExecute(字符串结果){
Log.i(“TEST”,“pic:+picture);//返回空
}
}
我已在活动顶部声明
图片
。我不知道如何保存在您正在调用的请求中的Onbackground()
中检索到的值。executeAsync
来自doInBackground
。因此,doInBackground
将立即返回,并且在调用onCompleted
回调之前可以调用onPostExecute
。您不必在doInBackground
中返回值,因为它已经在内部类的全局变量中。只需将此AsyncTask
更改为此AsyncTask
@mohammedalsafwan请学习一些java的基础知识。。。它不是全局变量,而是多线程。。。request.executeAsync();字段:类的数据成员。除非另有规定,否则字段不是静态的。变量:由标识符命名的数据项。每个变量都有一个类型(如int或Object)和一个作用域。另请参见类变量、实例变量、局部变量。