Getting string in Protected Function Android
Basically I have a stand alone class, which does not use Act开发者_Python百科ivity OR Service. A function in the class starts a new Authenticator.
I have a string in the strings.xml file, which I want to access Looking for the best method
Example code
class MyConnection(){
String username;
String pwd;
String strurl;
public MyConnection(String usernameIN, String pwdIN, String urlIN){
this.username = usernameIN;
this.pwd = pwdIN;
this.strurl = urlIN
}
public void
URL url = null;
try {
url = new URL(this.strURL);
URLConnection urlConn = null;
Authenticator.setDefault(new Authenticator()){
protected PasswordAuthentication getPasswordAuthentication()(
// I want my vars from strings.xml here
return new PasswordAuthentication(strUsername, strPwd.toCharArray());
}
});
urlCOnn = url.openConnection();
//Rest of the code, including CATCH
}
I passed the vars through into the class BUT how do I access them When I set the PasswordAuthentication. OR Can I access them direct from strings.xml ???
How do you create an instance of the MyConnection
class?
It should be through an Activity or a Service, right?
Then when you create it, pass the current Activity
public class MyConnection {
private Activity activity;
public MyConnection(Activity a) {
this.activity = a;
}
//....
private void method() {
activity.getResources().getString(R.string....);
}
}
edit: I did not see you already had a constructor. Then add a parameter to the existing one.
You can add a final
modificator to your MyConnection()
constructor's parameters, this way you can use them as parameters in the call to PasswordAuthentication()
. Hope this helps.
You'll need to pass a Context
instance to your class or individual methods. The Context
instance can be an instance of Activity
or Service
or anything else which is a subclass of Context
. You can then use this to access system resources:
class MyConnection
{
private final Context context;
public MyConnection( Context context )
{
this.context = context;
}
.
.
.
public void someMethod()
{
String str = context.getResources().getString ( R.string.myString );
}
}
精彩评论