Basically, I am trying to get some value from the Api callback response, then assign those value to some of my member variables, but It seems like the program has to run over my getPatientRecord() method each time before it could go to my call, which I have never encountered before.
The Log output result is :
viewPatient: paitient method
viewPatient: secondHello worldnullnull
100SN9 - David Hello H M H 1971-08-09
This is my code:
public class ViewPatientRecord extends AppCompatActivity{
TextView tvName, tvGender, tvBirthDate, tvAddress;
String pGender, pAddress, pBirthdate;
String pName = "Hello world";
Patient myPatient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_patient_record);
tvName = findViewById(R.id.tvFullName);
tvGender = findViewById(R.id.tvGender);
tvBirthDate = findViewById(R.id.tvDb);
tvAddress = findViewById(R.id.tvAddress);
myPatient= new Patient();
try {
getPatientRecord();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void getPatientRecord() throws InterruptedException {
SharedPreferences myPre = getSharedPreferences("PatientRecord", MODE_PRIVATE);
if(myPre.getString("uuid",null)!=null){
retrievePatientByUuid(myPre.getString("uuid",null));
Log.d("viewPatient", "second"+pName+pGender+pBirthdate);
tvName.setText(pName);
tvGender.setText(pGender);
tvBirthDate.setText(pBirthdate);
tvAddress.setText(pAddress);
}else{
Toast.makeText(ViewPatientRecord.this, "Something went wrong, please contact the administrator for help!", Toast.LENGTH_SHORT).show();
}
}
private void retrievePatientByUuid(String uuid) throws InterruptedException {
RestApi api = RetrofitInstance.getRetrofitInstance().create(RestApi.class);
Log.d("viewPatient", "paitient method");
Call<Patient> call = api.getPatientByUUID(uuid, null);
call.enqueue(new Callback<Patient>() {
private volatile Patient obj = new Patient();
#Override
public void onResponse(Call<Patient> call, Response<Patient> response) {
if (response.body() != null) {
Patient patient = response.body();
if (patient != null) {
if (!patient.getDisplay().isEmpty()) {
pName = patient.getDisplay();
pGender = patient.getPerson().getGender();
pBirthdate = patient.getPerson().getBirthdate();
Log.d("viewPatient", pName.toString() + " H " + pGender.toString() + " H " + pBirthdate.toString() + " ?? ");
pAddress = "";
} else {
Log.d("viewPatient", "no results");
}
} else {
Toast.makeText(ViewPatientRecord.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(ViewPatientRecord.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Patient> call, Throwable t) {
t.printStackTrace();
}
});
}
}
I don't see the problem. The call is done in retrievePatientByUuid which is called by getPatientRecord. So yes, you have to go through getPatientRecord. The call is async. It's in the callback that you should set your TextViews :
tvName.setText(pName);
tvGender.setText(pGender);
tvBirthDate.setText(pBirthdate);
tvAddress.setText(pAddress);
Related
Simple as that, I made a program with subscription, when the user subscribe, a boolean value turns to true.
when i test my software, if i cancel the subscription or it is automatically finished, the boolean value still return true.
I need to put in my code a check to see if the subscription is still available or not
As I am new to android studio, I have looked for that problem for 2 weeks so far but didn't find a solution for it.
All the solutions and posts are talking a bout the old in-App library (AIDL) with this magic line
Bundle ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
but it seems that doesn't work in the new Google Play Billing library.
here is my Billing Activity:
;
public class BillingActivity extends AppCompatActivity implements PurchasesUpdatedListener {
private static final String TAG = "BillingActivity";
private Button button;
protected SharedPreferences mSharedPreferences;
private boolean checkActivation;
private BillingClient mBillingClient;
private List<String> skuList;
private SkuDetailsParams.Builder skuParams;
private BillingFlowParams flowParams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_billing);
// Shred Preferences & Active user Initialize
checkActivation = false;
mSharedPreferences = this.getSharedPreferences("com.aterosolutions.customerspremiums", Context.MODE_PRIVATE);
if (mSharedPreferences.getInt("activeUser", 0) == 1) { // 0 ==> InActiveUser 1 ==> ActiveUser
//mSharedPreferences.edit().putInt("activeUser", 1).apply();
checkActivation = true;
} else {
//mSharedPreferences.edit().putInt("activeUser", 0).apply();
checkActivation = false;
}
Toast.makeText(this, checkActivation + "", Toast.LENGTH_SHORT).show();
// SKU List
skuList = new ArrayList<>();
skuList.add("premiums_subscribe");
skuParams = SkuDetailsParams.newBuilder();
skuParams.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
// Establish connection to billing client
mBillingClient = BillingClient.newBuilder(this).enablePendingPurchases().setListener(this).build();
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
Log.i(TAG, "onBillingSetupFinished: start" + billingResult.getResponseCode());
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
Log.i(TAG, "onBillingSetupFinished: second congrat");
} else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) {
Log.i(TAG, "onBillingSetupFinished: you own it");
} else {
Log.i(TAG, "onBillingSetupFinished: not your product");
}
}
#Override
public void onBillingServiceDisconnected() {
Toast.makeText(BillingActivity.this, "Connection Error", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onBillingServiceDisconnected: Connection Error");
}
});
queryPurchases();
//checkPurchsedItem();
// Button Handle
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.querySkuDetailsAsync(skuParams.build(), new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {
flowParams = BillingFlowParams.newBuilder().setSkuDetails(skuDetailsList.get(0)).build();
BillingResult response = mBillingClient.launchBillingFlow(BillingActivity.this, flowParams);
Log.i(TAG, "onSkuDetailsResponse: " + billingResult.getResponseCode());
Log.i(TAG, "onSkuDetailsResponse: response OK");
Log.i(TAG, "onSkuDetailsResponse: my test" + response);
Log.i(TAG, "onSkuDetailsResponse: queryPurshase01 " + mBillingClient.queryPurchases(BillingClient.SkuType.SUBS));
/* (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && skuDetailsList != null) {
flowParams = BillingFlowParams.newBuilder().setSkuDetails(skuDetailsList.get(0)).build();
mBillingClient.launchBillingFlow(BillingActivity.this, flowParams);
Log.i(TAG, "onSkuDetailsResponse: response OK");
}else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED && skuDetailsList != null){
Log.i(TAG, "onSkuDetailsResponse: response already Owned");
}else {
Log.i(TAG, "onSkuDetailsResponse: response something else");
}*/
}
});
}
});
}
#Override
public void onPurchasesUpdated(BillingResult billingResult, #Nullable List<Purchase> purchases) {
Log.i(TAG, "onPurchasesUpdated: start /// purchses"+ billingResult.getResponseCode() );
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK /*&& purchases != null*/) {
mSharedPreferences.edit().putInt("activeUser", 1).apply();
MainScreenActivity.activeUser = true;
for (Purchase purchase : purchases) {
handleNewPurchase(purchase);
}
} else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED /*&& purchases != null*/) {
Log.i(TAG, "onPurchasesUpdated: You Already Own It");
Toast.makeText(this, "Already Owned", Toast.LENGTH_SHORT).show();
mSharedPreferences.edit().putInt("activeUser", 1).apply();
MainScreenActivity.activeUser = true;
} else if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.USER_CANCELED /*&& purchases != null*/) {
Log.i(TAG, "onPurchasesUpdated: User Canceled");
Toast.makeText(this, "User Canceled", Toast.LENGTH_SHORT).show();
} else {
Log.i(TAG, "onPurchasesUpdated: other error " + billingResult.getResponseCode());
}
}
private void handleNewPurchase(Purchase purchase) {
Log.i(TAG, "handleNewPurchase: queryPurshase00 " + mBillingClient.queryPurchases(BillingClient.SkuType.SUBS).getBillingResult());
for (int i = 0; i < skuList.size(); i++) {
if (purchase.getSku() == skuList.get(i)) {
mSharedPreferences.edit().putInt("activeUser", 1).apply();
MainScreenActivity.activeUser = true;
Toast.makeText(this, "congrat dear", Toast.LENGTH_SHORT).show();
Log.i(TAG, "handleNewPurchase: product purchsed ");
// Acknowledge the purchase if it hasn't already been acknowledged.
if (!purchase.isAcknowledged()) {
Log.i(TAG, "handlePurchase: ok02");
AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = new AcknowledgePurchaseResponseListener() {
#Override
public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
}
};
Log.i(TAG, "handleNewPurchase: aknowledge done");
mBillingClient.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
} else {
Log.i(TAG, "handleNewPurchase: no need to aknowledge");
}
}
}
}
private void queryPurchases() {
Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.SUBS);
if (purchasesResult != null) {
List<Purchase> purchaseList = purchasesResult.getPurchasesList();
if (purchaseList == null) {
return;
}
if (!purchaseList.isEmpty()){
for (Purchase purchase : purchaseList){
if (purchase.getSku().equals(skuList.get(0))){
//mSharedPreferences.edit().putInt("activeUser", 1).apply();
//MainScreenActivity.activeUser = true;
}
}
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mBillingClient.endConnection();
}
private void checkPurchsedItem(){
mBillingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.SUBS, new PurchaseHistoryResponseListener() {
#Override
public void onPurchaseHistoryResponse(BillingResult billingResult, List<PurchaseHistoryRecord> purchaseHistoryRecordList) {
Log.i(TAG, "onPurchaseHistoryResponse: " + billingResult.getResponseCode());
}
});
Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.SUBS);
Log.i(TAG, "checkPurchsedItem: " + purchasesResult.getBillingResult());
try {
Log.i(TAG, "checkPurchsedItem: " + purchasesResult.getPurchasesList().size());
}catch (Exception e){
e.printStackTrace();
}
Log.i(TAG, "checkPurchsedItem: " + purchasesResult.getResponseCode());
Log.i(TAG, "checkPurchsedItem: " + purchasesResult.getBillingResult());
}
}
After lots of headache (like always with Google APIs and services) I figured out how one can access Google Play Developer API information (like billing) by using existing APIs.
1.) Create in Developer API Console a service account (JSON) key:
2.) Download this service-account-private-key.json file (don't mistake it with the OAuth2.0 client secret file!).
3.) In Google Play Developer Console go to Settings -> Users & Permissions -> Invite New User and set as user e-mail of the new user the client_email from the downloaded file. Assign the access rights you want to give to this users via the checkboxes inside this view (for example 'View financial data').
4.) Add the proper dependency to your project (version ...-1.23.0 does not work for me):
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-androidpublisher</artifactId>
<version>v2-rev50-1.22.0</version>
</dependency>
5.) Load the service-account-private-key.json file into your application. In my case it's a webserver:
#Singleton
#Startup
public class WebserverConfiguration
{
private String serviceAccountPrivateKeyFilePath;
/** Global instance of the HTTP transport. */
public static HttpTransport HTTP_TRANSPORT;
/** Global instance of the JSON factory. */
public static JsonFactory JSON_FACTORY;
private GoogleCredential credential;
#PostConstruct
public void init()
{
assignServiceAccountFileProperty();
initGoogleCredentials();
}
public String getServiceAccountPrivateKeyFilePath()
{
return serviceAccountPrivateKeyFilePath;
}
public GoogleCredential getCredential()
{
return credential;
}
private void initGoogleCredentials()
{
try
{
newTrustedTransport();
newJsonFactory();
String serviceAccountContent = new String(Files.readAllBytes(Paths.get(getServiceAccountPrivateKeyFilePath())));
InputStream inputStream = new ByteArrayInputStream(serviceAccountContent.getBytes());
credential = GoogleCredential.fromStream(inputStream).createScoped(Collections.singleton(AndroidPublisherScopes.ANDROIDPUBLISHER));
}
catch (IOException | GeneralSecurityException e)
{
throw new InitializationException(e);
}
}
private void newJsonFactory()
{
JSON_FACTORY = JacksonFactory.getDefaultInstance();
}
private void assignServiceAccountFileProperty()
{
serviceAccountPrivateKeyFilePath = System.getProperty("service.account.file.path");
if (serviceAccountPrivateKeyFilePath == null)
{
throw new IllegalArgumentException("service.account.file.path UNKNOWN - configure it as VM startup parameter in Wildfly");
}
}
private static void newTrustedTransport() throws GeneralSecurityException, IOException
{
if (HTTP_TRANSPORT == null)
{
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
}
}
}
6.) Now I am able the fetch Google Play Developer API information, e.g. reviews:
private void invokeGoogleApi() throws IOException
{
AndroidPublisher publisher = new AndroidPublisher.Builder(WebserverConfiguration.HTTP_TRANSPORT, WebserverConfiguration.JSON_FACTORY, configuration.getCredential()).setApplicationName("The name of my app on Google Play").build();
AndroidPublisher.Reviews reviews = publisher.reviews();
ReviewsListResponse reviewsListResponse = reviews.list("the.packagename.of.my.app").execute();
logger.info("review list response = " + reviewsListResponse.toPrettyString());
}
This worked.
I cannot test it yet, but I'm sure that fetching the billing information works as well:
private SubscriptionPurchase getPurchase() throws IOException
{
AndroidPublisher publisher = new AndroidPublisher.Builder(WebserverConfiguration.HTTP_TRANSPORT, WebserverConfiguration.JSON_FACTORY, configuration.getCredential()).setApplicationName("The name of my app on Google Play").build();
AndroidPublisher.Purchases purchases = publisher.purchases();
SubscriptionPurchase purchase = purchases.subscriptions().get("the.packagename.of.my.app", "subscriptionId", "billing token sent by the app").execute();
//do something or return
return purchase;
}
I'd like to get the string value output from AsyncTask. And store it into a variable on my main thread. How can I do so?
I tried to do store = new ReceiveData().execute().get() however it throws an execution exception error. But anyway, my question is not about the execution exception error. I just need a way to get the string out, please help!
Here is my activity code:
public class MainActivity extends AppCompatActivity { //MAIN ACTIVITIES (REMOTE)
double multiplier;
int seekbarvalue, finallumens;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); //On orientation change socket will disconnect...
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toast.makeText(MainActivity.this, LoginActivity.SERVER_IP, Toast.LENGTH_LONG).show();
//================START AFTER DEFAULT ON CREATE=================
SeekBar seekbarbrightness = (SeekBar) findViewById(R.id.seekbarbrightness);
final TextView tblumens, tbvolts, tbamps;
tblumens = (TextView) findViewById(R.id.tblumens);
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
tbvolts = (TextView) findViewById(R.id.tbvolts);
tbamps = (TextView) findViewById(R.id.tbamps);
seekbarbrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekbarbrightness, int progress, boolean b) {
if (b == true) {
seekbarvalue = seekbarbrightness.getProgress();
multiplier = (double) seekbarvalue / 100;
finallumens = (int) (multiplier * LoginActivity.enterlumens);
tblumens.setText(String.valueOf(finallumens) + " Lumens");
if (LoginActivity.getSocket() != null) {
try {
LoginActivity.getSocket().getOutputStream().write(String.valueOf(multiplier).getBytes());
new ReceiveData().execute();
//infinite loop here to keep receiving volts and amperes.
//Do a split and assign value to volt and amp
//String[] strrecv= store.split("|");
//String volts = strrecv[0];
//String amps = strrecv[1];
//tbvolts.setText("Voltage: " + volts + " V");
//tbamps.setText("Amperes:" + amps + " A");
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "NOT connected To Socket, please disconnect and reconnect!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
And in my Asynctask I am doing this.
class ReceiveData extends AsyncTask<Void, Void, String> {
String str;
protected String doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
String str = "fail";
return str;
}
}
protected void onPostExecute(String str) {
//super.onPostExecute(str);
}
}
The purpose of AsyncTask is to perform asynchronous task in a separate thread to free the main thread and avoid UX issues. For your purpose, I suggest transferring all of the work inside your try block inside the AsyncTask and update the UI after execution.
Something like this
In MainThread
new ReceiveData().execute();
In AsyncTask
class ReceiveData extends AsyncTask<Void, Void, Boolean> {
String volts;
String amps;
protected Boolean doInBackground(Void... args) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(LoginActivity.getSocket().getInputStream()));
str = in.readLine();
String[] strrecv= store.split("|");
volts = strrecv[0];
amps = strrecv[1];
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
protected void onPostExecute(Boolean result) {
if (result) {
tbvolts.setText("Voltage: " + volts + " V");
tbamps.setText("Amperes:" + amps + " A");
}
}
}
Note that this only works if your AsyncTask is defined inside your Activity. If not, you need to create an interface from the AsyncTask and implement it in your activity and activate it onPostExecute
Hi i am trying to send some data to server by using json parsing but activity is getting crashed and it leads to
java.lang.IllegalArgumentException: unexpected url
This is My Activity Code and i am commenting the lines where i am getting the Errors.
public class LoginActivity extends AppCompatActivity { **// Showing Error at this LIne**
public Location location;
private Button btnLogin;
private boolean doubleBackToExitPressedOnce = false;
private EditText phoneNo, password;
private CheckBox cbShow, cbRemember;
private NetworkUtil networkUtil;
private SharePrefUtil sharePref;
private LocationInfo locationInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
networkUtil = new NetworkUtil(getApplicationContext());
sharePref = new SharePrefUtil(getApplicationContext());
initScreen();
if (sharePref.getValueFromSharePref("remeberFlag").equalsIgnoreCase("true")) {
phoneNo.setText(sharePref.getValueFromSharePref("mobileno"));
password.setText(sharePref.getValueFromSharePref("password"));
cbRemember.setChecked(true);
}
}
private void initScreen() {
LocationLibrary.showDebugOutput(true);
try {
LocationLibrary.initialiseLibrary(LoginActivity.this, 60 * 1000, 60 * 1000 * 2, "com.aspeage.jagteraho");
} catch (UnsupportedOperationException e) {
Toast.makeText(this, "Device doesn't have any location providers", Toast.LENGTH_LONG).show();
}
phoneNo = (EditText) findViewById(R.id.ed_phoneno);
password = (EditText) findViewById(R.id.ed_password);
cbRemember = (CheckBox) findViewById(R.id.cbox_rememberme);
cbRemember.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) sharePref.setValueInSharePref("remeberFlag", "true");
else sharePref.setValueInSharePref("remeberFlag", "false");
}
});
cbShow = (CheckBox) findViewById(R.id.cbox_showpass);
cbShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
} else {
password.setInputType(129);
}
}
});
btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new ButtonClick());
}
private class ButtonClick implements View.OnClickListener {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_login:
btnLoginClicked();
break;
default:
break;
}
}
}
private void btnLoginClicked() {
if(phoneNo.getText().toString().trim().equals("admin") && password.getText().toString().trim().equals("admin")) {
loginService();
}
if (validation()) {
if (cbRemember.isChecked())
rememberMe(password.getText().toString().trim());
if (networkUtil.isConnected()) {
loginService();
} else {
new SweetAlertDialog(LoginActivity.this, cn.pedant.SweetAlert.SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No Network Connection")
.show();
}
}
}
/**
* save username and password in SharedPreferences.
*
* #param //password is key value for storing in SharedPreferences.
*/
public void rememberMe(String password) {
SharePrefUtil sharePref = new SharePrefUtil(getApplicationContext());
sharePref.setValueInSharePref("password", password);
}
private boolean validation() {
int errorCount = 0;
if (phoneNo.getText().toString().trim().equals("")
|| phoneNo.getText().length() != 10) {
phoneNo.setError("Enter valid phone number");
errorCount = errorCount + 1;
if (errorCount == 1) {
phoneNo.requestFocus();
}
} else {
phoneNo.setError(null);
}
if (password.getText().toString().trim().equals("")
|| password.getText().length() != 12) {
password.setError("Enter valid password");
errorCount = errorCount + 1;
if (errorCount == 1) {
password.requestFocus();
}
} else {
password.setError(null);
}
if (errorCount == 0) {
return true;
} else {
return false;
}
}
private void batteryTimer(){
Timer timer = new Timer();
TimerTask hourlyTask = new TimerTask() {
#Override
public void run() {
if (networkUtil.isConnected()) {
batteryLevelCheckService(); // **Getting Error at this Line**
}
else {
offlineBatteryStatus();
}
}
};
timer.scheduleAtFixedRate(hourlyTask, 01, 60000);
}
private void batteryLevelCheckService() {
OkHttpClient client = new OkHttpClient();
String requestURL = String.format(getResources().getString(R.string.service_batteryLevelCheckService));
JSONArray jsonArrayRequest = new JSONArray();
JSONObject jsonRequest;
try {
List<BatteryStatusModel> batStatusOffline = new Select().from(BatteryStatusModel.class).execute();
if (batStatusOffline.size() > 0) {
for (BatteryStatusModel batStatusObject : batStatusOffline) {
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", batStatusObject.batStatTime);
jsonRequest.accumulate("batteryStatusLat", "" + batStatusObject.battery_lat);
jsonRequest.accumulate("batteryStatusLog", "" + batStatusObject.battery_lon);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobno", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + batStatusObject.batteryStatus);
jsonArrayRequest.put(jsonRequest);
}
}
Intent intent = this.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level * 100) / scale;
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String time = simpleDateFormat.format(today);
jsonRequest = new JSONObject();
jsonRequest.accumulate("strTime", time);
jsonRequest.accumulate("batteryStatusLat", "" + locationInfo.lastLat);
jsonRequest.accumulate("batteryStatusLon", "" + locationInfo.lastLong);
jsonRequest.accumulate("empAuthKey", sharePref.getValueFromSharePref("authKey"));
jsonRequest.accumulate("mobNo", "" + sharePref.getValueFromSharePref("mobileno"));
jsonRequest.accumulate("strBatteryStatus", "" + percent);
jsonArrayRequest.put(jsonRequest);
} catch (Exception e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonArrayRequest.toString());
Request request = new Request.Builder()
.url(requestURL) // Getting Error at this Line
.post(body).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String responseString = response.body().string();
try {
JSONObject jsonResponse = new JSONObject(responseString);
String status = jsonResponse.getString("status");
String message = jsonResponse.getString("message");
Log.d("jagteraho", "response :: status: " + status.toString() + " message: " + message);
if (status.equals("success")) {
new Delete().from(BatteryStatusModel.class).execute();
} else if (status.equals("failure")) {
} else if (status.equals("error")) {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
This is my Logcat
java.lang.IllegalArgumentException: unexpected url: >http://192.168.2.20:8080/jagteraho/batteryStatus/save
at okhttp3.Request$Builder.url(Request.java:143)
at com.aspeage.jagteraho.LoginActivity.batteryLevelCheckService(LoginActivity.java:270)
at com.aspeage.jagteraho.LoginActivity.access$600(LoginActivity.java:59)
at com.aspeage.jagteraho.LoginActivity$4.run(LoginActivity.java:216)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Please help me with the possible solutions i am quite new in Android Development
Your error is coming from OkHttp.
If you search for the error message, you can see where OkHttp is generating it:
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Request.java#L142
HttpUrl parsed = HttpUrl.parse(url);
if (parsed == null) throw new IllegalArgumentException("unexpected url: " + url);
return url(parsed);
It means that your URL is invalid. As the comment to your question points out: >http://192.168.2.20:8080/jagteraho/batteryStatus/save is not a valid URL.
You need to remove the >.
I have 2 different class, first class Tracking.java and second class ReportingService.java. how to passing location address on ReportingService.java to Tracking.java?
private void doLogout(){
Log.i(TAG, "loginOnClick: ");
//ReportingService rs = new ReportingService();
//rs.sendUpdateLocation(boolean isUpdate, Location);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(NetHelper.getDomainAddress(this))
.addConverterFactory(ScalarsConverterFactory.create())
.build();
ToyotaService toyotaService = retrofit.create(ToyotaService.class);
// caller
Call<ResponseBody> caller = toyotaService.logout("0,0",
AppConfig.getUserName(this),
"null");
// async task
caller.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i(TAG, "onResponse: "+response.body().string());
}catch (IOException e){}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "onFailure: ", t);
}
});
AppConfig.saveLoginStatus(this, AppConfig.LOGOUT);
AppConfig.storeAccount(this, "", "");
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
finish();
}
This code for location address
Call<ResponseBody> caller = toyotaService.logout("0,0",
AppConfig.getUserName(this),
"null");
And this is class ReportingService.java location of code get longtitude, latitude and location address from googlemap
private void sendUpdateLocation(boolean isUpdate, Location location) {
Log.i(TAG, "onLocationChanged "+location.getLongitude());
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
String street = "Unknown";
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knowName = addresses.get(0).getFeatureName();
street = address + " " + city + " " + state + " " + country + " " + postalCode + " " + knowName;
Log.i(TAG, "street "+street);
}
} catch (IOException e) {
e.printStackTrace();
}
if (isUpdate)
NetHelper.report(this, AppConfig.getUserName(this), location.getLatitude(),
location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() {
#Override
public void preEvent() {
}
#Override
public void postEvent(String... result) {
try {
int nextUpdate = NetHelper.getNextUpdateSchedule(result[0]); // in second
Log.i(TAG, "next is in " + nextUpdate + " seconds");
if (nextUpdate > 60) {
dismissNotification();
isRunning = false;
} else if (!isRunning){
showNotification();
isRunning = true;
}
handler.postDelayed(location_updater, nextUpdate * 1000 /*millisecond*/);
}catch (JSONException e){
Log.i(TAG, "postEvent error update");
e.printStackTrace();
handler.postDelayed(location_updater, getResources().getInteger(R.integer.interval) * 1000 /*millisecond*/);
}
}
});
else
NetHelper.logout(this, AppConfig.getUserName(this), location.getLatitude(),
location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() {
#Override
public void preEvent() {
}
#Override
public void postEvent(String... result) {
Log.i(TAG, "postEvent logout "+result);
}
});
}
Thanks
Use this library and follow the provided example inside it.
Its for passing anything you wish to anywhere you wish.
i think just using an interface will solve your problem.
pseudo code
ReportingException.java
add this
public interface myLocationListner{
onRecievedLocation(String location);
}
private myLocationListner mylocation;
//add below line where you get street address
mylocation.onRecievedLocation(street);
then implement myLocationListner in Tracking.java
there you go :)
You can use an intent:
The intent will fire the 2nd Receiver and will pass the data into that
If BroadcastReceiver:
Intent intent = new Intent();
intent.setAction("com.example.2ndReceiverFilter");
intent.putExtra("key" , ); //put the data you want to pass on
getApplicationContext().sendBroadcast(intent);
If Service:
Intent intent = new Intent();`
intent.putExtra("key" , value ); //put the data you want to pass on
startService( ReportingService.this , Tracking.class);
in Tracking.java, to retrieve the Data you passed on:
inside onReceive, put this code first
intent.getExtras().getString("key");//if int use getInt("key")
I'm trying to call my updateDisplay method through a for loop to set the text for the corresponding index, but in the output only the 5th index code is getting run.
Here is the for loop that I'm calling in my fragment's onCreateView();
private int mIndexofDays;
for(int i =1; i < 6; i++) {
DateTime nextday = mDateTime.plusDays(i);
long time = nextday.getMillis() / 1000;
getForecast(mLattitude, mLongitude, time);
mIndexofDays = i;
}
Here is the getForecast() method:
private void getForecast(double latitude, double longitude, long time)
{
String apiKey = getResources().getString(R.string.api_key);
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude + "," + time;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mWeather = getCurrentDetails(jsonData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Running....");
updateDisplay();
}
});
} else {
Log.d(TAG, "Response not successful");
}
} catch (IOException e) {
Log.e(TAG, " IOException caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "JSON exception caught: ", e);
}
}
});
}
And here is the updateDisplay() method:
private void updateDisplay() {
if(mIndexofDays == 1) {
mDayOfWeek1.setText(mDateTime.plusDays(1).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage1.setImageDrawable(drawable);
mHighTemp1.setText(mWeather.getTemperatureMax() + "");
mLowTemp1.setText(mWeather.getTemperatureMin() + "");
}
if(mIndexofDays == 2) {
mDayOfWeek2.setText(mDateTime.plusDays(2).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage2.setImageDrawable(drawable);
mHighTemp2.setText(mWeather.getTemperatureMax() + "");
}
if(mIndexofDays == 3) {
mDayOfWeek3.setText(mDateTime.plusDays(3).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage3.setImageDrawable(drawable);
mHighTemp3.setText(mWeather.getTemperatureMax() + "");
}
if(mIndexofDays == 4) {
mDayOfWeek4.setText(mDateTime.plusDays(4).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage4.setImageDrawable(drawable);
mHighTemp4.setText(mWeather.getTemperatureMax() + "");
}
if(mIndexofDays == 5) {
mDayOfWeek5.setText(mDateTime.plusDays(5).dayOfWeek().getAsShortText());
Drawable drawable = getResources().getDrawable(mWeather.getIconId());
mDayOfWeekImage5.setImageDrawable(drawable);
mHighTemp5.setText(mWeather.getTemperatureMax() + "");
}
else
{
Log.d(TAG, "Index to high!!!");
}
}
From the logs I can see that "Running" is getting called but updateDisplay never updates for 1-4 indexes only for the 5th index.
I am a very novice programmer, so please tell me on what is wrong with my style and better methods to do what I'm trying to do.
modify updateDisplay and pass a copy of mIndexofDays as a parameter, and this should work. I can provide the actual implementation code but I encourage you to try it first yourself.
hope this helps :)
change your for loop like this
for(int i =1; i < 6; i++) {
mIndexofDays = i;
DateTime nextday = mDateTime.plusDays(i);
long time = nextday.getMillis() / 1000;
getForecast(mLattitude, mLongitude, time, mIndexofDays); // new parameter: mIndexofDays
}
catch the parameter mIndexofDays in getForecast method and pass it through updateDisplay method. Next, use the value of mIndexofDays to compare in your if...else statements. You can use Log method or time delay method to check if it's actually working or not.
Well, the issue is that your updateDisplay() is called only when you receive response in onResponse(). Now, by the time this happens your loop has already ended and the value of mIndexofDays is 5. To fix the issue one of the things you can do is to pass the value of mIndexofDays to your getForecast() method:
private void getForecast(double latitude, double longitude, long time, int indexOfDays) {
...
updateDisplay(numberOfDays);
...
}
You also need to change your updateDisplay() method:
private void updateDisplay(int indexOfDays) {
...
}
Also, get rid of the mIndexOfDays instance variable since you [probably] don't need it anywhere.