2

我正在尝试创建一个包含从服务器登录和注销的函数的类,服务器的 IP 地址在函数的开头以静态方式定义,如下所示:

private static String loginURL = "http://192.168.1.5/android_login_api/"

我想知道初始化条件的 loginURL 的最佳方法。例如:

if(this.isConnectedToServer("192.168.1.5", 500)) {
    private static String loginURL = "http://192.168.1.5/android_login_api/";
}

if(this.isConnectedToServer("192.168.1.9", 500)) {
    private static String loginURL = "http://192.168.1.9/android_login_api/";
}

我想将 loginURL 作为参数传递给这个类的每个函数,然后当我调用它们时,我使用这个条件来定义 IP 地址,但我认为这太傻了。

这是我的课:

public class UserFunctions {

private JSONParser jsonParser;

private static String loginURL = "http://192.168.1.5/android_login_api/";
private static String mplayerURL = "http://192.168.1.5/android_mplayer_api/";
private static String registerURL = "http://192.168.1.5/android_login_api/";

private static String login_tag = "login";
private static String register_tag = "register";
private static String delete_tag = "delete";
private static String update_tag = "update";
private static String music_tag = "music";
private static String getusers_tag = "getusers";


// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}

/**
 * function make Login Request
 * @param email
 * @param password
 * */
public JSONObject loginUser(String email, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", login_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("password", password));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    Log.i("JSON", json.toString());
    return json;
}
public JSONObject deleteUser(String email){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", delete_tag));
    params.add(new BasicNameValuePair("email", email));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    Log.i("JSON", json.toString());
    return json;
}

public JSONObject updateUser(String email, String field, String value){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", update_tag));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("field", field));
    params.add(new BasicNameValuePair("value", value));
    JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
    // return json
    Log.i("JSON", json.toString());
    return json;
}



public boolean isConnectedToServer(String url, int timeout) {
    try{
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        // Handle your exceptions
        return false;
    }
}

/**
 * function make Login Request
 * @param name
 * @param email
 * @param password
 * */
public JSONObject registerUser(String name, String email, String mode, String password){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", register_tag));
    params.add(new BasicNameValuePair("name", name));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("mode", mode));
    params.add(new BasicNameValuePair("password", password));

    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
    // return json
    return json;
}

    public JSONObject PlayMusic(String name){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "play"));
    params.add(new BasicNameValuePair("name", name));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}

public JSONObject ChangeVol(String volume){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "volume"));
    params.add(new BasicNameValuePair("volume", volume));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}

public JSONObject StopMusic(){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "stop"));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}


public JSONObject ParcourirMusic(){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", "parcourir"));
    // getting JSON Object
    JSONObject json = jsonParser.getJSONFromUrl(mplayerURL, params);
    // return json
    return json;
}


/**
 * Function get Login status
 * */
public boolean isUserLoggedIn(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    int count = db.getRowCount();
    if(count > 0){
        // user logged in
        return true;
    }
    return false;
}

/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}

public void ReadMail(){

try{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "rami.mtiri@gmail.com", "pass");
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);


SearchTerm term = new SearchTerm() {
  @Override
  public boolean match(Message mess) {
    try {
      return mess.getContent().toString().toLowerCase().indexOf("boston") != -1;
    } catch (IOException ex) {
     // Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MessagingException ex) {
     // Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
  }
};

Message[] searchResults = inbox.search(term);
for(Message m:searchResults){
    Log.e("mail",m.getFrom()[0].toString() );
  System.out.println("MATCHED: " + m.getFrom()[0]);

}
} catch (Exception e) {

}

}

}

请任何人都可以使用我的代码UP给我一个完整的解决方案,我是Java新手,不在乎函数或变量是否是静态的,我想要的只是按条件初始化IP地址。我在每个其他类中调用这个类的函数,所以在每个类中进行测试是不礼貌的。我把它作为最后的手段

4

2 回答 2

2

if(this.isConnectedToServer("192.168.1.5", 500))
{
    private static String loginURL = "http://192.168.1.5/android_login_api/";
}
if(this.isConnectedToServer("192.168.1.9", 500))
{
    private static String loginURL = "http://192.168.1.9/android_login_api/";
}

不是有效的 java 代码,假设上述语句位于类的声明中(private static修饰符的使用需要这种情况)。

不能有条件地声明字段。事实上,大多数语句(if、while、for 等)在函数之外都是非法的。您可以在类主体中静态地做的唯一一件事是声明该字段并给它一个初始化值。

private static String loginURL; //no initialization yet as you don't have an instance to call isConnectedToServer() on

现在,解决您的问题非常困难,因为正如 Adrian 指出的那样,您正在尝试使用非静态方法 ( isConnectedToServer()) 来确定静态行为 ( 的值loginURL)。这没有意义。您必须要么制作loginURL非静态的,要么制作isConnectedToServer()静态的。

您可能想要第一个选项。

由于初始化条件的性质,loginURL在构造函数中初始化会更容易,这与静态初始化几乎完全相同。以下是此类设置的框架示例:

class Example
{
     private String loginURL; //non-static, no initialization

     public Example()//construcutor
     {
           //run conditions normally
           if(this.isConnectedToServer("192.168.1.5", 500))
           {
                loginURL = "http://192.168.1.5/android_login_api/";
           }
           //you might want to use else if here
           if(this.isConnectedToServer("192.168.1.9", 500))
           {
                loginURL = "http://192.168.1.9/android_login_api/";
           }
           //if neither if starement executes, loginURL is null.
     }
}

如果您出于某种原因确实希望功能是静态的,请将初始化代码移动到静态块:

class StaticExample
{
     private static String loginURL;

     //isConnectedToServer must be declared static in order for this to work!
     //I believe your current function can be made static without changing its code
     public static boolean isConnectedToServer()
     {
        ...
     }

     static
     {
           if(isConnectedToServer("192.168.1.5", 500))
           {
                loginURL = "http://192.168.1.5/android_login_api/";
           }
           //you might want to use else if here
           if(isConnectedToServer("192.168.1.9", 500))
           {
                loginURL = "http://192.168.1.9/android_login_api/";
           }
           //if neither if starement executes, loginURL is null.
     }
于 2013-03-19T03:41:36.417 回答
0

我所要做的就是以这种方式在构造函数中初始化 var:

private JSONParser jsonParser;

private static String loginURL = "/android_login_api/";
private static String mplayerURL = "/android_mplayer_api/";
private static String registerURL = "/android_login_api/";
public String ip;
private static String login_tag = "login";
private static String register_tag = "register";
private static String delete_tag = "delete";
private static String update_tag = "update";
private static String music_tag = "music";
private static String getusers_tag = "getusers";


// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
    if(isConnectedToServer("192.168.1.5", 500)==false)
    {
        if(isConnectedToServer("www.google.com", 500)==true)
        {
            ReadEmails re = new ReadEmails();
            ip=re.processMail();
        }else{
            ip="192.168.1.5";
        }
    }else{
        ip="192.168.1.5";
    }
}
于 2013-03-24T23:52:03.927 回答