在以下代码中,我的toast未显示。但是,我收到错误," RuntimeException:无法在未调用Looper.prepare()"的线程内创建处理程序。
我尝试了Add_City.this
和getApplicationContext
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
System.out.println(code);
if(code==1)
{
Toast.makeText(Add_City.this, "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Add_City.this, "Sorry, City Already Available",Toast.LENGTH_LONG).show();
}
Log.i("TAG", "Result Retrieved");
} catch (Exception e) {
Log.i("TAG", e.toString());
}
答案 0 :(得分:0)
我的猜测是你得到一些异常,或者显示toast的代码没有在主线程上执行。
尝试使用此
runOnUiThread(new Runnable() {
public void run() {
//Your toast here
Toast.makeText(Add_City.this, "Sorry, City Already Available",Toast.LENGTH_LONG).show();
}
});
答案 1 :(得分:0)
如果你要,
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我相信你在工作线程中呼唤你的祝酒词。例如,AsyncTask的doInBackground()。只应在UI线程中调用Toast。
试试这个,
new AsyncTask<Integer, Void, Integer>() {
@Override
protected Integer doInBackground(Integer[] params) {
int code = 1; //your logic here.
return code;
}
@Override
protected void onPostExecute(Integer code) {
super.onPostExecute(code);
if(code==1)
{
Toast.makeText(Add_City.this, "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Add_City.this, "Sorry, City Already Available",Toast.LENGTH_LONG).show();
}
}
}.execute();