任何人都知道如何修复我的代码? 在我的StudentListView.setOnItemClickListener中有putExtra,它将把数据发送到ActivityShow.class
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Activity.this,ActivityShow.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position));
startActivity(intent);
}
});
//send data to service
Intent serviceIntent = new
Intent(Activity.this,ActivityService.class);
serviceIntent.putExtra("ListViewValue", IdList.get(position));
startService(serviceIntent);
我的问题是,当我尝试将putExtra直接添加到我的服务类时,它给出了一个错误,表示IdList.get(position)红色为位置,
我尝试删除get。(位置),但它给我一个null,有人知道如何解决这个问题吗?
答案 0 :(得分:0)
该位置是一个局部变量,其范围最大仅为onItemClick()。因此,要么在方法外部定义另一个变量位置,又要在onItemClick()中为其赋值。
答案 1 :(得分:0)
尝试使用实现Parcelable
接口的model
类。通过这种方式,您可以在Activity
中序列化对象,然后在Service
课程中取消重新它。
相同的一般例子:
public class MyActivity extends AppCompatActivity {
// Your activity code here
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
// onCreate() code
// create and populate your list
final ArrayAdapter<MyModel> myAdapter = new ArrayAdapter<>();
listView.setAdapter(myAdapter);
listView.setOnItemClickListener((parent, view, pos, id) -> {
MyModel model = myAdapter.get(pos);
Intent intent = new Intent(MyActivity.this, MyService.class);
intent.putExtra("ITEM", model);
startService(intent); // basic threading rules apply! be carefull
});
}
// inner class just for demo
static class MyModel implements Parcelable {
// your model goes here!
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
// write your model data into parcel
}
public static final Parcelable.Creator<MyModel> CREATOR = new Parcelable.Creator<MyModel>() {
public MyModel createFromParcel(Parcel in) {
return new MyModel(in);
}
public MyModel[] newArray(int size) {
return new MyModel[size];
}
};
private MyParcelable(Parcel in) {
// create model from parcel
}
}
}
然后在Service
中,您可以通过
MyActivity.MyModel model = (MyActivity.MyModel) intent.getExtra("MODEL");
您也可以使用Java的序列化,但通常建议不要在Android中以这种方式序列化对象。您可以阅读更多相关信息on this StackOverflow Answer
答案 2 :(得分:0)
定义全局变量pos
然后检查您是否在向服务发送价值之前点击了某个项目
int pos =-1;
StudentListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos=position;
Intent intent = new Intent(Activity.this,ActivityShow.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position));
startActivity(intent);
}
});
//send data to service
if(pos>=0){
Intent serviceIntent = new
Intent(Activity.this,ActivityService.class);
serviceIntent.putExtra("ListViewValue", IdList.get(pos));
startService(serviceIntent);
}
答案 3 :(得分:0)
这听起来有点奇怪,但我发现使用共享首选项管理器解决了这个问题 谢谢你的帮助