我希望MoviePage在单击ListView中的相关项目时显示来自网站的JSON数据。
以下是我的ListView页面中的代码,该代码在单击项目时打开一个新活动:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String movieData = ((TextView) view).getText().toString();
Intent newActivity = new Intent(ResultsActivity.this, MoviePage.class);
newActivity.putExtra("title", movieData);
startActivity(newActivity);
}
});
以下是我希望在
上显示JSON数据的页面代码@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String keyword = getIntent().getExtras().getString("keyword");
keyword = keyword.replaceAll("\\s", "+");
Intent newActivity1 = new Intent();
setResult(RESULT_OK, newActivity1);
private String movieData(String keyword) {
String jsonResult = null;
try {
URL url = new URL("https://omdbapi.com/?t=" + keyword);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream input = httpURLConnection.getInputStream();
Scanner scanner = new Scanner(input, "UTF-8").useDelimiter("\\A");
jsonResult = scanner.hasNext() ? scanner.next() : "";
} catch (Exception e) {
e.printStackTrace();
}
return jsonResult;
}
答案 0 :(得分:0)
String keyword = getIntent().getExtras().getString("keyword");
不应该这样,
String keyword = getIntent().getExtras().getString("title");
您应该将密钥定义为常量,这样您就不会犯这样的错误。
public static final String EXTRA_TITLE = "title";
newActivity.putExtra(EXTRA_TITLE, movieData);
然后当你拿出来
getIntent().getExtras().getString(ClassWhereIDefinedMyKey.EXTRA_TITLE);
答案 1 :(得分:0)
而是将json对象存储到sharedpreferences中,以便您可以检索该对象 在你的应用程序的任何类中。你需要先将该对象转换为字符串然后存储到共享的首选项中,反之亦然 link