【发布时间】:2014-06-14 10:54:58
【问题描述】:
嗨,在我的应用程序中,我正在使用 listview,我添加了一些来自 json 的数据,最后我添加了一个按钮,如果我单击按钮,我想移动到另一个活动,但是如果我单击添加按钮,我的应用程序得到了崩溃了。任何人都可以帮助我提前谢谢。
ImageAdapterNew.java:
public class ImageAdapterNew extends Activity {
ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_countries);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Button button1=(Button)findViewById(R.id.add);
//String content = ((TextView) view.findViewById(R.id.title)).getText().toString();
//Button place = ((Button) view.findViewById(R.id.button2));
//String datetime = ((TextView) view.findViewById(R.id.datetime)).getText().toString();
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent in = new Intent(getApplicationContext(), First.class);
startActivity(in);
}
});
/*in.putExtra(TAG_PLACE, place);
*///in.putExtra(TAG_CONTENT, content);
//in.putExtra(TAG_DATETIME, datetime);
}
});
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
// Start parsing xml data
listViewLoaderTask.execute(result);
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
// Doing the parsing of xml data in a non-ui thread
@Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
Schedule1 countryJsonParser = new Schedule1();
countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
Schedule1 countryJsonParser = new Schedule1();
// A list object to store the parsed countries list
List<HashMap<String, Object>> schedule = null;
try{
// Getting the parsed data as a List construct
schedule = countryJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "itemname","image"};
// Ids of views in listview_layout
int[] to = { R.id.tv_country,R.id.iv_flag};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), schedule, R.layout.lv_layout, from, to);
return adapter;
}
/** Invoked by the Android on "doInBackground" is executed */
@Override
protected void onPostExecute(SimpleAdapter adapter) {
// Setting adapter for the listview
mListView.setAdapter(adapter);
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("flag_path");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hm.put("flag_path",imgUrl);
hm.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hm);
}
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
@Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("flag_path");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/india_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
// Storing the path to the temporary image file
hmBitmap.put("image",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
日志猫:
06-14 16:33:24.274: W/dalvikvm(1592): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-14 16:33:24.285: E/AndroidRuntime(1592): FATAL EXCEPTION: main
06-14 16:33:24.285: E/AndroidRuntime(1592): java.lang.IllegalStateException: Could not find a method myClickHandler(View) in the activity class com.example.hotel.ImageAdapterNew for onClick handler on view class android.widget.Button with id 'add'
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.view.View$1.onClick(View.java:2059)
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.view.View.performClick(View.java:2408)
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.view.View$PerformClick.run(View.java:8816)
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.os.Handler.handleCallback(Handler.java:587)
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.os.Handler.dispatchMessage(Handler.java:92)
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.os.Looper.loop(Looper.java:123)
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-14 16:33:24.285: E/AndroidRuntime(1592): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 16:33:24.285: E/AndroidRuntime(1592): at java.lang.reflect.Method.invoke(Method.java:521)
06-14 16:33:24.285: E/AndroidRuntime(1592): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-14 16:33:24.285: E/AndroidRuntime(1592): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-14 16:33:24.285: E/AndroidRuntime(1592): at dalvik.system.NativeStart.main(Native Method)
06-14 16:33:24.285: E/AndroidRuntime(1592): Caused by: java.lang.NoSuchMethodException: myClickHandler
06-14 16:33:24.285: E/AndroidRuntime(1592): at java.lang.ClassCache.findMethodByName(ClassCache.java:308)
06-14 16:33:24.285: E/AndroidRuntime(1592): at java.lang.Class.getMethod(Class.java:985)
06-14 16:33:24.285: E/AndroidRuntime(1592): at android.view.View$1.onClick(View.java:2052)
06-14 16:33:24.285: E/AndroidRuntime(1592): ... 11 more
【问题讨论】:
-
你好,请告诉我
-
我认为您实现了自定义适配器并尝试在 getView() 中处理 onClick()。
-
你能举一些例子如何创建
-
但我想从 json 中获取数据
-
可以使用自定义适配器