Reputation: 2627
I have a button, part of whose functionality is in a class, that is in another class file in the same package. Is this the way how it is supposed to be done or I can somehow pass the instance of the current activity and then use whatever methods or fields it has in the methods of the second class.
public class LogInScreen extends AppCompatActivity {
Button logInButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in_screen);
logInButton = findViewById(R.id.button_login);
userText = findViewById(R.id.editText_user);
passText = findViewById(R.id.editText_pass);
}
public void logIn(View view) {
logInButton.setEnabled(false);
String username = userText.getText().toString();
String password = passText.getText().toString();
BackendConnectionService.encodeCredentials(username, password);
RequestQueue requestQueue = Volley.newRequestQueue(this);
BackendConnectionService.handleSSLHandshake();
// here I put the button
requestQueue.add(BackendConnectionService.createLogInRequest(this, logInButton));
}
}
Declaration of the second class
public class BackendConnectionService {
// some class declarations
static JsonArrayRequest createLogInRequest(Context packageContext, Button button){
final Context context = packageContext;
final Button b = button;
return new JsonArrayRequest(
Request.Method.GET,
PALLETE_URL,
null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Intent intent = new Intent(context, PalletsScreen.class);
context.startActivity(intent);
b.setEnabled(true);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("REST ResponseErr", error.toString());
Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
b.setEnabled(true);
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put(autorisation, encodedCredentials);
return headers;
}
};
}
}
Upvotes: 0
Views: 240
Reputation: 1648
To be honest with you, you already did it :). You just need to know how to use it. Let's say that you want to use your LogInScreen in your createLogInRequest
method:
static JsonArrayRequest createLogInRequest(Context packageContext, Button button){
final Context context = packageContext;
final Button b = button;
LogInScreen logInScreen = null;
if(context instanceof LogInScreen) {
logInScreen = (LogInScreen) context;
}
//...
}
Upvotes: 1