运行活动两次(而不是一次)以从 getter 获取价值



当点击图像(来自以前的活动(时,我会进入读取 JSONArray 并使用二传手设置昵称的活动(我传递客户端 id(。

然后我使用getter来做一个textview setText。

问题是第一次没有设置昵称。当我返回上一个活动并再次点击相同的图像时,才设置了昵称。 为什么第一次不显示昵称。

(ps:我对Java/Android Studio很陌生(

package com.smartvibes.smartbeat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class profileViewActivity extends AppCompatActivity {
RequestQueue rs;
String url, id, nick, age, city, mainpic, numpics, extrapic0, extrapic1, extrapic2, extrapic3, extrapic4, extrapic5;
TextView profileIntro;
static String pnick;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_view);
Bundle getProfileId = getIntent().getExtras();
if (getProfileId == null) {
return;
}
String profileid = getProfileId.getString("profileid");
url = "https://www.smartvibes.be/profiles/api/profileview.php?id=" + profileid;
rs = Volley.newRequestQueue(this);
sendjsonrequest();
profileIntro = (TextView) findViewById(R.id.profileIntro);
profileIntro.setText(getPnick());
}
public void sendjsonrequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
setPnick(response.getString("nick"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
rs.add(jsonObjectRequest);
}
public static void setPnick(String nick) {
pnick = nick;
}
public static String getPnick(){
return pnick;
}
}

因为sendjsonrequest是异步调用

您需要在方法本身中更新文本视图onResponse如下所示

setPnick(response.getString("nick"));
profileIntro.setText(getPnick());

最新更新