setOnClickListener - 应用程序意外停止
当我在代码中使用 setOnClickListener 作为按钮时,当我启动应用程序时,它会显示应用程序已意外停止
package example.khumbayatabbed;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Category extends ListActivity{
int categ=0;
String[] categories = new String[100];
Button button1;
EditText edittext1;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edittext1= (EditText) findViewById(R.id.edittext);
button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
edittext1.setText("");
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_SHORT).show();
}
});
// setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
// Set the text and call the connect function.
//call the method to run the data retreival
final String KEY_121 = "http://myurl";
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
private void getServerData(String jason) {
mylist = new ArrayList<HashMap<String, String>>();
InputStream is = null;
String returnString="";
String result = "";
//mylist.clear();
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(jason);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","url: "+json_data.getString("url")+
", name: "+json_data.getString("value")
);
//Get an output to the screen
categories[categ++]=json_data.getString("value");
map.put("name", json_data.getString("value"));
map.put("url", json_data.getString("url"));
mylist.add(map);
returnString += jArray.getJSONObject(i).getString("url") + "\n";
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
private void display(ArrayList<HashMap<String, String>> list)
{
ListAdapter adapter=new SimpleAdapter(this,list,R.layout.list_item2, new String[] {"name"}, new int[]{R.id.cat_name});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> tmp = new HashMap<String, String>();
tmp=(HashMap<String, String>)parent.getItemAtPosition(position);
String cat_url=tmp.get("url");
final String KEY_121 = "http://myurl/"+cat_url;
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
});
}
}
这是我的主页的代码:
public class Khumbayatabbed extends TabActivity
{ /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Category.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("category").setIndicator("Category",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, Event.class);
spec = tabHost.newTabSpec("event").setIndicator("Event",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
}
main. xml 看起来像这样:
As soon as I use setOnClickListener for a button in my code, when I start the application it says the application has stopped unexpectedly
package example.khumbayatabbed;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Category extends ListActivity{
int categ=0;
String[] categories = new String[100];
Button button1;
EditText edittext1;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edittext1= (EditText) findViewById(R.id.edittext);
button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
edittext1.setText("");
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_SHORT).show();
}
});
// setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
// Set the text and call the connect function.
//call the method to run the data retreival
final String KEY_121 = "http://myurl";
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
private void getServerData(String jason) {
mylist = new ArrayList<HashMap<String, String>>();
InputStream is = null;
String returnString="";
String result = "";
//mylist.clear();
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(jason);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","url: "+json_data.getString("url")+
", name: "+json_data.getString("value")
);
//Get an output to the screen
categories[categ++]=json_data.getString("value");
map.put("name", json_data.getString("value"));
map.put("url", json_data.getString("url"));
mylist.add(map);
returnString += jArray.getJSONObject(i).getString("url") + "\n";
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
private void display(ArrayList<HashMap<String, String>> list)
{
ListAdapter adapter=new SimpleAdapter(this,list,R.layout.list_item2, new String[] {"name"}, new int[]{R.id.cat_name});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> tmp = new HashMap<String, String>();
tmp=(HashMap<String, String>)parent.getItemAtPosition(position);
String cat_url=tmp.get("url");
final String KEY_121 = "http://myurl/"+cat_url;
getServerData(KEY_121);
if(mylist.isEmpty())
Toast.makeText(getApplicationContext(), "No more sub categories",
Toast.LENGTH_SHORT).show();
else
display(mylist);
}
});
}
}
This is code for my main page:
public class Khumbayatabbed extends TabActivity
{ /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Category.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("category").setIndicator("Category",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, Event.class);
spec = tabHost.newTabSpec("event").setIndicator("Event",
res.getDrawable(R.drawable.ic_tab))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
}
The main.xml looks like this:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有为您的布局编写setContentView。因此您无法访问您的editText1,也无法访问button1。
编写类似的内容来调用此用途
在您的主页中
You didn't wrtie setContentView for your layout.So you can't access Your editText1 and same for the button1.
write something like
In your Main Page to call this use