Categories
discuss

How to center ImageView in a toolbar?

Been trying to center a logo inside my toolbar. When i navigate to the next activity, the “up affordance” icon is present, and it will push my logo slightly to the right. How can I keep my logo at the center of the toolbar, without removing the up affordance icon?

This is my toolbar tag

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primaryColor"
android:paddingTop="@dimen/app_bar_top_padding"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
app:theme="@style/CustomToolBarTheme">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_android_logo"
    android:layout_gravity="center"
    android:paddingBottom="3dp"/>
 </android.support.v7.widget.Toolbar>

Answer

In javadoc, it says:

One or more custom views. The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view’s Toolbar.LayoutParams indicates a Gravity value of CENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.

It means you cannot do it unless you create a custom toolbar or remove the icon.

Categories
discuss

Problems using JSONParser with GWT

I have a simple GWT app that needs to get some JSON data from another server. I’ve followed a couple of tutorials to get to this point. When I try to compile it, I get errors

[ERROR] Line 44: No source code is available for type com.google.gwt.json.client.JSONValue; did you forget to inherit a required module? [ERROR] Line 44: No source code is available for type com.google.gwt.json.client.JSONParser; did you forget to inherit a required module? [ERROR] Line 46: No source code is available for type com.google.gwt.json.client.JSONArray; did you forget to inherit a required module? [ERROR] Line 49: No source code is available for type com.google.gwt.json.client.JSONObject; did you forget to inherit a required module?

I know I had to add

<inherits name="com.google.gwt.http.HTTP" />

to my .gwt.xml file, but couldn’t figure out what to add to get it to recognize the JSON stuff. What am I missing, please?

Relevant code:

  private SearchResult[] parseResponse(String jsonResponse) {
        ArrayList<SearchResult> retArray = new ArrayList<SearchResult>();

        JSONValue jval = JSONParser.parseStrict(jsonResponse);

        JSONArray resultArray = jval.isArray();

        for(int i=0; i<resultArray.size(); i++) {
            JSONObject resultObj =  resultArray.get(i).isObject();
            String title = resultObj.get("title").isString().stringValue();
            JSONArray roleArray = resultObj.get("roles").isArray();
            String roleNames = new String();
            for(int j=0; j< roleArray.size(); j++) {
                if(roleArray.get(j).isNumber().doubleValue() == 1.0) {
                    // this role is present
                    String currRole = Constants.getRoleNameForNum(j);
                    roleNames += currRole;
                }   
            }
            SearchResult sr = new SearchResult(title, roleNames);
            retArray.add(sr);
        }

        return retArray.toArray(new SearchResult[0]);
    }

    private void doSearch() {

        clearTable();

        final String searchTerms = searchTextBox.getText().toLowerCase().trim();
        searchTextBox.setFocus(true);
        final int roleNum = roleChooserBox.getSelectedIndex();
        final String roleName = roleChooserBox.getItemText(roleNum);
        String url = JSON_URL + "?" + ROLE_TXT + roleNum + "&" + QUERY_TXT + "'" + searchTerms + "'";
        url = URL.encode(url);

        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
        try {
            Request request = builder.sendRequest(null, new RequestCallback() {

                @Override
                public void onError(Request request, Throwable exception) {
                    displayError("Couldnt' retrieve JSON");

                }
                @Override
                public void onResponseReceived(Request request, Response response) {


                    if (200 == response.getStatusCode()) {
                        SearchResult[] results = parseResponse(response.getText());
                        updateTable(results, roleName);
                    } else {
                        displayError("Couldn't retrieve JSON (" + response.getStatusText()
                                + ")");
                    }
                }
            });
        } catch (RequestException e) {
            displayError("Couldn't retrieve JSON");
        }
            `

Answer

After further trial and error, adding

<inherits name="com.google.gwt.json.JSON" />

to my .gwt.xml file did the trick. I’m disappointed that I couldn’t find any information in the documentation explaining that. It would have saved a lot of time.

Categories
discuss

Camera.PreviewCallback equivalent in Camera2 API

Is there any equivalent for Camera.PreviewCallback in Camera2 from API 21,better than mapping to a SurfaceTexture and pulling a Bitmap ? I need to be able to pull preview data off of the camera as YUV?

Answer

You can start from the Camera2Basic sample code from Google.

You need to add the surface of the ImageReader as a target to the preview capture request:

//set up a CaptureRequest.Builder with the output Surface
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
mPreviewRequestBuilder.addTarget(surface);
mPreviewRequestBuilder.addTarget(mImageReader.getSurface());

After that, you can retrieve the image in the ImageReader.OnImageAvailableListener:

private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
    @Override
    public void onImageAvailable(ImageReader reader) {
        Image image = null;
        try {
            image = reader.acquireLatestImage();
            if (image != null) {
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                Bitmap bitmap = fromByteBuffer(buffer);
                image.close();
            }
        } catch (Exception e) {
            Log.w(LOG_TAG, e.getMessage());
        }
    }
};

To get a Bitmap from the ByteBuffer:

Bitmap fromByteBuffer(ByteBuffer buffer) {
    byte[] bytes = new byte[buffer.capacity()];
    buffer.get(bytes, 0, bytes.length);
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
Categories
discuss

Rendering a Base64 PNG with Express

My Node.js server has something that looks like the following:

app.get("/api/id/:w", function(req, res) {
    var data = getIcon(req.params.w);
});

Here, data is a string containing a Base64 representation of a PNG image. Is there any way I can send this to a client accessing the route encoded and displayed as an image (e.g. so the URL can be used in an img tag)?

Answer

Yes you can encode your base64 string and return it to the client as an image:

server.get("/api/id/:w", function(req, res) {
    var data = getIcon(req.params.w);
    var img = Buffer.from(data, 'base64');

   res.writeHead(200, {
     'Content-Type': 'image/png',
     'Content-Length': img.length
   });
   res.end(img); 
});
Categories
discuss

Android Unit Tests – no such property: bootClasspath

I’m trying to execute a simple test case for Android following just announced unit testing support – http://tools.android.com/tech-docs/unit-testing-support

After carefully following the walkthrough I’m trying to run ./gradlew test. I’m getting this error:

Execution failed for task ':app:compileDebugGroovy'.
> No such property: bootClasspath for class: com.android.build.gradle.AppPlugin

while using com.android.tools.build:gradle:1.1.0-rc1.

Anyone else got stuck on that?

Answer

The problem is that Groovy Android Gradle plugin (to have Groovy working on Android) isn’t simply working with Android plugin in version 1.1.0-rcX.

Here’s a very interesting piece of code directly from groovyx.grooid.GroovyAndroidPlugin, version 0.3.5 (current latest, here’s the source)

    def getRuntimeJars(Project project, plugin) {
    int index
    switch (getAndroidPluginVersion(project)) {
        case ~/0.9..*/:
            index = 0
            break
        case ~/0.10..*/:
        case ~/0.11..*/:
        case ~/0.12..*/:
        case ~/0.13..*/:
        case ~/0.14..*/:
        case ~/1.0..*/:
            index = 1
            break
        default:
            index = RUNTIMEJARS_COMPAT.size()-1
    }
    def fun = RUNTIMEJARS_COMPAT[index]
    fun(plugin)
}

and definition of RUNTIMEJARS_COMPAT:

private static List RUNTIMEJARS_COMPAT = [
        { it.runtimeJars },
        { it.bootClasspath }
]

So that API must have changed in Android Gradle between 0.9.x and 0.10.0 (yeah, I know – those Google devs change everything there :[ ). So let’s take a look at that problem making class in Android Plugin version 1.0.0:

> javap -cp [path to proper jar] com.android.build.gradle.AppPlugin:

public class com.android.build.gradle.AppPlugin extends com.android.build.gradle.BasePlugin implements org.gradle.api.Plugin<org.gradle.api.Project> {
...
public java.util.List super$2$getBootClasspath();
...

Yup! There’s the method we need (coming from parent com.android.build.gradle.BasePlugin class). Now there’s nothing like that in version 1.1.0-rc3. What’s more, the API of com.android.build.gradle.AppPlugin is completely changed, so it’s not a matter of simple if(version) to fix that.

I guess there’s no chance to have Groovy Android Gradle plugin working with Unit Tests (since 1.1.0) until authors update the plugin.

Let’s wait then.

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