Categories
discuss

Android License Test Response – Never works

I’ve been working on an Android App that has already been published to Google Play. For the next update (versionCode = 3) my client wants to include the LVL licensing scheme.

The first thing I did was set up a static test response from the licensing server. I set the test response to LICENSED. After reading this in the documentation:

This License Test Response will be sent to devices using [my email address]
or the Test Accounts listed above for applications you have uploaded to Google Play. >Additionally, this account (but not the Test Accounts) will receive this response for >applications that have not yet been uploaded to Google Play.

I thought, not a problem, since my developer account email is the same as my Google Play account email on my testing devices. So I should receive the test response when debugging the App.

After that, I read through all the other licensing documentation and sample code and integrated it into the App. I used a ServerManagedPolicy with the correct base64 public key and 20 random generated bytes as the salt.

Once everything looked good I uploaded it to the device to test it, but instead of receiving the LICENSED response that I expected, I am always receiving a NOT_LICENSED response. I went back and made sure that:

  1. I was connected to the internet.
  2. I was signed in to my developer account on Google Play.
  3. The LicenseChecker was using the correct public key.
  4. Clearing my Google Play cache.

At first, I thought maybe it had something to do with the caching, so I tried using a StrictPolicy instead. Same response. Since I haven’t purchased the App from the store, I’m under the impression that the licensing server is responding normally instead of sending the static test response. Here are some other things I have tried:

  1. Waiting 24 hours and trying again.
  2. Tried building the App with the android debug key, as well as the current distribution key.
  3. Setting up and using a different test user account on Google Play. I made sure to add this email account to the ‘Test accounts’ section in the developer console.
  4. Uploading the APK to Google Play, but not publishing it.
  5. Incrementing the versionCode from 2 to 3. This is interesting, because instead of responding NOT_LICENSED it returns the ‘application error code’ ERROR_NOT_MARKET_MANAGED.

This leads me to believe that the license server is always responding normally, instead of sending the static test response I set up to my developer account. I have a feeling it may be because the App is already published, but I cannot risk publishing a debug build just to test wether or not it is working.

Has anyone been in this situation before? Any help is greatly appreciated.

Answer

I’ve spent hours and even days with the same problem, it is documented here and elsewhere, that pre-published license test is hit and miss, and more miss than hit from what I discovered.

The only way I’ve found to make it work “more reliably” (but still not totally reliable) is to have a hardware device that is a reset to factory defaults, then set it’s PRIMARY google user as the same one as your dev account that has the app uploaded to test with.

The special AVDs are also not very reliable.

Categories
discuss

Different text for each image in image viewpager

I used viewpager class to display sets of images instead of gallery class as its deprecated and customized it to show the text by using the below code , the problem is the same text showed for all images , what im trying to get is : Different text for each image , which explain it , lets say we have 5 images , it must has 5 different text each one describe its image .

any advice will be appreciated , thanks

The code:

ImagePager

   public class ImagePager extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ImagePagerAdapter adapter = new ImagePagerAdapter(this, imageArra);
    ViewPager myPager = (ViewPager) findViewById(R.id.myimagepager);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);}

private int imageArra[] = { R.drawable.a, R.drawable.b, R.drawable.c,
                              R.drawable.d, R.drawable.e};        }

ImagePagerAdapter

   public class ImagePagerAdapter extends PagerAdapter {

Activity activity;
int imageArray[];

public ImagePagerAdapter(Activity act, int[] imgArra) {
    imageArray = imgArra;
    activity = act;}

public int getCount() {
    return imageArray.length;}

public Object instantiateItem(View collection, int position) {
    LayoutInflater inflater = (LayoutInflater)collection.getContext
                 ().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.custom_pager, null);   

    ImageView im=(ImageView) layout.findViewById(R.id.myimage);             
    im.setImageResource(imageArray[position]);

    TextView txt=(TextView) layout.findViewById(R.id.image_text);
    ((ViewPager) collection).addView(layout, 0);
       return layout;   }

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);
            }

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);
                      }

@Override
public Parcelable saveState() {
    return null;
              }   }

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
   android:layout_width="fill_parent" 
   android:layout_height="fill_parent" 
   android:orientation="vertical">
 <android.support.v4.view.ViewPager 
   android:id="@+id/myimagepager" 
   android:layout_width="match_parent" 
   android:layout_height="match_parent" /> 
</LinearLayout>  

custom_pager.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
   android:layout_width="match_parent" 
   android:layout_height="match_parent" 
   android:orientation="vertical" 
   android:background="#FFDAB9" 
   android:gravity="center_horizontal">
 <ImageView android:id="@+id/myimage" 
   android:layout_width="match_parent" 
   android:layout_height="0dp" 
   android:layout_margin="5dp" 
   android:layout_weight="2" /> 
 <TextView android:id="@+id/image_text" 
    android:layout_width="fill_parent" 
    android:layout_height="0dp" 
    android:textColor="#B22222" 
    android:layout_weight="1" 
    android:text="text to image" />

 </LinearLayout>                       

Answer

You could pass an array of Strings into your adapter that correspond to each image.. ex.

In the activity declare your string array with your list of images..

private int imageArra[] = { R.drawable.a, R.drawable.b, R.drawable.c,
                              R.drawable.d, R.drawable.e};  

private String[] stringArray = new String[] { "Image a", "Image b","Image c","Image d","Image e"}; 

Then when instantiating your adapter..

ImagePagerAdapter adapter = new ImagePagerAdapter(this, imageArra, stringArray );

In your adapter:

int imageArray[];
String[] stringArray;
public ImagePagerAdapter(Activity act, int[] imgArra, String[] stringArra) {
    imageArray = imgArra;
    activity = act;
    stringArray = stringArra;
}

Then assign the text value from the array

TextView txt=(TextView) layout.findViewById(R.id.image_text);
txt.setText(stringArray[position]);
Categories
discuss

Google Maps Marker Clusterer Not Functioning

I have the following code to try to get the MarkerClusterer library to work for my Google Map but for some reason it doesn’t change anything. I have some jinja2 in there for the loop but that is all working properly. Can you see any errors?

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <style type="text/css">
          html { height: 100% }
          body { height: 100%; margin: 0; padding: 0 }
          #map_canvas { height: 100% }
        </style>
        <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyD-pLsocZXv5mYwJsSxMghJncxa6iklFUU&sensor=false"></script>
        <script type="text/javascript" src="/static/js/markerclusterer.js"></script>
        <script type="text/javascript">

    var map;    

    function initialize() {

        var centerlocation = {{centerlocation|json_encode|safe}};   
        var LatLng = centerlocation.replace("(", "").replace(")", "").split(", ")
        var Lat = parseFloat(LatLng[0]);
        var Lng = parseFloat(LatLng[1]);

        var zoomAmt = 10;


      var USA = new google.maps.LatLng(Lat, Lng);
      var mapOptions = {
        zoom: zoomAmt,
        center: USA,
        mapTypeId: google.maps.MapTypeId.TERRAIN
      };
      map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    // Global var
       var infowindow = new google.maps.InfoWindow();

    //markers array
    var markers = [];

    //put all the markers on the map
    {% for location in locations %}

    //need to do the JSON encoding because JavaScript can't have Jinja2 variables
    //I need the safe here because Jinja2 tries to escape the characters otherwise
    var GPSlocation = {{location.GPSlocation|json_encode|safe}};    
    var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
    var Lat = parseFloat(LatLng[0]);
    var Lng = parseFloat(LatLng[1]);    

    var markerLatlng = new google.maps.LatLng(Lat, Lng);
    var title = {{location.title|json_encode|safe}}
    var iwContent = {{location.render_front()|json_encode|safe}}

    var marker = new google.maps.Marker({
            position: markerLatlng,
            title: title,
            map: map
      });

    google.maps.event.addListener(marker, 'click', function () {
      infowindow.setContent(iwContent);
      infowindow.open(map, marker);
      });

    //putting the marker onto the markers array
    markers.push(marker);


    {% endfor %}

    //creating the marker cluster
    var markerCluster = new MarkerClusterer(map, markers);

    }

    </script>

Like I said the map just looks normal after I call MarkerClusterer.

Answer

Looks like you need to remove the {map: map} property from the Marker.

Here is a working example with clustering.

Errors in chrome Javascript console on this page:

  • Uncaught ReferenceError: GOverlay is not defined markerclusterer.js:630
  • Uncaught ReferenceError: markers is not defined

The first implies you are using the wrong version of the markerclusterer script (GOverlay is from the Google Maps API v2)

If I use your code with the correct MarkerClusterer and declaring the markers array, the clusterer works, but you have issues with the association of the InfoWindow contents with the marker (which can be fixed with a createMarker function).

Here is an example that uses a createMarker function to fix the association of the markers to the infowindow. It is based off your code, but there is room for improvement (there is a lot of redundancy in your code).

Categories
discuss

implementing a lazy Supplier in java

What is the right paradigm or utility class (can’t seem to find a preexisting class) to implement a lazy supplier in Java?

I want to have something that handles the compute-once/cache-later behavior and allows me to specify the computation behavior independently. I know this probably has an error but it has the right semantics:

abstract public class LazySupplier<T> implements Supplier<T> 
{
    private volatile T t;
    final private Object lock = new Object();

    final public T get() {
        if (t == null)
        {
            synchronized(lock)
            {
                if (t == null)
                    t = compute();
            }
        }
        return t;
    }
    abstract protected T compute();
}

Answer

This is already implemented in Suppliers.memoize method.

public static <T> Supplier<T> memoize(Supplier<T> delegate)

Returns a supplier which caches the instance retrieved during the first call to get() and returns that value on subsequent calls to get(). See: memoization

The returned supplier is thread-safe. The delegate’s get() method will be invoked at most once. The supplier’s serialized form does not contain the cached value, which will be recalculated when get() is called on the reserialized instance.

If delegate is an instance created by an earlier call to memoize, it is returned directly.

Categories
discuss

Mahout: CSV to vector and running the program

I’m analysing the k-means algorithm with Mahout. I’m going to run some tests, observe performance, and do some statistics with the results I get.

I can’t figure out the way to run my own program within Mahout. However, the command-line interface might be enough.

To run the sample program I do

$ mahout seqdirectory --input uscensus --output uscensus-seq
$ mahout seq2sparse -i uscensus-seq -o uscensus-vec
$ mahout kmeans -i reuters-vec/tfidf-vectors -o uscensus-kmeans-clusters -c uscensus-kmeans-centroids -dm org.apache.mahout.common.distance.CosineDistanceMeasure -x 5 -ow -cl -k 25

The dataset is one large CSV file. Each line is a record. Features are comma separated. The first field is an ID. Because of the input format I can not use seqdirectory right away. I’m trying to implement the answer to this similar question How to perform k-means clustering in mahout with vector data stored as CSV? but I still have 2 Questions:

  1. How do I convert from CSV to SeqFile? I guess I can write my own program using Mahout to make this conversion and then use its output as input for seq2parse. I guess I can use CSVIterator (https://cwiki.apache.org/confluence/display/MAHOUT/File+Format+Integrations). What class should I use to read and write?
  2. How do I build and run my new program? I couldn’t figure it out with the book Mahout in action or with other questions here.

Answer

For getting your data in SequenceFile format, you have a couple of strategies you can take. Both involve writing your own code — i.e., not strictly command-line.

Strategy 1 Use Mahout’s CSVVectorIterator class. You pass it a java.io.Reader and it will read in your CSV file, turn each row into a DenseVector. I’ve never used this, but saw it in the API. Looks straight-forward enough if you’re ok with DenseVectors.

Strategy 2 Write your own parser. This is really easy, since you just split each line on “,” and you have an array you can loop through. For each array of values in each line, you instantiate a vector using something like this:

new DenseVector(<your array here>);

and add it to a List (for example).

Then … once you have a List of Vectors, you can write them to SequenceFiles using something like this (I’m using NamedVectors in below code):

FileSystem fs = null;
SequenceFile.Writer writer;
Configuration conf = new Configuration();

List<NamedVector> vectors = <here's your List of vectors obtained from CSVVectorIterator>;

// Write the data to SequenceFile
try {
    fs = FileSystem.get(conf);

    Path path = new Path(<your path> + <your filename>);
    writer = new SequenceFile.Writer(fs, conf, path, Text.class, VectorWritable.class);

    VectorWritable vec = new VectorWritable();
    for (NamedVector vector : dataVector) {

        vec.set(vector);
        writer.append(new Text(vector.getName()), vec);

    }
    writer.close();

} catch (Exception e) {
    System.out.println("ERROR: "+e);
}

Now you have a directory of “points” in SequenceFile format that you can use for your K-means clustering. You can point the command line Mahout commands at this directory as input.

Anyway, that’s the general idea. There are probably other approaches as well.

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