Store static data in Android - custom resource? - android

I'm new to Android development, and I've been playing around with it a bit. I was trying to create a program that has a small database-like collection of never-changing data. In C#, my currently best language, I'd use a List of a custom class and serialize that to an xml file, then read that into my application at runtime. I found the /xml resource folder in Android, but I'm not sure how I would go about doing what I'm envisioning. What would be the best way to go about doing this?
The data will never need to change. Example:
Blob | A | B
----------------
Blob 1 | 23 | 42
Blob 2 | 34 | 21
I know that's laid out like a table, but using a database doesn't really make sense to me because the data will never change, and I would need a way to store it to initially populate the database anyway.
So basically I'm looking for a way to store somewhat-complex static data in my application. Any ideas?
EDIT: I also saw the /raw folder. So I could store things in /res/raw or /res/xml. But I'm not sure what would be the best way to store/parse the data...

I think this is the BEST solution and i am already using this one to store Static-data in my every project.
For that...
You can do one thing, make one xml file namely "temp.xml" ..and store the data in temp.xml as follows:
<?xml version="1.0" encoding="utf-8"?>
<rootelement1>
<subelement> Blob 1
<subsubelement> 23 </subsubelement>
<subsubelement> 42 </subsubelement>
</subelement>
<subelement>Blob 2
<subsubelement> 34 </subsubelement>
<subsubelement> 21 </subsubelement>
</subelement>
</rootelement1>
and then use XML PullParser technique to parse data.
You can have coding samples of PullParsing technique on Example , refer this example for better idea.
Enjoy!!

The best way is to use the Android Resource Heirarchy.
In the res/values/ directory, you can store any number of key-value pairs for several basic data types. In your app, you would refer to them using an autogenerated resource id (name based on your resource's key). See the link above for more documentation and details.
Android also supports raw datafiles. You could store your data in the file directory under res/raw/yourfile.dat
You you create your data in whatever text based format you want and then read it on activity startup using the resource access apis.

I have used Simple for xml parsing in the past. I think it has the least amount of code if you know what to expect in xml, which in your case you do.
http://simple.sourceforge.net/

According to the doc, /xml is the way to go.
Providing Resources
xml/ Arbitrary XML files that can be read at run-time by calling
Resources.getXML().
Various XML configuration files must be saved here, such as a searchable configuration.
Documentation for getXML()
I also made a working example:
the XML structure:
<?xml version="1.0" encoding="utf-8"?>
<quizquestions>
<quizquestion>
<header_image_src>ic_help_black_24dp</header_image_src>
<question>What is the Capital of U.S.A.?</question>
<input_type>Radio</input_type>
<answer correct="false">New York City</answer>
<answer correct="true">Washington D.C.</answer>
<answer correct="false">Chicago</answer>
<answer correct="false">Philadelphia</answer>
</quizquestion>
<quizquestion>
<header_image_src>ic_help_black_24dp</header_image_src>
<question>What is the family name of the famous dutch painter Vincent Willem van .... ?</question>
<input_type>EditText</input_type>
<answer correct="true">Gogh</answer>
</quizquestion>
</quizquestions>
the Java class to hold parsed data:
public class QuizQuestion {
private int headerImageResId;
private String question;
private String inputType;
private ArrayList<String> answers;
private ArrayList<Boolean> answerIsCorrect;
private ArrayList<Integer> correctAnswerIndexes;
/**
* constructor for QuizQuestion object
*/
QuizQuestion() {
headerImageResId = 0;
question = null;
inputType = null;
answers = new ArrayList<>();
answerIsCorrect = new ArrayList<>();
correctAnswerIndexes = new ArrayList<>();
}
public void setHeaderImageResId(int headerImageResId) {
this.headerImageResId = headerImageResId;
}
public int getHeaderImageResId() {
return headerImageResId;
}
void setQuestion(String question) {
this.question = question;
}
public String getQuestion() {
return question;
}
void setInputType(String inputType) {
this.inputType = inputType;
}
public String getInputType() {
return inputType;
}
void addAnswer(String answer, boolean isCorrect)
{
if (isCorrect)
correctAnswerIndexes.add(answers.size());
answers.add(answer);
answerIsCorrect.add(isCorrect);
}
public ArrayList<String> getAnswers() {
return answers;
}
public String getAnswer(int index)
{
// check index to avoid out of bounds exception
if (index < answers.size()) {
return answers.get(index);
}
else
{
return null;
}
}
public int size()
{
return answers.size();
}
}
the parser itself:
/**
* Created by bivanbi on 2017.02.23..
*
* class to parse xml resource containing quiz data into ArrayList of QuizQuestion objects
*
*/
public class QuizXmlParser {
public static String lastErrorMessage = "";
/**
* static method to parse XML data into ArrayList of QuizQuestion objects
* #param activity is the calling activity
* #param xmlResourceId is the resource id of XML resource to be parsed
* #return null if parse error is occurred or ArrayList of objects if successful
* #throws XmlPullParserException
* #throws IOException
*/
public static ArrayList<QuizQuestion> parse(Activity activity, int xmlResourceId)
throws XmlPullParserException, IOException
{
String logTag = QuizXmlParser.class.getSimpleName();
Resources res = activity.getResources();
XmlResourceParser quizDataXmlParser = res.getXml(R.xml.quiz_data);
ArrayList<String> xmlTagStack = new ArrayList<>();
ArrayList<QuizQuestion> quizQuestions = new ArrayList<>();
QuizQuestion currentQuestion = null;
boolean isCurrentAnswerCorrect = false;
quizDataXmlParser.next();
int eventType = quizDataXmlParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
// begin document
if(eventType == XmlPullParser.START_DOCUMENT)
{
Log.d(logTag,"Begin Document");
}
// begin tag
else if(eventType == XmlPullParser.START_TAG)
{
String tagName = quizDataXmlParser.getName();
xmlTagStack.add(tagName);
Log.d(logTag,"Begin Tag "+tagName+", depth: "+xmlTagStack.size());
Log.d(logTag,"Tag "+tagName+" has "+quizDataXmlParser.getAttributeCount()+" attribute(s)");
// this is a beginning of a quiz question tag so create a new QuizQuestion object
if (tagName.equals("quizquestion")){
currentQuestion = new QuizQuestion();
}
else if(tagName.equals("answer"))
{
isCurrentAnswerCorrect = quizDataXmlParser.getAttributeBooleanValue(null,"correct",false);
if (isCurrentAnswerCorrect == true) {
Log.d(logTag, "Tag " + tagName + " has attribute correct = true");
}
else
{
Log.d(logTag, "Tag " + tagName + " has attribute correct = false");
}
}
}
// end tag
else if(eventType == XmlPullParser.END_TAG)
{
String tagName = quizDataXmlParser.getName();
if (xmlTagStack.size() < 1)
{
lastErrorMessage = "Error 101: encountered END_TAG "+quizDataXmlParser.getName()+" while TagStack is empty";
Log.e(logTag, lastErrorMessage);
return null;
}
xmlTagStack.remove(xmlTagStack.size()-1);
Log.d(logTag,"End Tag "+quizDataXmlParser.getName()+", depth: "+xmlTagStack.size());
// reached the end of a quizquestion definition, add it to the array
if (tagName.equals("quizquestion")){
if (currentQuestion != null)
quizQuestions.add(currentQuestion);
currentQuestion = null;
}
}
// text between tag begin and end
else if(eventType == XmlPullParser.TEXT)
{
String currentTag = xmlTagStack.get(xmlTagStack.size()-1);
String text = quizDataXmlParser.getText();
Log.d(logTag,"Text: "+text+", current tag: "+currentTag+", depth: "+xmlTagStack.size());
if (currentQuestion == null) {
Log.e(logTag,"currentQuestion is not initialized! text: "+text+", current tag: "+currentTag+", depth: "+xmlTagStack.size());
continue;
}
if (currentTag.equals("header_image_src"))
{
int drawableResourceId = activity.getResources().getIdentifier(text, "drawable", activity.getPackageName());
currentQuestion.setHeaderImageResId(drawableResourceId);
}
else if (currentTag.equals("question"))
{
currentQuestion.setQuestion(text);
}
else if (currentTag.equals("answer"))
{
currentQuestion.addAnswer(text, isCurrentAnswerCorrect);
}
else if (currentTag.equals("input_type"))
{
currentQuestion.setInputType(text);
}
else
{
Log.e(logTag,"Unexpected tag "+currentTag+" with text: "+text+", depth: "+xmlTagStack.size());
}
}
eventType = quizDataXmlParser.next();
}
Log.d(logTag,"End Document");
return quizQuestions;
}
}
and finally, calling the parser:
// read quiz data from xml resource quiz_data
try {
quizQuestions = QuizXmlParser.parse(this,R.xml.quiz_data);
Log.d("Main","QuizQuestions: "+quizQuestions);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
quizQuestions = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
quizQuestions = null;
}
if (quizQuestions == null)
{
Toast.makeText(this,"1001 Failed to parse Quiz XML, sorry", Toast.LENGTH_LONG).show();
finish();
}

Related

how to get inner image url including XML tags Android Studio?

i can't access the inner tag to get the image "url"
here my tag name is "enclosure" and it contain another one called "url" and this is what i want to get...
here the a whole class i created
**public class ParseApplications {
private static final String TAG = "ParseApplications";
private ArrayList<NewsFeeds> application;
public ParseApplications() {
this.application = new ArrayList<>();
}
public ArrayList<NewsFeeds> getApplication() {
return application;
}
public boolean Parse(String xmlData) {
boolean status = true;
NewsFeeds currentNews = null;
boolean InEntry = false;
String textValue = "";
boolean gotImage = false;
try {
// XmlPullParserFactory This class is used to create implementations of XML Pull Parser defined in XMPULL
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
//coming line mean that the xml parse i will handle it by my code
/*
Specifies that the parser produced by this factory will provide support for XML namespaces.
By default the value of this is set to false.
Parameters
awareness
boolean: true if the parser produced by this code will provide support for XML namespaces; false otherwise.
*/
factory.setNamespaceAware(true);
//XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API
//newPullParser is Creates a new instance of a XML Pull Parser using the currently configured factory features.
XmlPullParser xxp = factory.newPullParser();
xxp.setInput(new StringReader(xmlData));
//getEventType Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.). return int
int eventType = xxp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagName = xxp.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
Log.d(TAG, "Parse: Starting tag for " + tagName);
if ("item".equalsIgnoreCase(tagName)) {
InEntry = true;
currentNews = new NewsFeeds();
}
break;
case XmlPullParser.TEXT:
textValue = xxp.getText();
break;
case XmlPullParser.END_TAG:
if (InEntry) {
if ("item".equalsIgnoreCase(tagName)) {
application.add(currentNews);
} else if ("title".equalsIgnoreCase(tagName)) {
currentNews.setName(textValue);
} else if ("pubdate".equalsIgnoreCase(tagName)) {
currentNews.setTheDate(textValue);
} else if ("description".equalsIgnoreCase(tagName)) {
currentNews.setSummry(textValue);
} else if ("link".equalsIgnoreCase(tagName)) {
currentNews.setTitle(textValue);
} else if ("enclosure".equalsIgnoreCase(tagName)) {
currentNews.setImageUrl(textValue);
}
}
break;
default:
//nothing to do
}
eventType = xxp.next();
}
for (NewsFeeds app : application) {
Log.d(TAG, "*********************");
Log.d(TAG, app.toString());
}
} catch (Exception e) {
status = false;
}
return status;
}
}**
i can't access the inner tag to get the image "url" here my tag name is "enclosure" and it contain another one called "url" and this is what i want to get... here the a whole class i created
I suggest printing the raw data and see the hierarchy of the tags. just do a Log without parsing the data and read it yourself. It might be missing or you need to access a parent tag before you get it.
also this might seem basic but are you sure you typed it correctly ? (capital letters, spaces etc)
How about the other tags ? I guess you are getting them correctly .
SOLVED
JUST TWO LINES
else if ("enclosure".equalsIgnoreCase(tagName)) {
String url = xxp.getAttributeValue(0);
currentNews.setImageUrl(url);
}

Android - Simple XML Framework. #Convert interferes with #Attribute - How to solve this?

I was working on capturing the order of elements contained in tag. Here is all the code:
League.java:
#Root
#Convert(value = LeagueConverter.class)
public class League
{
#Attribute
private String name;
#Element(name="headlines", required = false)
private Headlines headlines;
#Element(name="scores", required = false)
private Scores scores;
#Element(name="standings", required = false)
private Standing standings;
#Element(name="statistics", required = false)
private LeagueStatistics statistics;
public List<String> order = new ArrayList<String>();
// get methods for all variables
}
LeagueConverter.java:
public class LeagueConverter implements Converter<League>
{
#Override
public League read(InputNode node) throws Exception
{
League league = new League();
InputNode next = node.getNext();
while( next != null )
{
String tag = next.getName();
if(tag.equalsIgnoreCase("headlines"))
{
league.order.add("headlines");
}
else if(tag.equalsIgnoreCase("scores"))
{
league.order.add("scores");
}
else if(tag.equalsIgnoreCase("statistics"))
{
league.order.add("statistics");
}
else if(tag.equalsIgnoreCase("standings"))
{
league.order.add("standings");
}
next = node.getNext();
}
return league;
}
#Override
public void write(OutputNode arg0, League arg1) throws Exception
{
throw new UnsupportedOperationException("Not supported yet.");
}
}
Exampe of XML:
<android>
<leagues>
<league name ="A">
<Headlines></Headlines>
<Scores></Scores>
...
</league>
<league name ="B">...</league>
</leagues>
</android>
How I'm calling it and expecting it to behave: (Snippet)
Android android = null;
Serializer serial = new Persister(new AnnotationStrategy());
android = serial.read(Android.class, source);
Log.i("Number of leagues found ",tsnAndroid.getLeagueCount() + ""); // prints fine
League nhl = tsnAndroid.getLeagues().get(0); // works fine
// DOES NOT WORK throws NullPointerEx
League nhl2 = tsnAndroid.getLeagueByName("A");
// DOES NOT WORK throws NullPointerEx
for(String s : nhl.getOrder())
{
Log.i("ORDER>>>>>", s);
}
The problem:
android.getLeagueByName() (Works with #Attribute name) suddenly stops working when I have the converter set, so its like the following from League.java, never gets set.
#Attribute
private String name; // not being set
However, when I comment out the converter declaration in League.java - Every league has an attribute called name and android.getLeagueByName() starts working fine...
Does #Convert for League somehow interfere with #Attribute in League?
Even though this question is outrageously old (as is the SimpleXML library), I will give my two cents.
#Convert annotation works only with #Element, but it does not have any effect on #Attribute. I'm not sure if that's a bug or a feature, but there is another way of handling custom serialized objects - called Transform with Matcher, and it works both with Attributes and with Elements. Instead of using the Converters, you define a Transform class that handles serialization and deserialization:
import java.util.UUID;
import org.simpleframework.xml.transform.Transform;
public class UUIDTransform implements Transform<UUID> {
#Override
public UUID read(String value) throws Exception {
return value != null ? UUID.fromString(value) : null;
}
#Override
public String write(UUID value) throws Exception {
return value != null ? value.toString() : null;
}
}
As you can see, it is more straight-forward than implementing the Convert interface!
Create a similar class for all your objects that require custom de/serialization.
Now instantiate a RegistryMatcher object and register there your custom classes with their corresponding Transform classes. This is a thread-safe object that internally uses a cache, so it might be a good idea to keep it as a singleton.
private static final RegistryMatcher REGISTRY_MATCHER = new RegistryMatcher();
static {
try {
REGISTRY_MATCHER.bind(UUID.class, UUIDTransform.class);
// register all your Transform classes here...
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Finally, you can create a Persister class each time before a conversion and pass it the AnnotationStrategy together with your RegistryMatcher instance. In this factory method below, we will also use an indenting formatter:
private static Persister createPersister(int indent) {
return new Persister(new AnnotationStrategy(), REGISTRY_MATCHER, new Format(indent));
}
Now you can make your serialization/deserialization methods:
public static String objectToXml(Object object, int indent) throws MyObjectConversionException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Persister p = createPersister(indent);
try {
p.write(object, out, "UTF-8");
return out.toString("UTF-8");
} catch (Exception e) {
throw new MyObjectConversionException("Cannot serialize object " + object + " to XML: " + e.getMessage(), e);
}
}
public static <T> T xmlToObject(String xml, final Class<T> clazz) throws MyObjectConversionException {
Persister p = createPersister(0);
try {
return (T) p.read(clazz, xml);
} catch (Exception e) {
throw new MyObjectConversionException(
"Cannot deserialize XML to object of type " + clazz + ": " + e.getMessage(), e);
}
}
The only issue with this approach is when you want to have different formatting for the same object - e.g. once you want the java.util.Date to have just the date component, while later on you also want to have the time component. Then just extend the Date class, calling it DateWithTime, and make a different Transform for it.
#ElementListUnion will capture the order of elements
The #Convert annotation works only on #Element fields. I am struggling against converting #Attribute fields too but with no success for now...

How to get Category for each App on device on Android?

I've got an Android app which scans for all Apps installed on the device and then reports this to a server (it's an MDM agent). Any suggestions on how to get the Category of the App? Everyone has a different list of Categories, but basically something like Game, Entertainment, Tools/Utilities, etc.
From what I can tell there is nothing related to Category stored on the device itself. I was thinking of using the android market API to search for the application in the market and use the Category value returned by the search. Not sure how successful this will be finding a match. Any suggestions on how best to do this?
Any suggestions on a different approach?
Thanks in advance.
mike
I know that this is an old post, but for anyone still looking for this, API level 26 (O) has added categories to android.content.pm.ApplicationInfo.
From the docs https://developer.android.com/reference/android/content/pm/ApplicationInfo#category:
public int category
The category of this app. Categories are used to cluster multiple apps together into meaningful groups, such as when summarizing battery, network, or disk usage. Apps should only define this value when they fit well into one of the specific categories.
Set from the R.attr.appCategory attribute in the manifest. If the manifest doesn't define a category, this value may have been provided by the installer via PackageManager#setApplicationCategoryHint(String, int).
Value is CATEGORY_UNDEFINED, CATEGORY_GAME, CATEGORY_AUDIO, CATEGORY_VIDEO, CATEGORY_IMAGE, CATEGORY_SOCIAL, CATEGORY_NEWS, CATEGORY_MAPS, or CATEGORY_PRODUCTIVITY
One can now do something like:
PackageManager pm = context.getPackageManager();
ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int appCategory = applicationInfo.category;
String categoryTitle = (String) ApplicationInfo.getCategoryTitle(context, appCategory)
// ...
}
if you get for each application its package name, you could ask directly to play store which category an app belongs, parsing html response page with this library:
org.jsoup.jsoup1.8.3
Here's a snippet to solve your problem:
public class MainActivity extends AppCompatActivity {
public final static String GOOGLE_URL = "https://play.google.com/store/apps/details?id=";
public static final String ERROR = "error";
...
private class FetchCategoryTask extends AsyncTask<Void, Void, Void> {
private final String TAG = FetchCategoryTask.class.getSimpleName();
private PackageManager pm;
private ActivityUtil mActivityUtil;
#Override
protected Void doInBackground(Void... errors) {
String category;
pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
Iterator<ApplicationInfo> iterator = packages.iterator();
while (iterator.hasNext()) {
ApplicationInfo packageInfo = iterator.next();
String query_url = GOOGLE_URL + packageInfo.packageName;
Log.i(TAG, query_url);
category = getCategory(query_url);
// store category or do something else
}
return null;
}
private String getCategory(String query_url) {
boolean network = mActivityUtil.isNetworkAvailable();
if (!network) {
//manage connectivity lost
return ERROR;
} else {
try {
Document doc = Jsoup.connect(query_url).get();
Element link = doc.select("span[itemprop=genre]").first();
return link.text();
} catch (Exception e) {
return ERROR;
}
}
}
}
}
You could make these queries in an AsyncTask, or in a service. Hope that you find it helpful.
I also faced the same issue. The solution for the above query is stated below.
Firstly, download the Jsoup library or download the jar file.
or
Add this to your build.gradle(Module: app) implementation 'org.jsoup:jsoup:1.11.3'
private class FetchCategoryTask extends AsyncTask<Void, Void, Void> {
private final String TAG = FetchCategoryTask.class.getSimpleName();
private PackageManager pm;
//private ActivityUtil mActivityUtil;
#Override
protected Void doInBackground(Void... errors) {
String category;
pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
Iterator<ApplicationInfo> iterator = packages.iterator();
// while (iterator.hasNext()) {
// ApplicationInfo packageInfo = iterator.next();
String query_url = "https://play.google.com/store/apps/details?id=com.imo.android.imoim"; //GOOGLE_URL + packageInfo.packageName;
Log.i(TAG, query_url);
category = getCategory(query_url);
Log.e("CATEGORY", category);
// store category or do something else
//}
return null;
}
private String getCategory(String query_url) {
try {
Document doc = Jsoup.connect(query_url).get();
Elements link = doc.select("a[class=\"hrTbp R8zArc\"]");
return link.text();
} catch (Exception e) {
Log.e("DOc", e.toString());
}
}
}
In return, you will get Application Company Name and category of the application
I made a Kotlin solution based on the answer from #Ankit Kumar Singh.
This solution maps the category to an enum, in case you want to do other things than just show it.
import kotlinx.coroutines.*
import org.jsoup.Jsoup
import javax.inject.Inject
import javax.inject.Singleton
class AppCategoryService {
companion object {
private const val APP_URL = "https://play.google.com/store/apps/details?id="
private const val CAT_SIZE = 9
private const val CATEGORY_STRING = "category/"
}
suspend fun fetchCategory(packageName: String): AppCategory {
val url = "$APP_URL$packageName&hl=en" //https://play.google.com/store/apps/details?id=com.example.app&hl=en
val categoryRaw = parseAndExtractCategory(url) ?: return AppCategory.OTHER
return AppCategory.fromCategoryName(categoryRaw)
}
#Suppress("BlockingMethodInNonBlockingContext")
private suspend fun parseAndExtractCategory(url: String): String? = withContext(Dispatchers.IO) {
return#withContext try {
val text = Jsoup.connect(url).get()?.select("a[itemprop=genre]") ?: return#withContext null
val href = text.attr("abs:href")
if (href != null && href.length > 4 && href.contains(CATEGORY_STRING)) {
getCategoryTypeByHref(href)
} else {
null
}
} catch (e: Throwable) {
null
}
}
private fun getCategoryTypeByHref(href: String) = href.substring(href.indexOf(CATEGORY_STRING) + CAT_SIZE, href.length)
}
And here is the enum with all the possible values at of this moment in time:
// Note: Enum name matches API value and should not be changed
enum class AppCategory {
OTHER,
ART_AND_DESIGN,
AUTO_AND_VEHICLES,
BEAUTY,
BOOKS_AND_REFERENCE,
BUSINESS,
COMICS,
COMMUNICATION,
DATING,
EDUCATION,
ENTERTAINMENT,
EVENTS,
FINANCE,
FOOD_AND_DRINK,
HEALTH_AND_FITNESS,
HOUSE_AND_HOME,
LIBRARIES_AND_DEMO,
LIFESTYLE,
MAPS_AND_NAVIGATION,
MEDICAL,
MUSIC_AND_AUDIO,
NEWS_AND_MAGAZINES,
PARENTING,
PERSONALIZATION,
PHOTOGRAPHY,
PRODUCTIVITY,
SHOPPING,
SOCIAL,
SPORTS,
TOOLS,
TRAVEL_AND_LOCAL,
VIDEO_PLAYERS,
WEATHER,
GAMES;
companion object {
private val map = values().associateBy(AppCategory::name)
private const val CATEGORY_GAME_STRING = "GAME_" // All games start with this prefix
fun fromCategoryName(name: String): AppCategory {
if (name.contains(CATEGORY_GAME_STRING)) return GAMES
return map[name.toUpperCase(Locale.ROOT)] ?: OTHER
}
}
}
private fun getCategory(){
val GOOGLE_URL = "https://play.google.com/store/apps/details?id=com.google.android.deskclock"
lifecycleScope.launch(Dispatchers.IO) {
val doc: Document = Jsoup.connect(GOOGLE_URL).get()
val index = doc.body().data().indexOf("applicationCategory")
val simpleString = doc.body().data().subSequence(index,index+100)
val data = simpleString.split(":")[1].split(",")[0]
Log.e("DATA-->",data.toString())
}
}
You can use below AsyncTask for extract Android app category from playStore by using app package id.
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class GetAppCategory extends AsyncTask<String, Void, String> {
//Main URL for each app on Play Store
public static final String APP_URL = "https://play.google.com/store/apps/details?id=";
//Use below String if extracting 'CATEGORY' from href tag.
private final String CATEGORY_STRING = "category/";
private final int cat_size = 9;
/*Use below String for identified 'GAME' apps, which must start with this prefix.
Here I only display 'Games' as category for all Games app instead of showing their subCategory also*/
private final String CATEGORY_GAME_STRING = "GAME_";
//Name of the app package for which you want to get category.
private String packageName = null;
private PackageManager pm = null;
//Activity or Application context as per requirement.
private Context appContext;
/* You can add default system app OR non play store app package name here as comma seprated for ignore them
and set their category directly 'Others' OR anythings you wish. */
private final String extractionApps = "com.android.providers.downloads.ui, com.android.contacts," +
" com.android.gallery3d, com.android.vending, com.android.calculator2, com.android.calculator," +
" com.android.deskclock, com.android.messaging, com.android.settings, com.android.stk";
//Class level TAG, use for Logging.
private final String TAG = "GetAppCategory";
/**
* #param packageName: package name of the app, you want to extract category.
* #param appContext: Activity/Application level Context ap per requirement.
*/
public GetAppCategory(String packageName, Context appContext) {
this.packageName = packageName;
this.appContext = appContext;
}
#Override
protected String doInBackground(String... params) {
try {
pm = appContext.getPackageManager();
if (packageName != null && packageName.length() > 1) {
if (packageName.contains("package:")) {
packageName = packageName.replace("package:", "");
}
/**
* Mathod used for parse play store html page and extract category from their.
*/
String appCategoryType = parseAndExtractCategory(packageName);
Log.i(TAG, "package :" + packageName);
Log.i(TAG, "APP_CATEGORY: " + appCategoryType);
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
} finally {
//TODO::
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
/**
* #param packageName
* #return
*/
private String parseAndExtractCategory(String packageName) {
//You can pass hl={language_code} for get category in some other langauage also other than English.
//String url = APP_URL + packageName + "&hl=" + appContext.getString(R.string.app_lang);
String url = APP_URL + packageName + "&hl=en"; //{https://play.google.com/store/apps/details?id=com.example.app&hl=en}
String appCategoryType = null;
String appName = null;
try {
if (!extractionApps.contains(packageName)) {
Document doc = null;
try {
doc = Jsoup.connect(url).get();
if (doc != null) {
//TODO: START_METHOD_1
//Extract category String from a <anchor> tag value directly.
//NOTE: its return sub category text, for apps with multiple sub category.
//Comment this method {METHOD_1}, if you wish to extract category by href value.
Element CATEGORY_SUB_CATEGORY = doc.select("a[itemprop=genre]").first();
if (CATEGORY_SUB_CATEGORY != null) {
appCategoryType = CATEGORY_SUB_CATEGORY.text();
}
//TODO: END_METHOD_1
//TODO: START_METHOD_2
// Use below code only if you wist to extract category by href value.
//Its return parent or Main Category Text for all app.
//Comment this method {METHOD_2}, If you wihs to extract category from a<anchor> value.
if (appCategoryType == null || appCategoryType.length() < 1) {
Elements text = doc.select("a[itemprop=genre]");
if (text != null) {
if (appCategoryType == null || appCategoryType.length() < 2) {
String href = text.attr("abs:href");
if (href != null && href.length() > 4 && href.contains(CATEGORY_STRING)) {
appCategoryType = getCategoryTypeByHref(href);
}
}
}
}
//TODO: END_METHOD_2
if (appCategoryType != null && appCategoryType.length() > 1) {
/**
* Ger formatted category String by removing special character.
*/
appCategoryType = replaceSpecialCharacter(appCategoryType);
}
}
} catch (IOException e) {
//appCategoryType = appContext.getString(R.string.category_others);
appCategoryType = "OTHERS";
//TODO:: Handle Exception
e.printStackTrace();
}
} else {
//appCategoryType = appContext.getString(R.string.category_others);
appCategoryType = "OTHERS";
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
}
return appCategoryType;
}
/**
* #param href
* #return
*/
private String getCategoryTypeByHref(String href) {
String appCategoryType = null;
try {
appCategoryType = href.substring((href.indexOf(CATEGORY_STRING) + cat_size), href.length());
if (appCategoryType != null && appCategoryType.length() > 1) {
if (appCategoryType.contains(CATEGORY_GAME_STRING)) {
//appCategoryType = appContext.getString(R.string.games);
appCategoryType = "GAMES";
}
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
}
return appCategoryType;
}
/**
* #param appCategoryType
* #return: formatted String
*/
private String replaceSpecialCharacter(String appCategoryType) {
try {
//Find and Replace '&' with '&' in category Text
if (appCategoryType.contains("&")) {
appCategoryType = appCategoryType.replace("&", " & ");
}
//Find and Replace '_AND_' with ' & ' in category Text
if (appCategoryType.contains("_AND_")) {
appCategoryType = appCategoryType.replace("_AND_", " & ");
}
//Find and Replace '_' with ' ' <space> in category Text
if (appCategoryType.contains("_")) {
appCategoryType = appCategoryType.replace("_", " ");
}
} catch (Exception e) {
//TODO:: Handle Exception
e.printStackTrace();
}
return appCategoryType;
}
}
It's requires jsoup library for parsing the html page. you can find it here org.jsoup.jsoup1.11.1
Probably a bit late, but the problem is still here.
The OP has the advantage because of sending those results to the API (here I assume that the API is managed by the OP or his API colleagues at least).
So, for anyone with the similar problem I'd suggest following:
Collect all the package names you're interested in from device.
Send that data to the your API
API should extract package names and try to read results from its cache / db...
For those packages that do not exist in cache / db make "market API" call and extract category - save it to the db / cache for reuse in this iteration.
When all requests (to cache / db and market API) are completed do whatever you like with the results.
Things to consider:
When multiple users try to query your API for a same package name and you don't have a category for that package in your cache / db...
Do 1 request to "market API" for packagex and update packagex in your cache / db to "waiting for results" state - next request should either get a "waiting for results" or a result that "market API" returned.
One should also consider a fallback for possible "market API" fails (market API not working, not a google play app, or something similar). This decision is basically tied to your domain and the business trend that you're trying to catch will force a decision about this for you. If you're really into getting this category stuff sorted out you could pipeline this fallback to human decision and update your API db / cache for packagex accordingly.
put up a nice API that would handle these and similar scenarios gracefully then one could probably even commercialize it up to a certain extent and "market API endpoint" - AKA play store package details page. That page would lose a big part of it's fake users :)

XML object storage

I've created an XML pull-parser which pulls details of an xml out:
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new InputStreamReader(response3.getEntity().getContent()));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
This searches through the XML correctly pulling out different tags etc.
My problem is now that I wish to store these. The basic structure is that it stores a series of cards, each with an attribute list. The outer tag would be something like <card> and inside there would be many attributes such as <resourceid>, <price> etc.
I wish to store each card in an easy to retrieve manner. I was thinking of using SQlite but have very little experience with it.Is it possible to do this as the parser steps through?
Added my class here
public class SecondActivity {
String resourceid;
String startprice;
String currentbid;
String buynowprice;
String expires;
public String getResourceId(){
return this.resourceid;
}
public String getStartPrice(){
return this.startprice;
}
public String getCurrentBid(){
return this.currentbid;
}
public String getBuyNowPrice(){
return this.buynowprice;
}
public String getExpires(){
return this.expires;
}
public void setResourceId(String resourceidin){
this.resourceid = resourceidin;
}
public void setStartPrice(String startpricein){
this.startprice = startpricein;
}
public void setCurrentBid(String currentbidin){
this.currentbid = currentbidin;
}
public void setBuyNowPrice(String buynowpricein){
this.buynowprice = buynowpricein;
}
public void setExpires(String expiresin){
this.expires = expiresin;
}
}
I now just call each statement i.e. the set inside where the parser finds the tag values, I then call a store, passing it this object? How do I then clear all values inside object?
Thanks for all the help, most appreciated.
Trying to find the start of the card as defined by
added this to my code:
else if(eventType == XmlPullParser.START_TAG) {
if (xpp.getName() == "auctionInfo"){
this.setMyflag(1);
System.out.println("IN THE IF FLAG IS SET TO 1");
}
System.out.println("Start tag "+xpp.getName());
Unfortunately it never enters the if, and I am stumped as to why!
Sure you can. For some input about how to use SQLite in Android, see here.
You could (for example) create a class which holds the informations for one of your <card>-tags (to build something like a data-package for one card) and then perform the Database-Inserts in another method which takes an Object of this class and processes it.
Your <card>-element will have multiple child-elements or attributes. Those are the fields you for your new class. When the parser finds one of those Child-Elements/Attributes, you set the corresponding field in your class.
When the parser finds the next <card>-element, you first call your storeCardInDB()-method (or whatever you call it) and pass it the filled out Object.
The method will take the fields from your Object, bind them to a PreparedStatement (for example) and send it to the Database.
This is done for every <card>-element in your XML-File.
Okay, there is a difference in comparing two ints and two Strings. If you want to know if the content of a String matches the content of another String, you'll need to use the equals()-method:
if ( xpp.getName().equals("auctionInfo") ) {[...]}
Here is a nice article which should clear the background of this behavior.

XMLPullParser Out of Memory (Android)

I'm stuck in trying to handle an out of memory error in Android while trying to parse a response from a HTTPTransfer using SOAP. Overall the transport is fine until I ask for a large image. The image is about 901KB is size, but for some reason it causes Android to run out of memory while parsing it. Here is the code:
public void parseWithPullParser(InputStream is) {
try {
XmlPullParser parser = GenericHandler.createParser(this.parserTypeName); // new
// org.xmlpull.mxp1.MXParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(is, null);
Log.d(TAG, "Name of class being parsed: " + resultClassName);
for (int eventType = parser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = parser
.next()) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT: {
break;
}
case XmlPullParser.START_TAG: {
String name = parser.getName();
String prefix = null;
if ("Envelope".equals(name) || "Header".equals(name) || "Body".equals(name)
|| "return".equals(name)) {
prefix = "env:"; // TODO: Hack-Hack-Hack... :)
}
name = prefix == null ? name : prefix + ":" + name;
this.startElement(name);
break;
}
case XmlPullParser.TEXT: {
String text = parser.getText();
if (text != null) {
if (resultClassName.contains("ImageSingle")) {
Log.d(TAG, "Text passage: " + text);
}
if (content == null) {
content = new String();
}
content = text; // Original system used a string builder
// but only for a single section, for
// large images this was a problem, but
// a single string object appears to
// have the same affect
// char[] ch = text.toCharArray(); //original
// this.characters(ch, 0, ch.length); //original
}
break;
}
case XmlPullParser.END_TAG: {
String name = parser.getName();
String prefix = null;
if ("Envelope".equals(name) || "Header".equals(name) || "Body".equals(name)
|| "return".equals(name)) {
prefix = "env:"; // TODO: Hack-Hack-Hack... :)
}
name = prefix == null ? name : prefix + ":" + name;
this.endElement(name);
break;
}
default: {
break;
}
}
}
} catch (Exception except) {
Log.e(this.getClass().getSimpleName(), except.toString(), except);
}
}
I found the library here. The issue (I believe) is when it does parser.next() because it reads in the image data (which is sent to me in a Base64 encoded string) and then tries to do parser.getText(). If I am understanding everything properly the way it outputs the string is by repetitive calls to the internal stringbuilder that will keep repeating .toString() to itself until it generates the parsed string. The image in question is about 1.2 million characters and as each character is 2 bytes, that implies 2.4 MB (the image though is 901 KB originally..but I guess there's extra data that gets parsed?) if I understand this correctly. But the heap expands to over 16 MB which causes the app to crash on stock VM settings when this method is called.
I doubt this is a unique situation and as such would love to hear how others have handled this problem. I've thought about maybe just throwing the string to a file on the SD card to keep it out of memory but it seems that for me to get the string I need parser.getText...which therein lies the problem.
Pursuant to Stephan Branczyk's comment here is my comment extracted and marked as the answer to my question.
For anyone that comes across this, I eventually ended up using a sax parser, I got the idea from here : helloandroid.com/tutorials/newsdroid-rss-reader

Categories

Resources