android – Toast没有显示在catch块中

嗨!我正在尝试在网络关闭或服务器没有响应时显示消息.我的消息在LOG中可见,但没有显示在屏幕上(没有烘烤).我有一个示例代码,工作正常,但我的代码不是.

import android.view.View.OnKeyListener;

public class AgAppHelperMethods  extends Activity  {

    private static final String LOG_TAG = null;
    private static AgAppHelperMethods instance = null;
    public static String varMobileNo;
    public static String varPinNo;

    String[][] xmlRespone = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.agapphelpermethods);
    }

    protected AgAppHelperMethods() {}

    public static AgAppHelperMethods getInstance() 
    {
        if(instance == null) 
        {
            instance = new AgAppHelperMethods();
        }
        return instance;
    }

    public static String getUrl () 
    {
        String url = "https://demo.accessgroup.mobi/";
        return url;
    }

    public  String[][] AgAppXMLParser(String parUrl) 
    {       
        String _node,_element;
        String[][] xmlRespone = null;
        try {
            String url = AgAppHelperMethods.getUrl() + parUrl;
            URL finalUrl = new URL(url);

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(finalUrl.openStream()));
            doc.getDocumentElement().normalize();

            NodeList list=doc.getElementsByTagName("*");
            _node=new String();
            _element = new String();
            xmlRespone = new String[list.getLength()][2];

            for (int i=0;i<list.getLength();i++)
            {
                Node value=list.item(i).      getChildNodes().item(0);
                _node=list.item(i).getNodeName();
                _element=value.getNodeValue();
                xmlRespone[i][0] = _node;
                xmlRespone[i][1] = _element;
            }
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(), "error  server not responding " + e.getMessage(),
                Toast.LENGTH_SHORT).show();
            Log.e(LOG_TAG, "CONNECTION ERROR  FUNDAMO SERVER NOT RESPONDING", e);
        }
    }
}

如何在屏幕上显示我的祝酒词?谢谢.

最佳答案 你不能这样做.你可以做这样的事情

boolean flag=true;//take globally

//working thread
.
.
.

  catch (Exception e)
  {
    flag=false;
    Log.e(LOG_TAG, "CONNECTION ERROR  FUNDAMO SERVER NOT RESPONDING", e);
  } 

一旦你的工作线程结束,检查标志值并显示Toast.

//Main Thread
 if(!flag)
 Toast.makeText(getApplicationContext(), "error  server not responding " + e.getMessage(),
                Toast.LENGTH_SHORT).show();

注意:如果你仍然希望在NonUI线程中显示,那么你可以使用Handler或runOnUiThread()

点赞