当网络或服务器不可用时,屏幕上不显示Toast消息

时间:2012-07-12 08:38:20

标签: android android-activity

我需要在服务器没有响应时显示toast消息 当我按下登录按钮时,一些参数被传递到AgAppMenu屏幕,该屏幕使用url连接到服务器并在AgAppHelperMethods屏幕中获取xml响应。该 probelm是服务器忙或网络不可用时,虽然它显示了日志消息但我无法在catch块上显示toast消息。

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent ;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginScreen extends Activity implements OnClickListener {

EditText mobile;
EditText pin;
Button btnLogin;
Button btnClear;

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.agapplogin);

    TextView lblMobileNo = (TextView) findViewById(R.id.lblMobileNo);
    lblMobileNo.setTextColor(getResources()
            .getColor(R.color.text_color_red));

    mobile = (EditText) findViewById(R.id.txtMobileNo);

    TextView lblPinNo = (TextView) findViewById(R.id.lblPinNo);
    lblPinNo.setTextColor(getResources().getColor(R.color.text_color_red));

    pin = (EditText) findViewById(R.id.txtPinNo);

    btnLogin = (Button) findViewById(R.id.btnLogin);
    btnClear = (Button) findViewById(R.id.btnClear);

    btnLogin.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            postLoginData();

        }
    });

    btnClear.setOnClickListener(new OnClickListener() {
        public void onClick(View v)

        {
            cleartext();
        }

    });

    /*
     * 
     * btnClear.setOnClickListener(new OnClickListener() { public void
     * onClick(View arg0) {
     * 
     * } });
     */

}

public void postLoginData()

{

    if (pin.getTextSize() == 0 || mobile.getTextSize() == 0) {

        AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
        altDialog.setMessage("Please Enter Complete Information!");

    } else {
        Intent i = new Intent(this.getApplicationContext(),  AgAppMenu.class);          
        Bundle bundle = new Bundle();
        bundle.putString("mno", mobile.getText().toString());
        bundle.putString("pinno", pin.getText().toString());
        i.putExtras(bundle);
        startActivity(i);
    }
}

@Override
public void onClick(View v) {

}

public void cleartext() {

    {
        pin.setText("");
        mobile.setText("");
    }

}

}


  import android.app.Activity;
  import android.content.Intent;
  import android.os.Bundle;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.TextView;
  import android.widget.Toast;

 public class AgAppMenu extends Activity {

String mno, pinno;

private String[][] xmlRespone;


Button btnMiniStatement;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.agappmenu);

    mno = getIntent().getExtras().getString("mno");
    pinno = getIntent().getExtras().getString("pinno");

    setTitle("Welcome to the Ag App Menu");

    AgAppHelperMethods agapp =new AgAppHelperMethods();


//  xmlRespone =   AgAppHelperMethods.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin=" + pinno + "&mobile=" + mno + "&source=" + mno   + "&channel=INTERNET");
    xmlRespone = agapp.AgAppXMLParser("AG_IT_App/AgMainServlet?messageType=LOG&pin="    + pinno + "&mobile=" + mno + "&source=" + mno   + "&channel=INTERNET");







 import java.net.URL;

  import javax.xml.parsers.DocumentBuilder;
  import javax.xml.parsers.DocumentBuilderFactory;

  import org.w3c.dom.Document;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  import org.xml.sax.InputSource;

  import android.app.Activity;
  import android.os.Bundle;
  import android.util.Log;
  import android.widget.Toast;
  import android.view.View;
  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;

boolean flag = true;

@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];

        // this "for" loop is used to parse through the
        // XML document and extract all elements and their
        // value, so they can be displayed on the device

        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;

        }// end for
        throw new ArrayIndexOutOfBoundsException();
    }// end try
    // will catch any exception thrown by the XML parser

    catch (Exception e) {
        Toast.makeText(AgAppHelperMethods.this,
                "error  server not responding " + e.getMessage(),
                Toast.LENGTH_SHORT).show();
        Log.e(LOG_TAG, "CONNECTION ERROR  FUNDAMO SERVER NOT RESPONDING", e);

    }

    // Log.e(LOG_TAG, "CONNECTION ERROR  FUNDAMO SERVER NOT RESPONDING", e);

    return xmlRespone;

}
    `

1 个答案:

答案 0 :(得分:0)

AgAppHelperMethods实际上不是Activity。您已从Activity派生此类,但之后您已创建Singleton管理方法(getInstance())并且您自己实例化它。这是不好的。不要这样做。

通常Android控制活动的实例化。你自己不创建一个(new)。

在我看来,AgAppHelperMethods只需要成为常规的Java类。它不需要继承任何东西。同时删除onCreate()等生命周期方法。

现在你的toast会遇到问题,因为你需要一个上下文,而AgAppHelperMethods不是一个Context。要解决此问题,您可以将Context作为参数添加到AgAppXMLParser(),如下所示:

public String[][] AgAppXMLParser(Context context, String parUrl) {
     ...
     // Now you can use "context" to create your toast.
}

当您从AgAppXMLParser()拨打AgAppMenu时,只需将“this”作为上下文参数传递。