Categories
discuss

Create properties file using gradle

I would like to create a properties file named “dev.properties” using gradle. Here is my build.gradle code:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.8.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 16
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 16
    }

    def prop = new Properties()
    def propFile = new File("dev.properties");
    propFile.createNewFile();
    prop.store(propFile.newWriter(), null);

    buildTypes {
        release {
            runProguard false
            proguardFile getDefaultProguardFile('proguard-android.txt')
        }
    }
}

The file is created when I right click on the build.gradle and choose run. However it’s not created when I make the entire project. How come?

I’m using android studio 0.4.6 with gradle 1.10.

Answer

It’s creating the file, just not where you expect. Your script is creating the file inside the current working directory, and in Android Studio, that will be in Android Studio’s distribution. There’s a bug filed to make Android Studio consistent with the command line (https://code.google.com/p/android/issues/detail?id=65552) and put the working directory at the project root (well, that’s assuming your working directory is set there when you issue Gradle commands), but the fix is actually difficult, and the real answer is you should probably never implicitly rely on the working directory, so that you can make your builds as bulletproof as possible.

If you do something like this:

def propFile = new File("${project.rootDir}/dev.properties")

it will put the file in your project’s root directory. There’s also project.projectDir, which will be your module directory; see http://www.gradle.org/docs/current/dsl/org.gradle.api.Project.html for more details on what’s available to you.

As a side note, you should keep in mind this will run every time the build file is evaluated (because the android block is executed every time the build script is run), which could be more often than you want. It’s more than just build time; it’s project import time as well, and any time Android Studio decides to evaluate the build file, which happens when you open the project and also when you click the Sync Project with Gradle Files button.

Additionally, you should consider at what phase of the build process you want it to happen: is it script evaluation time, or do you want it to run after Gradle has done its analysis and is ready to actually start building things? You can read http://www.gradle.org/docs/current/userguide/build_lifecycle.html to find out more about that.

Sorry, I know it’s a lot of information to drop on you when you’re just trying to get something going, but those concepts will help you out pretty soon down the road.

Categories
discuss

Android animate view outside fragment is getting clipped

I have a view in a fragment. This fragment is within a FrameLayout. I want to animate this view moving outside the fragment borders. However, the view always get clipped when crossing the border. I have tried by setting android:clipChildren="false" and android:clipToPadding="false" to everything, but I can’t get it to work.

Is this even possible to do?

Answer

I had the similar problem with fragments and put android:clipChildren="false" and android:clipToPadding="false" on all the levels in my hierarchy, but it was still not working. The trick that worked for me was to add this override in my fragment code:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ViewGroup vg = (ViewGroup) view;
    vg.setClipChildren(false);
    vg.setClipToPadding(false);
}

Hope this helps…

P.S. the credit should go to this answer

Categories
discuss

Handlebars specific – escape both single and double quotes when passing Handlebars expression

HTML and Handlebars:

onclick='shareItem("{{name}}")'> 

Does not successfully pass a safely escaped name when it has double quotes in it.

onclick="shareItem('{{name}}')"> 

Does not successfully pass a safely escaped name when it has single quotes in it.

I need to handle both eventualities- and even in the same string.

It feels sloppy to have to define a JS variable and pass it to a backslash adder.

Is there a cleaner way to do this with Handlebars or Moustache?

Answer

You need to register a inline helper that manipulates the context. In your case, you need to escape a single or double quote.

Handlebars.registerHelper('escape', function(variable) {
  return variable.replace(/(['"])/g, '\$1');
});

By registering such helper, you can use it with a variable to achieve what you want.

{{ escape name }} # expects to escape any ' or "

I wrote a simple example to demonstrate this on jsfiddle: http://jsfiddle.net/VLy4L/

Categories
discuss

How Javascript is getting executed in browser by Javascript Engine?

Question not for solution, Question to understand the system better

Experts! I know whenever you feed javascript code into javascript engine, It will execute by javascript engine immediately. Since, I haven’t seen Engine’s source code, I have few of questions as follows,

Let us assume I am loading couple of files from remote server namely FILE_1.js and FILE_2.js. And the code in FILE_2.js is requiring some of the code in FILE_1.js. So I have included files as follows,

<script type="text/javascript" src="FILE_1.js" ></script>
<script type="text/javascript" src="FILE_2.js" ></script>

So hopefully, I have done what Javascript Engine requires. Here unfortunately I have written 5000KB of code in FILE_1.js, and however I have 5KB of code in FILE_2.js. Since server is multi-threaded definitely FILE_2.js will be loaded into my browser before FILE_1.js completed.

How javascript engine handle this?

And If moved the code from FILE_2.js to inline-script tag as follows, what are actions taken by javascript engine to manage this dependency?

<script type="text/javascript" src="FILE_1.js" ></script>
<script type="text/javascript" >
// Dependent code goes here
</script>

Note: I am not expecting single word answer Single Threaded. I just want to know deep who is manage issuing request either browser or javascript engine or common guy? if the request/response is handled by common guy, then how javascript engine aware about this?

Answer

When I post an answer about the behavior of code, I always like to go to two places:

  1. The specification
  2. The implementation

The specification:

The DOM API explicitly specifies scripts must be executed in order:

If the element has a src attribute, does not have an async attribute, and does not have the “force-async” flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

From 4.1 Scripting. Please check the list of exceptions to this rule before – having the defer or async attribute. This is specified well in 4.12.1.15.

This makes sense, imagine:

 //FILE_1.js
     var trololo = "Unicorn";
     ....
     // 1 million lines later
     trololo = "unicorn";
     var message = "Hello World";
//FILE_2.js
     alert(message); // if file 1 doesn't execute first, this throws a reference error.

It is generally better to use a module loader (that will defer script insertion and execution, and will manage dependencies correctly for you).

At the moment, the best approach is to use something like Browserify or RequireJS . In the future, we’ll be able to use ECMAScript 6 modules.

The implementation:

Well, you mentioned it and I couldn’t resist. So, if we check the Chromium blink source (still similar in WebKit):

bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition, 
                                    LegacyTypeSupport supportLegacyTypes)
    {
    .....
    } else if (client->hasSourceAttribute() && // has src attribute
              !client->asyncAttributeValue() &&// and no `async` or `defer`
              !m_forceAsync                    // and it was not otherwise forced                                   
              ) { // - woah, this is just like the spec
   m_willExecuteInOrder = true; // tell it to execute in order
   contextDocument->scriptRunner()->queueScriptForExecution(this, 
                                                            m_resource,
                                      ScriptRunner::IN_ORDER_EXECUTION);

Great, so we can see in the source code that it adds them in order parsed – just like the specification says.

Let’s see how a script runner does:

void ScriptRunner::queueScriptForExecution(ScriptLoader* scriptLoader,
                                          ResourcePtr<ScriptResource> resource,
                                          ExecutionType executionType){
     .....
     // Adds it in the order of execution, as we can see, this just 
     // adds it to a queue
     case IN_ORDER_EXECUTION:
        m_scriptsToExecuteInOrder.append(PendingScript(element, resource.get()));
        break;
     }

And, using a timer, it fires them one by one when ready (or immediately, if nothing is pending):

 void ScriptRunner::timerFired(Timer<ScriptRunner>* timer)
 {
 ...
    scripts.swap(m_scriptsToExecuteSoon);
    for (size_t i = 0; i < size; ++i) {
    ....
        //fire!
        toScriptLoaderIfPossible(element.get())->execute(resource);
        m_document->decrementLoadEventDelayCount();
    }
Categories
discuss

Is it possible to use React without rendering HTML?

I was wondering if it’s possible to use React for doing logic and sending data back to a javascript function, without rendering any html. The component I’m thinking of is something that you pass some data to, and it’ll send data back to a javascript function outside of react. I know that can be done, and I’ve done that part myself, but I’m not sure how you would do this without rendering html as it is required. Is this even a practical use case for react?

Answer

As of React >= 16.2 it is possible to use any of these versions:

render() { 
   return false; 
}

render() { 
   return null; 
}

render() { 
   return []; 
}

render() { 
   return <React.Fragment></React.Fragment>; 
}

render() { 
   return <></>; 
}

Returning undefined does not work.


The component I’m thinking of is something that you pass some data to, and it’ll send data back to a javascript function outside of react.

Why would you want to create a component for that? Most of the time a regular js function in an existing component can be enough.

One usecase is for exemple to setup a side-effect when component is mounted and tear it down when it unmounts. For exemple if you have a ReactNative mobile app with portrait orientation, you could imagine a <Landscape/> component, that, when mounted, would allow temporarily to display the app in landscape orientation, and when unmounted, orientation would be reset to app default. You can surely manage this orientation change on an existing component, but creating a dedicated component might be more handy and reusable.

Note that React can also run on the server side so I guess it is possible to use it in such a way that it doesn’t involve any DOM modifications (but maybe only the virtual DOM computation).

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