您好我的应用程序我正在使用listview,我添加了一些来自json的数据,最后我添加了一个按钮如果我点击按钮我想转移到另一个活动,但如果我点击添加按钮我的应用程序得到了crashed.can任何人请帮助我提前谢谢。
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;
}
logcat的:
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
答案 0 :(得分:0)
而不是:
Intent in = new Intent(getApplicationContext(), First.class);
把这个:
Intent in = new Intent(ImageAdapterNew.this, First.class);
答案 1 :(得分:0)
为什么你把这个点击监听器放在onItemClickListener中,你需要在它之外写这个。
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(ImageAdapterNew.this, First.class);
startActivity(in);
}
});
答案 2 :(得分:0)
如果要在列表的每一行中添加按钮,则必须在getView方法中放置按钮的单击侦听器。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(vi==null)
vi=inflater.inflate(R.layout.catgridres,null);
Button button=(Button)vi.findViewById(R.layout_inflator.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//do your code here.
}
});
return vi;
}
For your task I think Custom Adapter is more efficient.
答案 3 :(得分:0)
首先你应该把你的错误放在logcat上,这有助于解决代码上的确切问题
其次我认为您的按钮来自不同的布局,因此您必须从视图中获取finviewbyid。
Button button=(Button)convertView.findViewById(R.layout_inflator.button1);