Categories
discuss

Is there a way to preview a vector drawable

Short of building and installing my app, is there a way to preview a vector drawable xml file?

I’ve built it into a small test app in Android Studio, and can preview it as part of the layout file, but I was hoping for a simpler way.


Edit: here’s what my drawable.xml file looks like:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">

    <group>
        <path
            android:fillColor="#f5a625"
            android:strokeColor="#000000"
            android:strokeWidth=".5"
            android:pathData="M0,0l18,0l6,6l0,10l-24,0z" />
    </group>
</vector>

Answer

There is a Preview tab especial for that at the right side (since Android Studio 2.0):

enter image description here

Categories
discuss

How do I set a different number of port using Square’s okHttp?

I’m trying to connect okHttp with a web service but with different port, for example, 10000. My idea to stub the responses with a proxy during the unit tests. Neverthless, there is not enough documentation to make it with this library. As a matter of fact, my implementation is:

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(TIMEOUT_MS, TimeUnit.MILLISECONDS);

For example, with other libraries such as loopj, this feature is possible:

httpClient.setProxy("localhost", 10000);

I’m using this version: com.squareup.okhttp:okhttp:2.5.0

Answer

I’m trying to connect okHttp with a web service but with different port, for example, 10000

Put the port in the URL that you supply to Request.Builder:

Request request = new Request.Builder()
    .url("http://publicobject.com:10000/helloworld.txt")
    .build();

My idea to stub the responses with a proxy during the unit tests.

Use a different URL for the tests than you do in production.

Categories
discuss

How can I sort an ES6 `Set`?

new Set(['b', 'a', 'c']).sort() throws TypeError: set.sort is not a function. How can I sort a Set to ensure a particular iteration order?

Answer

A set is not an ordered abstract data structure.

A Set however always has the same iteration order – element insertion order [1], so when you iterate it (by an iterating method, by calling Symbol.iterator, or by a for.. of loop) you can always expect that.

You can always convert the set to an array and sort that.

Array.from(new Set(["b","a","c"])).sort();
[...(new Set(["b","a","c"]))].sort(); // with spread.

[1] forEach and CreateSetIterator

Categories
discuss

What is the reason of this error java.io.IOException: Content-Length and stream length disagree

I am getting this error

   java.io.IOException: Content-Length and stream length disagree

on this line of code return response.body().bytes();

this is full code

edit: after some google the reason of the error is from okhttp lib

if (contentLength != -1L && contentLength != bytes.size.toLong()) {
  throw IOException(
      "Content-Length ($contentLength) and stream length (${bytes.size}) disagree")
}

but how to fix that ?

edit:

enter image description here

this is full code:

public class OkHttpHandler extends AsyncTask<Void, Void, byte[]> {

    private final String Fetch_URL = "http://justedhak.comlu.com/get-data.php";
    ArrayList<Listitem> Listitem;
    int resulta;

    OkHttpClient httpClient = new OkHttpClient();

    String myJSON;
    JSONArray peoples = null;
    InputStream inputStream = null;

    @Override
    protected byte[] doInBackground(Void... params) {
        Log.d("e", "dddddddddd");
        Log.d("e", Fetch_URL);

        Request.Builder builder = new Request.Builder();
        builder.url(Fetch_URL);

        Request request = builder.build();

        String result = null;
        try {

            Response response = httpClient.newCall(request).execute();
          //  int statusCode = response.getStatusLine().getStatusCode();

              int statusCode =200;

           // HttpEntity entity = response.body().byteStream();
            if (statusCode == 200) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
            //    inputStream = response.body().byteStream();

                // json is UTF-8 by default
             //   BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            /*    StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "n");
                }
                result = sb.toString();*/
                resulta = 1; //"Success
                Log.d("e", "response.");
                return response.body().bytes();

            }
            else
            {
                resulta = 0; //"Failed

            }
        } catch (Exception e) {

            Log.d("e", "r2r2 error");

            e.printStackTrace();        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }
        return null;
    }

    protected void onPostExecute(String result){
        if( resulta ==1){
            myJSON=result;
            showList();
        }
        else{
            Log.e("d","zzzzzzzz");

        }
    }

    protected void showList(){
        try {
            Log.e("d","jjjjjjjjjj");

            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray("result");
            Listitem = new ArrayList<Listitem>();
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String id = c.getString("id");
                String url = c.getString("path");
                Listitem.add(new Listitem(id,url));
                Log.e("d","ppppp");
            }

         //   GridViewAdapter adapter = new GridViewAdapter(this, R.layout.grid_item_layout, Listitem);
            //   gridView.setAdapter(gridAdapter);
           // adapter.notifyDataSetChanged();

            //  list.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

Answer

That Exception thrown because you have called InputStream inputStream = response.body().byteStream(); then called response.body().bytes(); again.

You can use return bytes array from the inputStream or return result.getBytes(); instead if that is what you want to return.

From inputStream to bytes refer to the following:

    public byte[] getBytesFromInputStream(InputStream inputStream) throws IOException {
        try {            
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
            return output.toByteArray();
        } catch (OutOfMemoryError error) {
            return null;
        }
    }

UPDATE:

If you debug at ResponseBody.class, you will see as the following screenshot:

BNK's screenshot

Categories
discuss

Debounce on only one validator

I’ve just read the awesome angular page on form validation and I’ve probably missed something but how can I apply ng-model-options debounce property on a specific validator.

Let me explain the problem. I have a form that validate a public key and for that I have a directive called key-check that contains multiple validator. Some of them are local and synchronous like the format of the key and there is another asynchronous that check if the key is available on the server (asynchronously).

I don’t want my server to be flood nor the angular application to be slowed so I use that the cool kids call debouncing and my input seems something like :

<input type="text" ... ng-model="key" key-check ng-model-options="{ debounce: 700 }" ng-minlength="5" ng-maxlength="50"/>

And the directive is like :

ctrl.$validators.keyFormatCheck = function(modelValue) {
   // return boolean
}

ctrl.$asyncValidators.KeyAvailabilityCheck = function(modelValue) {
   // return promise
}

It’s work like a charm but all the check are done with 700ms latency and I wonder if it’s possible to do the keyFormatCheck without debouncing and the KeyAvailabilityCheck with it. I can probably use the old good way with $timeout but I prefer to do it the angular way.

Any ideas ?

Answer

ngModelController‘s debounce applies to the entire pipeline of parsers, validators and view-change-listeners (e.g. ng-change).

There is no way today (Angular v1.4) with ngModelOptions to isolate the debounce delay to a specific validator.

But the functionality is easily achieved by passing a delay parameter to your own async validator directive:

<input ng-model="val" foo-validator="{delay: 500}">

You implement the actual delay with $timeout; no reason here to avoid using $timeout on the grounds that it is somehow less than “the Angular way”; it’s not.

The only trick is to make sure that you cancel the previous pending validation request before executing a new one.

var pendingValidation;
ngModel.$asyncValidators.foo = function(modelValue, viewValue){

  if (pendingValidation) $timeout.cancel(pendingValidation);

  pendingValidation = $timeout(function(){
    pendingValidation = null;

    // returns promise or value
    return doAsyncValidation();
  }, delay);

  return pendingValidation;
};

delay can be obtained from a parameter via a foo-validator attribute, either with isolate scope binding (scope: {config: "=fooValidator"}), or by directly using $eval-ing the attribute expression against the right scope:

var config = $scope.$eval(attrs.fooValidator);
var delay = config.delay;
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..