我有两个类,一个叫做Main1843,另一个是JsonParse。当我复制与main1843相同的所有课程时,一切正常。但我更喜欢分开课程和整洁。问题是我无法运行下面的代码。没有显示错误,只是app停止运行。 (清单文件具有权限)
因为它是一个简短的程序,你可以检查每一行。
Main1843课程:
public class Main1843 extends Activity implements View.OnClickListener {
private Button button;
private TextView tv;
private EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1843);
tv = (TextView) findViewById(R.id.panel);
et = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
public void onClick(View v) {
String text;
text = et.getText().toString();
tv.append(text);
tv.append("\n");
new JsonParse().execute();
}
protected void putScreen(String t) {
tv.append(t);
}
}
另一个类(JsonParse)扩展了AsyncTask<> ;
public class JsonParse extends AsyncTask{
private String yazi;
protected String yazi2;
protected String id;
private String TAG = "JWP";
@Override
protected Object doInBackground(Object[] objects) {
return POST("http://somewebsite/show.php");
}
public String POST(String url) {
String result = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
Main1843 m = new Main1843();
try {
HttpResponse response = client.execute(post);
InputStream inputStream = response.getEntity().getContent();
if (inputStream != null) {
String text = "";
result = convertInputStreamToString(inputStream);
Log.d(TAG, result);
JSONArray reader = new JSONArray(result);
for (int i = 0; i < reader.length(); i++) {
JSONObject data = reader.getJSONObject(i);
id = data.getString("id");
yazi = data.getString("yazi");
yazi2 = data.getString("yazi2");
text += yazi;
text += " ";
}
m.putScreen(text);
} else
result = "Did not work";
return result;
} catch (IOException e) {
e.printStackTrace();
return "Exception 1";
} catch (Exception e) {
e.printStackTrace();
return "haha";
}
}
private String convertInputStreamToString(InputStream inputStream) {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
try {
while ((line = br.readLine()) != null)
result += line;
br.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return "Exception";
}
}
}
感谢您的时间。
答案 0 :(得分:0)
评论解决了问题
“您需要将活动上下文传递到AsyncTask以调用其上的方法,或者您可以调用您的活动实现的侦听器,或者您可以使用localbroadcast。” KenWolf
@ShaikhMohammedShariq shared a similar problem answer