我正试图在listview上的“OnClick”事件中找回一个对象(在我的情况下是一个Wallpaper对象),我试图通过两种方式来管理它,但每次我得到:“{{ 1}}”。
第一个解决方案:InvocationTargetException.class
第二个解决方案:Wallpaper obj = (Wallpaper) listV.getItemAtPosition(position);
我在MainActivity中的代码:
Wallpaper obj = (Wallpaper ) adapter.getItem(position);
在我的其他一个项目中,我使用了第一个解决方案并且运行良好。我没有看到任何差异..
编辑:
我的任务中设置的适配器已完成:
ListView listV = null;
LazyAdapter adapter;
public final static String EXTRA_MESSAGE = "com.project.samplelist.MESSAGE";
public String message = null;
public Wallpaper wallpaperMessage = null;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final JsonDownloaderTask task = new JsonDownloaderTask(this);
task.execute(url); //download json data and set to wallpaper object and set Lazyadapter
listV = (ListView) findViewById(R.id.list);
/*adapter = new LazyAdapter(this, wallpList);
listV.setAdapter(adapter);*/
listV.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Wallpaper obj = (Wallpaper) listV.getItemAtPosition(position); // get wallpaper object on click
message = obj.getFullscreen(); // create message
wallpaperMessage = obj;
Intent wallpaperFullScreenActivity = new Intent(MainActivity.this, FullscreenActivity.class);
wallpaperFullScreenActivity.putExtra(EXTRA_MESSAGE, message);
wallpaperFullScreenActivity.putExtra("id", obj.getId());
startActivity(wallpaperFullScreenActivity);
}
});
}
编辑:
我没有任何堆栈跟踪..只是我在调试模式下按F6两次在同一行:public void jsonTaskComplete(JSONArray data)
{
ArrayList<Wallpaper> wallpapersList = new ArrayList<Wallpaper>();
Wallpaper w = null;
String id = "";
String preview = "";
String fullscreen = "";
String tags = "";
String size = "";
try {
for(int indexData = 0; indexData < data.length(); indexData++)
{
w = new Wallpaper();
// Fetching data
id = data.getJSONObject(indexData).getString("id");
preview = data.getJSONObject(indexData).getString("preview");
fullscreen = data.getJSONObject(indexData).getString("fullscreen");
tags = data.getJSONObject(indexData).getString("tags");
size = data.getJSONObject(indexData).getString("size");
// Setting data
w.setId(id);
w.setPreview(preview);
w.setFullscreen(fullscreen);
w.setSize(size);
w.setTags(tags);
// Adding result as a wallpaper object in the list
wallpapersList.add(w);
}
} catch (JSONException e) {
e.printStackTrace();
}
listV.setAdapter(new LazyAdapter(this, wallpapersList));
}
我得到了InvocationTargetException.class(找不到源代码)和这个:
Wallpaper obj = (Wallpaper) listV.getItemAtPosition(position);
答案 0 :(得分:0)
将此行从JsonTaskComplete
移至类级别,使其成为类字段:
ArrayList<Wallpaper> wallpapersList = new ArrayList<Wallpaper>();
现在执行此操作以获取OnItemClickListener
Wallpaper obj = wallpapersList.get(position);