Get repeated Entries for Some Items in DataBase! - android

I am working on an android application. In which i have slideShows. I am parsing these through an xml and after parsing them, saving in the SQLite DB. Majority of the slideshows are saved properly but, sometimes this happens that the slides are saved two times that is, every slide in the slideShow is saved two times obviously with different PK but same content. which should be avoided.
Partial code is here, where i am getting the slides and trying to store them in DB.
ArrayList<SlideShowItem> slideItems = null;
slideItems=Utils.database.getSlideItemOfUrl(Constants.StoriesTable,tempSlideShow.getFullStoryUrl().substring(0, index - 1), type);
if (slideItems == null) {
Log.d("store in DB: ", " when SlideItems == null ");
Log.d("SlideShow Title: ", tempSlideShow.getTitle());
Log.d("SlideShow pub Date: ", tempSlideShow.getPubDate());
slideItems = tempSlideShow.getSlideShow();
Utils.database.storeSlideItem(Constants.StoriesTable, myUrl,slideItems, type);
Utils.topStorySlidesArrayList = slideItems;
slideItems = null ;
} else {
Log.d("SlideShow Title: ", tempSlideShow.getTitle());
Utils.topStorySlidesArrayList = slideItems;
slideItems = null ;
}
and code of function storeSlideItem in DataBase is:
public synchronized void storeSlideItem(String tableName, String, url,ArrayList<SlideShowItem> list, String type) {
System.out.println("size of the Array list: " + list.size());
String newType = null;
if (type == null) {
newType = "List";
}else{
newType = type;
}
ArrayList<SlideShowItem> newList = new ArrayList<SlideShowItem>();
//newList = null;
Iterator<SlideShowItem> iterator = list.iterator();
while (iterator.hasNext())
{
SlideShowItem sSItem = iterator.next();
if(!newList.contains(sSItem))
{
newList.add(sSItem);
}
}
try {
for (int i = 0; i < newList.size(); i++) {
SlideShowItem item = newList.get(i);
String itemUrl = url + i;// Unique URL for the DB;
String imgString = null;
Log.e("Loop Counter", " time " + i);
Drawable drawable = item.getImage();
if (item.getBody() != null) {
item.setBody(item.getBody().replace('\'', '`'));
// replace as it create syntax error for storing data
}
if (item.getSubTitle() != null) {
item.setSubTitle(item.getSubTitle().replace('\'', '`'));
}
if (drawable != null) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
imgString = Base64.encodeBytes(b);
}
if (isOpen()) {
myDB.execSQL("INSERT INTO " + tableName + "(" + column[1] + "," + column[2] + "," + column[3] + "," + column[4] + "," + column[6]
+ "," + column[7] + ",type) VALUES('" + itemUrl + "','" + item.getSubTitle() + "','" + item.getBody() + "','"
+ item.getImagePath() + "','" + item.getIndex() + "','" + imgString + "','" + newType + "Slide')");
if (item.getBody() != null) {
item.setBody(item.getBody().replace('`', '\''));// " ' "
// replace as it create syntax error for storing data
}
if (item.getSubTitle() != null) {
item.setSubTitle(item.getSubTitle().replace('`', '\''));
}
if (tableName.equals(Constants.StoriesTable)) {
item.setItemId(getItemID(tableName, itemUrl));
Utils.hashListStoriesIds.put(itemUrl, item.getItemId());
if (imgString != null) {
Utils.hashListImages.put(item.getItemId(), new Boolean(true));
} else {
Utils.hashListImages.put(item.getItemId(), new Boolean(false));
}
}
}
}
} catch (Exception e) {
Log.e("Error", "Exception: storeSlideItem type " + e.toString());
} finally {
closeConnection();
}
}
Please tell me anything that can get me out of this irritating problem. Any help is appreciated.
in DB for duplication of slides the view is somewhat like:
1 abc USA 111
2 abc USA 111
and so on this was for one slide of a slideShow. if i have 3 slides in a slideshow, i'll get 6 entries in DB each slide being saved for two times.

Use HashSet instead of ArrayList

Related

For loop runs twice the result?

I am new to Android. I am creating a native MobilePOS Android application for printng by using Bluetooth. This is my code:
private void showandadd() {
/*String num="";
num=num+String.valueOf(number);*/
String string1="";
String string2="";
String string3="";
if(num==""){
Toast.makeText(this,"Wrong input!! try again", Toast.LENGTH_LONG).show();
}
if(flag==1) {
getItem(directadd);
if(blankflag!=1) {
int updatedPrice = Integer.parseInt(this.price);
int data = Integer.parseInt(this.num);
if(data==0){
Toast.makeText(this,"Wrong input!! insert different quantity number", Toast.LENGTH_LONG).show();
}else {
int d = updatedPrice * data;
this.price = d + "";
// String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add(num);
amount.add(price);
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}
}
num = "";
directadd = "";
flag = 0;
blankflag = 0;
}else {
getItem(directadd);
if(blankflag!=1) {
//String str = itemName + " \t" + num + " No" + " \t" + "Rs " + price;
printdetailsnew.add(itemName);
quantitynum.add("1");
amount.add(price);
num = "";
}
directadd="";
blankflag=0;
}
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
}
There are 3 strings assigned to result.
I am getting result twice when I am press second item.
when I am select first item getting "Itemname Quantity ampount" format like
Tea 1qty 10rs...when I enter second item output will came first item+first item+second item show like this:
Tea 1qty 10rs
Tea 1qty 10rs
Coffee 1qty 12rs
I want to get result
Tea 1qty 10rs
Coffee 1qty 12rs
like this...please any one can help me
A simple example would be to use one label and append to it each time you add a new item.
Instead of this:
for(int i=0;i<printdetailsnew.size();i++){
string1=string1+ printdetailsnew.get(i)+"\t"+"\n";
string2=string2 +"No."+ quantitynum.get(i)+"\t"+"\n";
string3= string3 + amount.get(i)+"\n";
result = printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"+result);
}
this.selection.setText(string1);
this.selection2.setText(string2);
this.selection3.setText(string3);
num="";
Change it to this:
str = this.selection.getText().toString();
str += printdetailsnew.get(i)+"\t" + "No."+ quantitynum.get(i)+"\t"+ amount.get(i)+"\n";
this.selection.setText(str);
num="";

How to get the results from multiple servers in a function in Android

I'm installing Hybrid Ranking algorithm for Linked Data Extraction & Context on Android. Documents you can search Google for the keywords above.
And now I'm installing semantic similarity between two uri1 and uri2.
Input: two DBpedia URIs
Output: a value representing their similarity
private float similarity(String uri1, String uri2) {
float wikipedia = wikiS(uri1, uri2);
float abtract = abtractS(uri1, uri2);
float google = engineS(uri1, uri2, google);
float yahoo = engineS(uri1, uri2, yahoo);
float bing = engineS(uri1, uri2, bing);
float dilicious = engineS(uri1, uri2, dilicicous);
return wikipedia + abtract + google + yahoo + bing + dilicious;
}
And with each child function, I have to query data using SPARQL dbpedia, google, yahoo, bing, dilicious using provided API. The results obtained will be calculated to the parser and returns the corresponding float value.
Example for abtractS(uri1, uri2) below:
private float abstractS(String uri1, String uri2, final float wikiS){
String url = createUrlAbstractS(uri1, uri2);
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
float abtractS = 0.0f;
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray data = jsonObject.getJSONObject("results").getJSONArray("bindings");
if(data.length() == 0){
showLogAndToast("No result");
}else{
JSONObject element = data.getJSONObject(0);
String label1 = element.getJSONObject("label1").getString("value");
String abtract1 = element.getJSONObject("abtract1").getString("value");
String label2 = element.getJSONObject("label2").getString("value");
String abtract2 = element.getJSONObject("abtract2").getString("value");
abtractS = calWordContained(label1, abtract2) + calWordContained(label2, abtract1) + wikiS;
//TODO: RESULT ABTRACTS HERE. How next?
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
return 0.0f;//HERE: no results
}
private float calWordContained(String label, String abtract){
if(label.length() == 0 || abtract.length() == 0){
return 0.0f;
}
List<String> words = Arrays.asList(label.split(" "));
int count = 0;
float length = words.size();
for(int i = 0; i < length; i++){
if(abtract.toLowerCase().contains(words.get(i).toLowerCase())){
count++;
}
}
return (count/length);
}
public String createUrlAbstractS(String uri1, String uri2){
private String BASE_URL_DBPEDIA = "http://dbpedia.org/sparql?default-graph-uri=&query=";
String query = createQueryAbstractS(uri1, uri2);
String url = "";
try {
url = Config.BASE_URL_DBPEDIA + URLEncoder.encode(query, "UTF-8") + Config.RESULT_JSON_TYPE;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
private String createQueryAbstractS(String uri1, String uri2){
String query = Config.PREFIX_DBPEDIA + " \n" +
"prefix dbpedia-owl: <http://dbpedia.org/ontology/>\n" +
"\n" +
"\n" +
"select ?label1, ?label2, ?abtract1, ?abtract2 where\n" +
"{\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri1 + "> rdfs:label ?label1 ;\n" +
" dbpedia-owl:abstract ?abtract1 .\n" +
" FILTER langMatches(lang(?abtract1),'en') . \n" +
" FILTER langMatches(lang(?label1),'en') .\n" +
" }\n" +
" }\n" +
"\n" +
"\n" +
" {\n" +
" select *\n" +
" where{\n" +
" <" + uri2 + "> rdfs:label ?label2 ;\n" +
" dbpedia-owl:abstract ?abtract2 .\n" +
" FILTER langMatches(lang(?label2),'en') . \n" +
" FILTER langMatches(lang(?abtract2),'en') .\n" +
" }\n" +
" }\n" +
"}";
return query;
}
but how to do this on, I could not get the results I wanted in the similarity function (uri1, uri2). Therefore it will affect the results in different functions.
So I'm asking is: how can I get all the results of the function Wikis, abtractS, engine (google), engine (bing), engine (yahoo), engine (dilicious) in a simple way Best. I currently do on Android and data load times is very important.
Thank you very much!

How to Extract Name,Phone Number and Email Address From Vision OCR result text in Android?

Here is my sample code where i want to get details...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PHOTO_REQUEST && resultCode == RESULT_OK) {
launchMediaScanIntent();
try {
Bitmap bitmap = decodeBitmapUri(this, imageUri);
if (detector.isOperational() && bitmap != null) {
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> textBlocks = detector.detect(frame);
String blocks = "";
String lines = "";
String words = "";
for (int index = 0; index < textBlocks.size(); index++) {
//extract scanned text blocks here
TextBlock tBlock = textBlocks.valueAt(index);
blocks = blocks + tBlock.getValue() + "\n" + "\n";
for (Text line : tBlock.getComponents()) {
//extract scanned text lines here
lines = lines + line.getValue() + "\n";
for (Text element : line.getComponents()) {
//extract scanned text words here
words = words + element.getValue() + ", ";
}
}
}
if (textBlocks.size() == 0) {
scanResults.setText("Scan Failed: Found nothing to scan");
} else {
scanResults.setText(scanResults.getText() + "Blocks: " + "\n");
scanResults.setText(scanResults.getText() + blocks + "\n");
scanResults.setText(scanResults.getText() + "---------" + "\n");
scanResults.setText(scanResults.getText() + "Lines: " + "\n");
scanResults.setText(scanResults.getText() + lines + "\n");
scanResults.setText(scanResults.getText() + "---------" + "\n");
scanResults.setText(scanResults.getText() + "Words: " + "\n");
scanResults.setText(scanResults.getText() + words + "\n");
scanResults.setText(scanResults.getText() + "---------" + "\n");
}
} else {
scanResults.setText("Could not set up the detector!");
}
} catch (Exception e) {
Toast.makeText(this, "Failed to load Image", Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, e.toString());
}
}
}
You have nice libraries to parse link (emails,websites etc) like org.nibor.autolink
Concerning numbers you can have a look to libphonenumber. It is proposed by google and used by android. If you provide the country it can parse for you any format of the number.
Concerning names it is difficult. If you are using your app only for a country you can create a database with the names (in france we have a file in opendata proposed by a public servive) but it won't be complete...

Android get gmail email subject from notification

i would like to read the subject of a new received email (gmail) from an android notification.
I think i have to use a NotificationListenerService running in background, catch the notification of new email in real time, and read the subject from that.
But how can i read the subject or a part of body text? Is it possible?
Thank you very much.
Here is an example that catches notifications and puts them into a text file. I only made this for development purposes so I could see how each app populates the notifications but it should show you how to do it.
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
new Store().execute(sbn);
}
private class Store extends AsyncTask<StatusBarNotification, Integer, Long> {
#Override
protected Long doInBackground(StatusBarNotification... params) {
String temp = "";
StatusBarNotification sbn = params[0];
Notification not = sbn.getNotification();
String pack = sbn.getPackageName();
// dump all the android notifications
if (pack.startsWith("com.android")) return null;
if (pack.startsWith("com.estrongs")) return null;
if (pack.startsWith("com.motorola")) return null;
count++;
if (not.category != null)
temp += "Category: " + not.category.toString() + "\n";
else
temp += "Category = null \n";
if (not.tickerText != null)
temp += "TickerText: " + not.tickerText.toString() + "\n";
else
temp += "TickerText = null \n";
temp += "Key: " + sbn.getKey() + "\n" + "ID: " + sbn.getId() + "\n";
SimpleDateFormat format = new SimpleDateFormat("DD-kk:mm:ss:SSS");
Long ptime = sbn.getPostTime();
temp += "Post time: " + format.format(ptime) + "\n";
Long nottime = not.when;
temp += "When: " + format.format(nottime) + "\n";
temp += "Extras..." + "\n";
Bundle bun = not.extras;
if (bun.getString(Notification.EXTRA_BIG_TEXT) != null)
temp += "BigText: " + bun.getString(Notification.EXTRA_BIG_TEXT).toString() + "\n";
else
temp += "BigText = null \n";
if (bun.getString(Notification.EXTRA_SUMMARY_TEXT) != null)
temp += "SummaryText: " + bun.getString(Notification.EXTRA_SUMMARY_TEXT).toString() + "\n";
else
temp += "SummaryText = null \n";
if (bun.getString(Notification.EXTRA_INFO_TEXT) != null)
temp += "InfoText: " + bun.getString(Notification.EXTRA_INFO_TEXT).toString() + "\n";
else
temp += "InfoText = null \n";
if (bun.getString(Notification.EXTRA_TEXT) != null)
temp += "Text: " + bun.getString(Notification.EXTRA_TEXT).toString() + "\n";
else
temp += "Text = null \n";
if (bun.getString(Notification.EXTRA_SUB_TEXT) != null)
temp += "SubText: " + bun.getString(Notification.EXTRA_SUB_TEXT).toString() + "\n";
else
temp += "SubText = null \n";
if (bun.getString(Notification.EXTRA_TITLE) != null)
temp += "Title:" + bun.getString(Notification.EXTRA_TITLE).toString() + "\n";
else
temp += "Title = null \n";
if (bun.getString(Notification.EXTRA_TITLE_BIG) != null)
temp += "Big Title:" + bun.getString(Notification.EXTRA_TITLE_BIG).toString() + "\n";
else
temp += "Big Title = null \n";
temp += "Fields... \n";
CharSequence[] lines = bun.getCharSequenceArray(Notification.EXTRA_TEXT_LINES);
if (lines != null) {
for (CharSequence line : lines) {
temp += "line: " + line.toString() + " \n";
}
} else {
temp += " no lines... \n";
}
file = new File(save, pack + count + ".txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(temp.getBytes());
fos.close();
//Toast.makeText(this, "File written", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
//Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
Notice I send the SBN to a background thread. The listener does not like much of anything in its thread. Also, the listener can be tricky with the debugger. I found that you need to disable the app in Android settings -> Sound & Notification -> Notification Access before you update the app. Then you can re-enable it once a package update is installed.
Hope that helps.

How to set youtube data to android widgets?

This is the code i am using to retreive a list of searched videos using the youtube data api.
if(detailed) {
YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
System.out.println("Uploaded by: " + mediaGroup.getUploader());
System.out.println("Video ID: " + mediaGroup.getVideoId());
System.out.println("Description: " +
mediaGroup.getDescription().getPlainTextContent());
MediaPlayer mediaPlayer = mediaGroup.getPlayer();
System.out.println("Web Player URL: " + mediaPlayer.getUrl());
MediaKeywords keywords = mediaGroup.getKeywords();
System.out.print("Keywords: ");
for(String keyword : keywords.getKeywords()) {
System.out.print(keyword + ",");
}
GeoRssWhere location = videoEntry.getGeoCoordinates();
if(location != null) {
System.out.println("Latitude: " + location.getLatitude());
System.out.println("Longitude: " + location.getLongitude());
}
Rating rating = videoEntry.getRating();
if(rating != null) {
System.out.println("Average rating: " + rating.getAverage());
}
YtStatistics stats = videoEntry.getStatistics();
if(stats != null ) {
System.out.println("View count: " + stats.getViewCount());
}
System.out.println();
System.out.println("\tThumbnails:");
for(MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) {
System.out.println("\t\tThumbnail URL: " + mediaThumbnail.getUrl());
System.out.println("\t\tThumbnail Time Index: " +
mediaThumbnail.getTime());
System.out.println();
}
How could i convert this information to the use of a text view for the title, a ImageView for the thumbnail??

Categories

Resources