我对Android非常陌生。 我在做什么: 我通过API下载了JSON格式的数据。我试图将其与其他一些数据捆绑在一起,并将其发送给我的第二个活动。 我的逻辑是我创建了一个全局变量“JSONData”,并将其下载到“onPostExecute”中的数据分配给它。 但是,当我尝试通过Intent(捆绑)将其发送到第二个活动时,只有第一条数据显示出来。 我的猜测是在下载JSON数据之前发送了这个包。 当我使用TextView显示数据时,数据肯定是通过API下载的。 任何人都可以给我一些提示,请问如何解决? 我将非常感激:)无法将JSON数据发送到其他活动Android
public class MainActivity extends AppCompatActivity {
private String JSONData;
private TextView Data_Test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TestView = (TextView)findViewById(R.id.TestView);
}
public class JSONTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONData = result;
/*Data_Test.setText(JSONData);*/
}
}
public void btnType0(View view) {
new JSONTask().execute("URL_with_API");
String activity_title = getResources().getString(R.string.housing_button);
Intent intent = new Intent(this, DisplayDataActivity.class);
Bundle extras = new Bundle();
extras.putString("title", activity_title);
extras.putString("JSON_Object", JSONData);
intent.putExtras(extras);
startActivity(intent);
}
在我的第二个活动,我收到了一束这样:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_data);
Bundle bundle = getIntent().getExtras();
String activity_title = bundle.getString("title");
TextView txtView = (TextView) findViewById(R.id.txtTitle);
txtView.setText(activity_title);
String JSONData = bundle.getString("JSON_Object");
TextView txtView1 = (TextView) findViewById(R.id.data_test);
txtView1.setText(JSONData);
}
看看这个答案http://stackoverflow.com/questions/42433703/my-questions-is-how-do-i-pass-the-list-data-i-have-obtained-from-json-in-a-frag/ 42434427#42434427 –
您必须将json数据更改为字符串,然后将字符串更改回到您接收它的json。 –