4

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

4
  • i am not sure but it looks like this ">" shouldnt be in url. maybe its generated by the exception but if not have a look at it Commented Dec 2, 2016 at 10:03
  • then you have a problem with readingyour xml file. as i know xml looks like this <url>testurls</url> this should mean that you take the > from first url into your url Commented Dec 2, 2016 at 10:10
  • @XtremeBaumer: Thanks for your quick solution i have mistakenly inserted two " > " in my xml file. thanks a lot Commented Dec 2, 2016 at 10:15
  • no problem mate. happens to the best of us xD Commented Dec 2, 2016 at 10:16

1 Answer 1

4

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 >.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for letting me rectify the issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.