Androidにはかなり新しいです。 私がやろうとしていること: APIを使用してJSON形式でデータをダウンロードしました。他のデータと一緒にバンドルして、2番目のアクティビティに送信しようとしています。 私のロジックは、グローバル変数 "JSONData"を作成し、ダウンロードしたデータを "onPostExecute"に割り当てたことです。 しかし、Intent(バンドル内)を介して2番目のアクティビティに送信しようとすると、最初のデータだけが表示されます。 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);
}
表情のonCreateにURLを使用して、その活動のデータを、必要な活動にURLを渡し、フェッチする必要がありますこの回答は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に戻してそれを受け取る必要があります。 –