如何在Android App中使用不同的Base Urls

时间:2015-10-16 14:54:22

标签: java android

我的Android应用中有许多带有通用Base Urls的API。我的应用程序中有一个登录页面,其中包含用户名,密码和登录按钮。当用户单击登录按钮时输入凭据为所有API选择BaseUrl-1,而如果用户长按登录按钮,则会出现一个复选框,当用户选择该复选框然后单击登录按钮时,所有API都会选择BaseUrl-2在我的应用程序中。

BaseUrl存在于实用程序类中。我的问题是如果我的应用程序在后台运行并且我从后面清除它并再次打开我的应用程序,Base Url就会丢失,即如果由于BaseUrl为null而导致任何Api被命中,我会得到NullPointerException。

我实施的代码是:

public class Activity_Login extends Activity implements OnLongClickListener 
{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.password);
    checkBox = (CheckBox) findViewById(R.id.checkBox);
    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    checkBox.setVisibility(View.INVISIBLE);
    btnSubmit.setOnLongClickListener(this);
}
public void onButtonClick(View v) {

if (checkBox.isChecked()) {
            Utility.WHICH_URL = 2;
        }else {
            Utility.WHICH_URL = 1;
        }
        Utility.URL();
         url = Utility.BASE_URL;
            if (username.getText().toString().trim().length() == 0) {
                showToast("Please enter User Name");
            } else if (password.getText().toString().trim().length() == 0) {
                showToast("Please enter password");
            } else {
                try {
                    String encodedUsername = URLEncoder.encode(username
                            .getText().toString().trim(), "UTF-8");
                    String encodedPassword = URLEncoder.encode(password
                            .getText().toString().trim(), "UTF-8");
                    NetworkOperation operation = new NetworkOperation(this);
                    operation.execute("GetLogin", encodedUsername,
                            encodedPassword);
                } catch (UnsupportedEncodingException e) {
                    Toast.makeText(Activity_Login.this,
                            "Enter valid credentials.", Toast.LENGTH_SHORT)
                            .show();

                    e.printStackTrace();
                }
            }
}
@Override
public boolean onLongClick(View v) {

    checkBox.setVisibility(View.VISIBLE);

    return true;
}

}

我的实用工具类是:

public class Utility {

public static String BASE_URL1= null;
public static  String BASE_URL= null;
 public static final String URL() {
if(WHICH_URL==1){

     BASE_URL1="http://live.net/api.php";

}else if(WHICH_URL==2){
     BASE_URL1="http://staging.net/api.php";

}

BASE_URL  = BASE_URL1;
return BASE_URL;

}
}

如何解决这个问题??

0 个答案:

没有答案