我在调用包含json数据的第二个活动(登录后)的意图时试图增加额外费用。在LoginActivity的BackgroundTask类中正确调用json数据(我知道,因为显示了我带有json字符串的Log),但是当我执行startChildActivityIntent.putExtra时,它表示json_string变量为null(这会导致TaskActivity出错。我希望有人能告诉我出了什么问题?我留下了一些评论,确切地说出了问题。这是代码:
LoginActivity:
package com.example.myApp;
some imports
public class LoginActivity extends AppCompatActivity {
GoogleSignInOptions gso;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private int RC_SIGN_IN = 6;
String json_string;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
@Override
protected void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
private void updateUI(GoogleSignInAccount account) {
if(account == null){
signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
signIn();
}
});
signInButton.setVisibility(View.VISIBLE);
} else {
//here the json_string is correct
new BackgroundTask().execute();
Context context = LoginActivity.this;
Class destinationActivity = TaskActivity.class;
Intent startChildActivityIntent = new Intent(context, destinationActivity);
//here the json_string is null again
startChildActivityIntent.putExtra("json_data", json_string);
startActivity(startChildActivityIntent);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
updateUI(account);
} catch (ApiException e) {
updateUI(null);
}
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
String JSON_STRING;
@Override
protected void onPreExecute() {
json_url = "https://my_url/json_get_data.php";
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result) {
json_string = result;
//this log is displayed with the json_string filled in correctly
Log.i("onpostexecute","json: " + json_string);
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null){
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
TaskActivity:
package com.example.myApp;
some imports
public class TaskActivity extends AppCompatActivity {
private static final String URL_DATA = "https://my_url/json_get_data.php";
private RecyclerView recyclerView;
private RecyclerView.Adapter scorpioAdapter;
private List<ListItem> listItems;
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
progressDialog.dismiss();
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
int id;
String name, and, some, other, fields;
while (count < jsonObject.length()){
JSONObject o = jsonArray.getJSONObject(count);
id = o.getInt("id");
name = o.getString("name");
and= o.getString("and");
some= o.getInt("some");
other= o.getString("other");
fields= o.getString("fields");
ListItem item = new ListItem(id, name, and, some, other, fields);
listItems.add(item);
}
myAdapter = new myAdapter (listItems, getApplicationContext());
recyclerView.setAdapter(myAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
答案 0 :(得分:2)
这是因为您正在调用后台任务,而不等待结果传递json_string
作为额外内容。因此,json_string
将为null,因为后台任务尚未完成执行。
为避免这种情况,请尝试从TaskActivity
onPostExecute
@Override
protected void onPostExecute(String result) {
json_string = result;
//this log is displayed with the json_string filled in correctly
Log.i("onpostexecute","json: " + json_string);
Intent startChildActivityIntent = new Intent(LoginActivity.this, TaskActivity.class);
startChildActivityIntent.putExtra("json_data", json_string);
startActivity(startChildActivityIntent);
}
并删除已存在的意向调用