I would like to sending string between java class in android studio. I have class CreateToken.java and MainActivity.java, how can I send string yourToken to MainActivity.java and how can I receive string yourToken in MainActivity.java, and the result of yourToken is com.example.user.application.CreateToken#yourToken but yourToken is not full token, its just 7 charecter.
This is one of my function in CreateToken.java:
public class CreateToken {
private ICreateToken listener;
public CreateToken(ICreateToken listener) {
this.listener = listener;
}
public Call<Token> api(final Context ctx){
ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
String usernameApi = "web";
String passwordApi = "123";
Call<Token> getToken = api.postWebService(usernameApi,passwordApi);
getToken.enqueue(new Callback<Token>() {
#Override
public void onResponse(Call<Token> call, Response<Token> response) {
String error = response.body().getError();
if (error.equals("false")){
Toast.makeText(ctx, response.body().getToken(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token Show");
String yourToken = response.body().getToken();
listener.onTokenGenerated(yourToken);
}else {
Toast.makeText(ctx, response.body().getMessage(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token NUll");
}
}
#Override
public void onFailure(Call<Token> call, Throwable t) {
Log.d("Smart","Response : Token Null");
}
});
return getToken;
}
public interface ICreateToken {
void onTokenGenerated(String token);
}
}
And this is my MainActivity.java:
public class MainActivity extends AppCompatActivity implements CreateToken.ICreateToken {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
CreateToken token = new CreateToken(MainActivity.this);
textView.setText(token.toString());
}
#Override
public void onTokenGenerated(String token) {
}
}
You must call api like below for sending request to server:
CreateToken tokenCreator = new CreateToken(MainActivity.this);
tokenCreator.api(this);
and wait to triggered onTokenGenerated and using String token
#Override
public void onTokenGenerated(String token) {
textView.setText(token.toString());
}
You should have access to yourToken in MainActivity in
#Override
public void onTokenGenerated(String token) {
}
when listener.onTokenGenerated(yourToken); in CreateToken is executed. Just call public Call<Token> api(final Context ctx) method, and receive your token in MainActivity.
Related
Good night everybody.
I need to do a POST request and I'm using Retrofit 2 to do this.
But the Api I'm consuming does not give me these parameters in the API response, just in the body.
Api Response
I already searched in some places but I did not find anything that could help me.
My interface Class
public interface LoginApi {
#POST("api/login")
Call<UserAccount> doLogin(#Body Login login);
}
My Model Class
public class Login {
public String user;
public String password;
}
My API response class
public class UserAccount {
#SerializedName("userId")
#Expose
private Integer userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("bankAccount")
#Expose
private String bankAccount;
#SerializedName("agency")
#Expose
private String agency;
#SerializedName("balance")
#Expose
private Double balance;
}
My call class
public class LoginPresenter {
private LoginView loginView;
private ServiceConfig serviceConfig;
public LoginPresenter() {
this.loginView = loginView;
if (this.serviceConfig == null) {
this.serviceConfig = new ServiceConfig();
}
}
public void doLogin(Login login) {
serviceConfig
.login()
.doLogin(login)
.enqueue(new Callback<UserAccount>() {
#Override
public void onResponse(Call<UserAccount> call, Response<UserAccount> response) {
UserAccount userAccount = response.body();
assert userAccount != null;
Log.e("Agency:",userAccount.getAgency());
Log.e("BankAccount:", userAccount.getBankAccount());
Log.e("Name:", userAccount.getName());
}
#Override
public void onFailure(Call<UserAccount> call, Throwable t) {
Log.d("Erro", t.getMessage());
}
});
}
}
My Activity
public class LoginActivity extends Activity implements LoginView {
private EditText edtUser, edtPassword;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
}
private void init() {
edtUser = findViewById(R.id.edt_user);
edtPassword = findViewById(R.id.edt_password);
btnLogin = findViewById(R.id.btn_login);
final LoginPresenter loginPresenter = new LoginPresenter();
final Login login = new Login();
login.user = edtUser.getText().toString();
login.password = edtPassword.getText().toString();
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginPresenter.doLogin(login);
}
});
}
#Override
public void userAccount(List<UserAccount> userAccount) {
}
}
I hope I have made my problem clear and that someone who has been through it can help me.
Appreciate.
Pass #Body JsonObject body instead of #Body Login login
Here is full code:
Your interface will be:
public interface LoginApi {
#POST("api/login")
Call<UserAccount> doLogin(#Body JsonObject body);
}
How to Create JsonObject :
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("user", userValue);
jsonObject.addProperty("password", passwordValue);
Pass it from your activity to presenter.
Hope it will works for you.
Thank you.
Pass Like This:-
You Interface
public interface ApiInterface {
String URL_BASE = "Base Url";
#Headers("Content-Type: application/json")
#POST("login")
Call<User> getUser(#Body String body);
}
Activity
public class SampleActivity extends AppCompatActivity implements Callback<User> {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// prepare call in Retrofit 2.0
try {
JSONObject paramObject = new JSONObject();
paramObject.put("email", "sample#gmail.com");
paramObject.put("pass", "4384984938943");
Call<User> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResponse(Call<User> call, Response<User> response) {
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
}
hello guys I would like to sending string between java class in android studio.
I have class CreateToken.java and MainActivity.java, how can I send String yourToken to MainActivity.java and how can i receive string yourToken in MainActivity.java, and the result of yourToken is com.example.user.application.CreateToken#yourToken but yourToken is not full token , its just 7 charecter.
this is one of my function in CreateToken.java :
public class CreateToken {
private ICreateToken listener;
public CreateToken(ICreateToken listener) {
this.listener = listener;
}
public Call<Token> api(final Context ctx){
ApiInterface api = ApiClient.getClient().create(ApiInterface.class);
String usernameApi = "web";
String passwordApi = "123";
Call<Token> getToken = api.postWebService(usernameApi,passwordApi);
getToken.enqueue(new Callback<Token>() {
#Override
public void onResponse(Call<Token> call, Response<Token> response) {
String error = response.body().getError();
if (error.equals("false")){
Toast.makeText(ctx, response.body().getToken(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token Show");
String yourToken = response.body().getToken();
listener.onTokenGenerated(yourToken);
}else {
Toast.makeText(ctx, response.body().getMessage(),Toast.LENGTH_SHORT).show();
Log.d("Smart","Response : Token NUll");
}
}
#Override
public void onFailure(Call<Token> call, Throwable t) {
Log.d("Smart","Response : Token Null");
}
});
return getToken;
}
public interface ICreateToken {
void onTokenGenerated(String token);
}
}
and this is my MainActivity.java :
public class MainActivity extends AppCompatActivity implements CreateToken.ICreateToken {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
CreateToken token = new CreateToken(MainActivity.this);
textView.setText(token.toString());
}
#Override
public void onTokenGenerated(String token) {
}
}
I think that you could use the AsyncTask class from Android framework:
https://developer.android.com/reference/android/os/AsyncTask
Then use the methods doInBackground to call the webservice and onPostExecute use the response from that call:
public ActivityExample extends AsyncTask <clazz1,clazz2,clazz3> {
doInBackGround(clazz1 clazz){
return result;
}
onPostExecute(clazz2 result){
}
}
create an interface ICreateToken within CreateToken class as below
public interface ICreateToken {
void onTokenGenerated(String token);
}
Also declare Interface field in CreateToken class
private ICreateToken listener;
and from your MainActivity pass context in CreateToken class like this
CreateToken token = new CreateToken(MainActivity.this);
then initialise the listener in CreateToken constructor
public CreateToken(ICreateToken listener) {
this.listener = listner;
}
finally from onResponse you can return token via
listener.onTokenGenerated(yourToken)
Last and most important
MainActivity extends AppCompatActivity implements ICreateToken
implement ICreateToken in MainActivity which will ask to implement onTokenGenerated in MainActivity there you'll receive your token.
How can I get the data from getDataForId(Integer.toString(1)); by calling the same getDataForId method from the DisplayData class?
I want reuse the same method and get the result.
It doesn't make sense to copy and paste the same method into the other activity class. Then there will be the same code repeated twice.
This is my DisplayData.class
public class DisplayData extends AppCompatActivity {
Detail reqDetail;
String BASE_URL = "";
TextView name;
ImageView image;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_data);
name = (TextView) findViewById(R.id.name);
image = (ImageView)findViewById(R.id.image);
public void getDataForId(final String id) {
ApiInterface apiInterface = APIClient.getApiInterface();
Call<MyResponse> call = apiInterface.getResponse();
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response.body() != null) {
MyResponse myResponse = response.body();
List<Detail> details = myResponse.getDetails();
for (Detail d : details) {
if (d.getId().equals(id)) {
reqDetail = d;
name.setText(reqDetail.getName());
Picasso.with(DisplayData.this)
.load(reqDetail.getName())
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(image);
}
}
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
}
This is my SecondData class where I want to display the same data response of DisplayData by reusing same methods
public class SecondData extends AppCompatActivity {
Detail reqDetail;
String BASE_URL = "";
TextView name;
ImageView image;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
name = (TextView) findViewById(R.id.name);
image = (ImageView)findViewById(R.id.image);
}
}
Create a class to make retrofit call like this
public class SampleClass {
private DataInterface mListener;
public SampleClass() {
super();
}
public void getDataForId(final String id) {
ApiInterface apiInterface = APIClient.getApiInterface();
Call<MyResponse> call = apiInterface.getResponse();
call.enqueue(new Callback<MyResponse>() {
#Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (response!=null && response.body() != null && mListener != null) {
mListener.responseData(response.body());
}
}
#Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
}
public void setOnDataListener(DataInterface listener) {
mListener = listener;
}
public interface DataInterface {
void responseData( MyResponse myResponse );
}
}
And in your activity just call the class like this
SampleClass sampleClass = new SampleClass();
sampleClass.setOnDataListener(new SampleClass.DataInterface() {
#Override
public void responseData(MyResponse myResponse) {
}
});
sampleClass.getDataForId("UR ID");
Also in your class store the ID as private memeber variable
private Integer YOUR_ID;
Then on getting the result compare the result ID with this ID
List<Detail> details = myResponse.getDetails();
for (Detail d : details) {
if (d.getId().equals(YOUR_ID)) {
reqDetail = d;
name.setText(reqDetail.getName());
Picasso.with(DisplayData.this)
.load(reqDetail.getName())
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(image);
}
}
You should create a BaseActivity and extend the other two from it. Then, you place the method you want to use in both of them in the BaseActivity and make it public so you can use it properly.
Note that anything you need in your method from outside it won't be available in the BaseActivity, so you should either pass in the constructor or declare it in the BaseActivity if possible.
You should also think on how the return of your method should be for you to have access to its results.
You can refer to this question to learn more:
trying not to repeat myself (android/java)
So, If you want to use response of one Activity to another Activity,
Then, First save response to List or ArrayList.
And Then Pass data Using Intent.
That should do a trick.
How can I call the method "loginprep" of the LoginActivityClass from the FingerPrintClass?
See in the code...I wrote in where I want to call the loginprep with: "//Here I need the method loginprep() from the LoginActivity class"
FingerprintHandler.java
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
Toast.makeText((Activity)context, "Fingerprint Authentication error.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
Toast.makeText((Activity)context, "Fingerprint Authentication help.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationFailed() {
Toast.makeText((Activity)context, "Fingerprint Authentication failed.", Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
//Here I need the method loginprep() from the LoginActivity class
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
public void loginprep() {
SharedPreferences sharedPreferencesF = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPreferencesF.getString("username", "");
String pwd = sharedPreferencesF.getString("password", "");
loginUser(urn, pwd);
}
private void launchHomeScreen() {
Intent homeActivity = new Intent (LoginActivity.this,HomeActivity.class);
LoginActivity.this.startActivity(homeActivity);
finish();
}
public void loginUser(final String urn, final String pwd){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
System.out.println("JSON RESPONSE: " + jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
if (success) {
launchHomeScreen();
pd.dismiss();
Toast.makeText(LoginActivity.this,"Welcome back " + urn,Toast.LENGTH_LONG).show();
SharedPreferences sharedPref = getSharedPreferences("loginDatas", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", urn);
editor.putString("password", pwd);
editor.apply();
}
else {
loginButton.setBackgroundColor(0x73000000);
Toast.makeText(LoginActivity.this,"Wrong Username or Password!",Toast.LENGTH_LONG).show();
pd.dismiss();
}
}
catch (JSONException e) {
loginButton.setBackgroundColor(0x73000000);
e.printStackTrace();
pd.dismiss();
Toast.makeText(LoginActivity.this,response,Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loginButton.setBackgroundColor(0x73000000);
pd.dismiss();
System.out.println("Error: " + error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<>();
params.put(KEY_USERNAME,urn);
params.put(KEY_PASSWORD,pwd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Following:
MainActivity mActivity = new MainActivity();
this is not the way Android is expecting you to create new instances of an activity, normally you wait the onCreate callback as described in the activity lifeCycle...
no following that approach you will need another way to communicate 2 different activities, what way must be taken depends on the specific arch of your application... the most commonly implemented could be using self defined interfaces and implement you custom callbacks...
You're writing a FingerPrint callback class, which means there is some onAuthenticationSucceeded method that is called when the "authentication succeeds."
How about you implement your own callback to pass back into the LoginActivity?
In other words, you'd
1) Write an interface
public interface LoginListener {
void onLoginSuccess();
void onLoginFailed();
}
2) Have the Activity implements LoginListener and have the Activity method of onLogin do your non-static stuff with the SharedPreferences,
public class LoginActivity extends AppCompatActivity
implements LoginListener {
public static final String KEY_USERNAME = "username";
public static final String KEY_PASS = "password";
private FingerprintHandler fingerprintHandler;
#Override
public void onLoginFailed() { }
#Override
public void onLoginSuccess() {
SharedPreferences sharedPrefs = getSharedPreferences("loginDatasFinger", Context.MODE_PRIVATE);
String urn = sharedPrefs.getString(KEY_USERNAME, "");
String pwd = sharedPrefs.getString(KEY_PASS, "");
loginUser(urn, pwd);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_login);
fingerprintHandler = new FingerprintHandler(this);
}
// public void loginUser(final String urn, final String pwd){ }
}
3) Expect to pass in a LoginListener as a parameter to that separate class.
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private final Context mContext;
private LoginListener mListener;
// Constructor
public FingerprintHandler(Context context) {
mContext = context;
if (context instanceof LoginListener) {
this.mListener = (LoginListener) context;
} else {
throw new ClassCastException("FingerprintHandler: context must implement LoginListener!");
}
}
4) And you do then can use your callback from the other callback.
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
if (mListener != null) {
mListener.onLoginSuccess();
}
}
I try the same method of initial&update using in Thermostat object to SmokeCOAlarm object but not work.
Does anyone know how to initial&update SmokeCOAlarm object?
or Nest hasn't opened for access SmokeCOAlarm object?!
Following is my code:
public class COSmokeAlarm extends Activity implements
NestAPI.AuthenticationListener, Listener.SmokeCOAlarmListener, Listener.ThermostatListener {
private Listener mUpdateListener;
private NestAPI mNestApi;
private SmokeCOAlarm mSmokeCOAlarm;
private Thermostat mThermostat;
private AccessToken mToken;
TextView txvBattery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_co_smoke_alarm);
txvBattery = (TextView)findViewById(R.id.txvBattery);
mNestApi = NestAPI.getInstance();//Initial NestAPI, connect Firebase
mToken = Settings.loadAuthToken(this);//Loade AccessToken
authenticate(mToken);
}
private void updateBatteryTextView() {
if (mSmokeCOAlarm != null) {
txvBattery.setText(mSmokeCOAlarm.getBatteryHealth());
}
}
private void authenticate(AccessToken token) {
Log.v("COSmokeAlarm", "Authenticating...");
NestAPI.getInstance().authenticate(token, this);
}
#Override
public void onAuthenticationSuccess() {
Log.v("COSmokeAlarm", "Authentication succeeded.");
fetchData();
}
#Override
public void onAuthenticationFailure(int errorCode) {
Log.v("COSmokeAlarm", "Authentication failed with error: " + errorCode);
}
private void fetchData() {
Log.v("COSmokeAlarm", "Fetching data...");
mUpdateListener = new Listener.Builder()
.setSmokeCOAlarmListener(this)
.setThermostatListener(this)
.build();
mNestApi.addUpdateListener(mUpdateListener);
Toast.makeText(COSmokeAlarm.this, "Success fetching data.", Toast.LENGTH_SHORT).show();
}
#Override
public void onSmokeCOAlarmUpdated(#NonNull SmokeCOAlarm smokeCOAlarm) {
Log.v("COSmokeAlarm", String.format("COSmoke Alarm (%s) updated.", smokeCOAlarm.getDeviceID()));
this.mSmokeCOAlarm = smokeCOAlarm;
updateBatteryTextView();
}
#Override
public void onThermostatUpdated(#NonNull Thermostat thermostat) {
Log.v("COSmokeAlarm", String.format("Thermostat (%s) updated.", thermostat.getDeviceID()));
mThermostat = thermostat;
}
}
Go to Nest account and add permission "Smoke+CO alarm read v4"
then we can access SmokeCOAlarm information.