【发布时间】:2018-04-09 17:42:32
【问题描述】:
我正在使用 android 上的 web 服务。我正在关注其中一个 lynda.com 上的教程。我确实经历了tuorial。我得到数据 来自 webservice 并将其显示在“ListView”中。我有 MainActivity 类 以及扩展 IntentServcie 的 MyService 类,以及实现 Parcelable 的 POJO 类名 Course。它包含我得到的网络服务响应的一部分 点击。
public class MainActivity extends AppCompatActivity {
//member variables I have
ListView listview;
List<String> courseList = new ArrayList<>();
ArrayAdapter<String> adapter;
Course[] courses;
......
public void runClickHandler(View view) {
Intent intent = new Intent(this, MyService.class);
//the url where I extract the JSON data
intent.setData(Uri.parse(JSON_URL));
startService(intent);
}
在 MyService 类中,从 web 服务下载响应并 我打开一个连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Authorization", TOKEN);
我使用 GSON 库转换 JSON ,打包数据并使用 LocalBroadcastManager 将其发送到 MainActivity。
protected void onHandleIntent(Intent intent) {
...........
messageIntent.putExtra(MY_SERVICE_PAYLOAD, courseList);
//we package the data we want to share to the rest of the applicaiton
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(getApplicationContext());
manager.sendBroadcast(messageIntent);
}
在我的 MainActivity 上,我使用 BroadcastReceiver 获取数据并将其显示在列表视图上。 BroadcastReceiver 的 OnReceive 方法内部。我有这个
public void onReceive(Context context, Intent intent) {
courses = (Course[]) intent.getParcelableArrayExtra(MyService.MY_SERVICE_PAYLOAD);
for (Course course : courses) {
courseList.add(course.getCourseTitle());
}
Collections.sort(courseList);
adapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1,
courseList);
listview.setAdapter(adapter);
}
当我改变屏幕方向时,问题就来了。我从 web 服务获得的数据被破坏了。我阅读了在 XML 文件上设置内容以调整屏幕大小更改的建议,这也被认为不是“好方法”。我认为使用的是覆盖此处或在线其他帖子所建议的 onSaveInstanceState 。我确实很难连接各个部分,并在方向更改期间保留我的数据。 我应该如何处理事情?我会很感激您阅读的任何好文章,或者您如何根据我上面的实现来解决问题。检查 if(savedInstanceState != null) 后如何处理显示 onCreate?我应该保存哪些成员变量数据?是否一切都更改为 null onDestroy()?这是我有的 onCreate() 方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(mBroadcastReceiver,new IntentFilter(MyService.MY_SERVICE_MESSAGE));
listview = (ListView) findViewById(R.id.list);
}
【问题讨论】:
标签: android json web-services