2013-03-19 109 views
2

我想創建一個包含從服務器登錄和註銷的函數的類,服務器的IP地址在函數的開頭以靜態方式定義,如下所示:java:變量初始化

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", "[email protected]", "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新不關心,如果功能或variavble是靜態的還是沒有,所有的我想要的是通過條件初始化IP地址。我把這個類的功能稱爲evry其他類,所以在evry類中做測試是不禮貌的。 IM保留,作爲最後的手段

+2

單獨從調用方法發送IP地址並追加其餘靜態條帶克到它。不需要任何檢查。 – SudoRahul 2013-03-19 03:23:33

+2

這沒有意義 - 您正在更新基於實例方法結果的靜態字符串。 – Adrian 2013-03-19 03:26:25

回答

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改性劑的使用量的聲明中要求這是情況)。

字段不能有條件地聲明。如果事實上,大多數陳述(如果,等等等)在功能之外是非法的。唯一可以在類體中靜態執行的是聲明該字段併爲其賦予初始化值。現在

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

,這是非常困難的,因爲阿德里安指出,您要使用非靜態方法(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. 
    } 
0

所有我要做的就是用這種方法初始化構造函數中的變量:

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"; 
    } 
}