Android update array of bitmaps / Queue - android

I need some advice how to implement this situation in my application.
I have array of bitmpaps, which I'm using to store different states of my Canvas, so I can use them in the future. Here is the code which I'm using :
private Bitmap[] temp;
// on user click happens this ->
if(index<5){
temp[index] = Bitmap.createBitmap(mBitmap);
index++;
}
So basically I want to save only the last 5 bitmaps depending on user's actions. The things which I want to learn is how can I update my array so I can always have the last 5 bitmaps.
Here is what I mean :
Bitmaps [1,2,3,4,5] -> after user clicks I want to delete the first bitmap, re-order the array and save the new one as the last..so my array should look like this : Bitmaps[2,3,4,5,6];
Any suggestions / advices which is the best way to do that?
Thanks in advance!

I just wrote this...
Use this code to initialise:
Cacher cach = new Cacher(5);
//when you want to add a bitmap
cach.add(yourBitmap);
//get the i'th bitmap using
cach.get(yourIndex);
Remember you can re implement the function get to return the ith "old" Bitmap
public class Cacher {
public Cacher(int max) {
this.max = max;
temp = new Bitmap[max];
time = new long[max];
for(int i=0;i<max;i++)
time[i] = -1;
}
private Bitmap[] temp;
private long[] time;
private int max = 5;
public void add(Bitmap mBitmap) {
int index = getIndexForNew();
temp[index] = Bitmap.createBitmap(mBitmap);
}
public Bitmap get(int i) {
if(time[i] == -1)
return null;
else
return temp[i];
}
private int getIndexForNew() {
int minimum = 0;
long value = time[minimum];
for(int i=0;i<max;i++) {
if(time[i]==-1)
return i;
else {
if(time[i]<value) {
minimum = i;
value = time[minimum];
}
}
return minimum;
}
}

Related

Java, what is best way to compare two lists?

I have two lists of Default and Chrome browsers history.
I want to merge these two lists into one list.
I need to update item if I find it duplicate (is common between two lists).
So, my "BrowserRecord" class is like this:
public class BrowserRecord {
private long id;
private int bookmark;
private long created;
private long date;
private String title;
private String url;
private long visits;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BrowserRecord record = (BrowserRecord) o;
return url.equals(record.url);
}
#Override
public int hashCode() {
return url.hashCode();
}
// other getter setter methods
...
}
and finally, I have a method that gets browsers histories and does merging:
public List<BrowserRecord> getHistory() {
List<BrowserRecord> browserList = new ArrayList<BrowserRecord>();
// get history of default and chrome browsers
List<BrowserRecord> defaultList = getDefaultBrowserHistory();
List<BrowserRecord> chromeList = getChromeBrowserHistory();
Log.e(TAG, "=> size of Default browser:" + defaultList.size());
Log.e(TAG, "=> size of Chrome browser:" + chromeList.size());
// compare list A with B, update A item if equal item found in B and push it to tempList
for(int i=0; i<chromeList.size(); i++) {
BrowserRecord chromeBrowser = chromeList.get(i);
for(int j=0; j<defaultList.size(); j++) {
BrowserRecord defaultBrowser = defaultList.get(j);
if(chromeBrowser.equals(defaultBrowser)) {
if(chromeBrowser.getBookmark() != defaultBrowser.getBookmark())
chromeBrowser.setBookmark(1);
chromeBrowser.setVisits(chromeBrowser.getVisits() + defaultBrowser.getVisits());
}
}
browserList.add(chromeBrowser);
}
// compare list B with A, jump if equal item found in A, push to tempList if item not found
for(int i=0; i<defaultList.size(); i++) {
BrowserRecord defaultBrowser = defaultList.get(i);
boolean found = false;
for(int j=0; j<chromeList.size(); j++) {
BrowserRecord chromeBrowser = chromeList.get(j);
if(defaultBrowser.equals(chromeBrowser)) {
found = true;
break;
}
}
if(!found)
browserList.add(defaultBrowser);
}
Log.e(TAG, "=> size of final browser:" + browserList.size());
return browserList;
}
I have tested this method and is working fine. Since my history records on mobile device after 3 years didn't exceed more than 200 records on one list and 150 for others, I assume something similar is happening for other users. But I'm sure is not optimum way.
What do you recommend?
any suggestion would be appreciated. Thanks.
Not sure I understand correctly, but it seems like what you're trying to do is, given both lists, create a final list which will contain all of the elements from both lists, removing any duplicates.
If this is the case, then take a look at Java's TreeSet class. If you iterate over all of the elements from both your lists and insert them into a TreeSet, you will basically get the result you're looking for. You can then use an Iterator to create an ArrayList containing all of the non-duplicate items from both your lists. As a side-effect of using a TreeSet, they will ordered (you can also use either a HashSet if you don't care about the order or a LinkedHashSet if you want to preserve the order of insertion).

Handling images in HTML In TextView in a different way

I'm trying to show Html in TextView. And all works fine, but I want to display images in TextView in different way.
For example, I want each image to be in the container, which can be dragged and dropped.
Does anyone knows any way to implement this?
Thanks!
Upd: I can't use WebView, because I will show about 10-20 separate views on same Activity at once. And I don't think it will help me to implement this.
This is how I solved the problem.
The main idea:
Go through all spans from Html.fromHtml(section.text) and search for ImageSpan. Once it is found set all previous spans as text for one TextView, create ImageView for image, continue searching.
Code:
new AsyncTask<String, Integer, List<Object>>() {
#Override
protected List<Object> doInBackground(String... params) {
List<Object> res = new ArrayList<Object>();
Spanned in = Html.fromHtml(section.text);
Object[] spans = in.getSpans(0, Integer.MAX_VALUE, Object.class); // get all spans
int lastImageSpanPosition = 0; // it's end position of image span
for (int i = 0; i < spans.length; i++) { // itarete searching ImageSpan
Object span = spans[i];
if (span instanceof ImageSpan) {
int spanStart = in.getSpanStart(span); // If you;ve found one
if (lastImageSpanPosition == spanStart)
continue; // check if image is first span (avoid creation of empty spans).
res.add(new SpannableStringBuilder(in.subSequence(lastImageSpanPosition, spanStart))); // add all previous spans as a single Spannable object
ImageSpan imageSpan = (ImageSpan) span;
String imageUrl = imageSpan.getSource();
if (!imageUrl.startsWith("http"))
imageUrl = "http:" + imageUrl;
res.add(new ImageSpan(null, imageUrl)); // add separate span for image
lastImageSpanPosition = in.getSpanEnd(span);
}
if (i < spans.length - 1 && !containsImageSpan(spans, i + 1)) { // to not lose text in the end
res.add(new SpannableStringBuilder(in.subSequence(lastImageSpanPosition, in.getSpanEnd(spans[spans.length - 1]))));
break;
}
}
return res;
}
#Override
protected void onPostExecute(List<Object> objects) {
for (Object object : objects) {
View v = null;
if (object instanceof ImageSpan) { // create separate views for each span
NetworkImageView networkImageView = new NetworkImageView(getContext());
networkImageView.setImageUrl(((ImageSpan) object).getSource(), App.get().getImageLoader());
v = networkImageView;
} else {
TextView textView = new TextView(getContext());
textView.setText((CharSequence) object);
v = textView;
}
holder.sectionTextViewsContainer.addView(v);
}
}
}.execute(section.text);
EDIT: added containsImageSpan method
private boolean containsImageSpan(Object[] spans, int index) {
for (int i = index; i < spans.length; i++) {
if (spans[i] instanceof ImageSpan) {
return true;
}
}
return false;
}
According to the documentation of HTML class, I'm not sure you can achieve what you want. Take a look at
http://developer.android.com/reference/android/text/Html.html
If you really want to use HTML I recommand you to use a webview. Otherwise, you can use native drag and drop. Check the official training: http://developer.android.com/guide/topics/ui/drag-drop.html

Indexing Android

My problem is I have around 1000+ records in an Android App
string field1;
string field2;
string field3;
string field4;
//...
I want to search in this set of records and get the best results on two fields (field1 and field2).
Currently I read each record and compare() (string compare) with the text i want to search so that takes a long time.
What is the best method to perform search?
Store each records in SQLite DB and do "select query where like"
Hash-Mapped
? any other suggestions?
Or may be create an Index of the records and do search.
If you want to search for not exact matches, I would try to make an ArrayList of MyAppRecord where
public class MyAppRecord {
private String record;
private int deviance;
}
and get for each record the deviance of the String you want to find with:
public static int getLevenshteinDistance (String s, String t) {
if (s == null || t == null) {
throw new IllegalArgumentException("Strings must not be null");
}
int n = s.length(); // length of s
int m = t.length(); // length of t
if (n == 0) {
return m;
} else if (m == 0) {
return n;
}
int p[] = new int[n+1]; //'previous' cost array, horizontally
int d[] = new int[n+1]; // cost array, horizontally
int _d[]; //placeholder to assist in swapping p and d
// indexes into strings s and t
int i; // iterates through s
int j; // iterates through t
char t_j; // jth character of t
int cost; // cost
for (i = 0; i<=n; i++) {
p[i] = i;
}
for (j = 1; j<=m; j++) {
t_j = t.charAt(j-1);
d[0] = j;
for (i=1; i<=n; i++) {
cost = s.charAt(i-1)==t_j ? 0 : 1;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+cost);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
return p[n];
}
}
save it to your MyAppRecord-object and finally sort your ArrayList by the deviance of its MyAppRecord-objects.
Note that this could take some time, depending on your set of records. And NOTE that there is no way of telling wether dogA or dogB is on a certain position in your list by searching for dog.
Read up on the Levensthein distance to get a feeling on how it works. You may get the idea of sorting out strings that are possibly to long/short to get a distance that is okay for a threshold you may have.
It is also possible to copy "good enough" results to a different ArrayList.

Array access producing unwanted result

I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object

Array Being Overwritten with Last Index in Loop

I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.

Categories

Resources