I have to download here map for my country without using the complex UI for selecting it.
Simply I need to detect the country somehow and download the offline map for the country from here.
I know this will fix the problem.
List<Integer> idList = new ArrayList<>();
idList.add(country.getId());
mMapLoader.installMapPackages(idList)
But I don't know how to get the MapPackage country object .
I don't want to implement a list UI and select country from it.
I want to detect my MapPackage country and download it directly.
You can use the locale of the device to find the country:
String locale = context.getResources().getConfiguration().locale.getDisplayCountry();
or you can use the location through the sim used in the phone by the user:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
below is the code for country code
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
Using the above function you can get Country code so that you can directly pass it as a parameter to your function
ex: mMapLoader.installMapPackages(System.Web.HttpContext.Current.Session["UserCountryCode"])
below is the code for country code
String UserIP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(UserIP))
{
UserIP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
string url = "http://freegeoip.net/json/" + UserIP.ToString();
WebClient client = new WebClient();
string jsonstring = client.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
System.Web.HttpContext.Current.Session["UserCountryCode"] = dynObj.country_code;
Using the above function you can get Country code so that you can directly pass it as a parameter to your function
ex: mMapLoader.installMapPackages(System.Web.HttpContext.Current.Session["UserCountryCode"])
In Java
public static final Map<String, String> COUNTRY_MAP;
static {
Map<String, String> map = new HashMap<String, String>();
map.put("AF", "afghanistan"); // here put your country dynamically
map.put("AL", "albania");
...
map.put("ZW", "zimbabwe");
COUNTRY_MAP = Collections.unmodifiableMap( map );
}
Related
I'm using amirdew/JSON library, which you can find here to parse my string to JSON.
The string I retrieved is this: https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal
This is the code I have at the moment, and it is not working and I believe that it is because of the keys...
public void ParseJson (String json){
JSON json2 = new JSON(json);
String firstTag = json2.key("query").key("pages").key("extract").stringValue();
txtInfo = findViewById(R.id.txtInfo);
txtInfo.setText(firstTag);
}
The firstTag variable is null because it can't retrieve any value. I want to retrieve the text inside "extracts". How can I do it? What keys do I need?
I suggest you to use the JSONObject which is already inside the SDK. You would use it like this:
String input = "..."; // your input
JSONObject obj = new JSONObject(input);
Strings extracts = obj.getJSONObject("query").getJSONObject("pages").getJSONObject("23033").getString("extract");
I'm developing a client app for android and my API requires me to send picture names in ArrayList<String> like:
collection[0] = 15a877ce9f22bc8349cac80565c4bff6.jpg
collection[1] = 25a877ce9f22bc8349cac80565c4bff6.jpg
but when i send it it goes in the form like:
collection[] = 15a877ce9f22bc8349cac80565c4bff6.jpg
collection[] = 25a877ce9f22bc8349cac80565c4bff6.jpg
my retrofit interface:
#Field("collection[]") ArrayList<String> collection);
how can I achieve the requested result?
any help would be appreciated! Thank you!
Don't put [] in the #Field name, I don't know exactly why you are doing this but it could be confusing as those are reserved character...
You can use something like this:
// ApiService.java
#FormUrlEncoded
#POST("/api/projectLost")
public void projectMarkLost(
#Field("apiKey") String apiKey,
#Field("project_id") int projectId,
#Field("lost_project_remark") String lostProjectRemark,
#Field("lost_project_reasons") ArrayList<Integer> lostProjectReasons,
Callback<JsonObject> cb
);
// Content wish to post
POST content:
apiKey = EzAvFvScs45a2DRI0MktdIDeVRbP59
project_id = 986
remark = testing
details = [detail_1,detail_2]
I found a solution of using Map to achive a desirable result
#FormUrlEncoded
#POST("user/news")
Call<CreateNews> createNews(
#Field("text") String text,
#FieldMap Map<String, String> collection);
and in method:
public void createNews(String text, ArrayList<String> collection, final Callback<CreateNews> callback){
News createNews = ServiceGenerator.createService(News.class);
SortedMap fields = new TreeMap<String, String>();
for (int i = collection.size()-1 ; i >= 0 ; i--) {
fields.put("collection["+i+"]", collection.get(i));
}
Call<CreateNews> call = createNews.createNews(text, fields);
call.enqueue(callback);
I have an issue in getting parameters from a URL mentioned below,
String url = http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999
My code to extract the parameters is as follows:
Uri uri = Uri.parseurl(url);
Set<String> paramNames = uri.getQueryParameterNames();
However, as you can see a "#" in the URL instead of "?" so that's why I am not able to get the parameters Set.
First thing that came to my mind is to replace "#" with "?" using String.replace method then I thought their might be better solution for this. So if you guys have better solution please help me.
Easiest method:
String string = url.replace("#","?");
String access_token = Uri.parse(string).getQueryParameter("access_token");
Log.d("TAG", "AccessToken: " + access_token);
Now you can get any parameter from the url just by passing their name.
Good Luck
'#' is called refrence parameter, Here you can do one of two things either replace the '#' with '?' and process your uri i.e
String url = "http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999";
url = url.Replace("#","?"); //now your URI object to proceed further
or other alternative
String url = "http://example.com/api_callback#access_token=XXXXXXXXXXXXXXX&state=enabled&scope=profile%20booking&token_type=bearer&expires_in=15551999";
URL myurl = new URL(url);
String refrence = myurl.getRef(); //returns whatever after '#'
String[][] params = GetParameters(refrence);
and the defination for function GetParameters() is following
private String[][] GetParameters(String r)
{
try
{
String[] p = r.split("&"); //separate parameters mixed with values
String[][] data = new String[p.length][2];
for(int i = 0 ; i<p.length; i++) //iterate whole array
{
data[i][0] = p[i].split("=")[0]; //parameter name
data[i][1] = p[i].split("=")[1]; //parameter value
data[i][1] = data[i][1].replace("%"," "); //replace % with space character
}
return data; //return result
}
catch(Exception e)
{
return null;
}
}
i have not executed and tested the code i am lazy one too so i hope you will accomodate lolz :D
You can use the Uri class in Android to do this; https://developer.android.com/reference/android/net/Uri.html
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths-Addition%20&%20Subtraction&post=394");
//Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("chapter"); //will return "V-Maths-Addition "
Uri uri = Uri.parse("http://www.chalklit.in/post.html?chapter=V-Maths- Addition%20&%20Subtraction&post=394");
String server = uri.getAuthority();
String path = uri.getPath();
String protocol = uri.getScheme();
Set<String> args = uri.getQueryParameterNames();
Then you can even get a specific element from the query parameters as such;
String chapter = uri.getQueryParameter("key");
I have a api like this
-{
- meta {
item1: value;
item2: value;
item3: value;
},
- object [
{
- category {
id: 1;
...
}
- File {
...
}
},
{
- category {
id:2;
...
}
- File {
...
}
}
]
I dont have any problem to parse JSONArray of "obejct" and it's JSONObjects...
I do like this:
private static final String TAG_NOD = "object";
private static final String TAG_CAT = "category";
private static final String TAG_CAT_ID = "id";
private static final String TAG_CAT = "File";
JSONArray Items = null;
JSONObject jsonObj = new JSONObject(jsonstr); // jsonstr is loaded url by httpcal
Items = jsonObj.getJSONArray(TAG_NOD);
for ( int i=0; i<Items.length(); i++){
JSONObject childs = Items.getJSONObject(i);
JSONObject category= child.getJSONOBject(TAG_CAT);
// getting category items in string like String ID = category.getString(TAG_CAT_ID);
JSONObject file = Item.getJSONObject(TAG_FILE)
// getting file items in string like file.getString(String name)
HashMap<String, String> items = new HashMap<String, String>();
items.put(TAG_CAT_ID, ID);
.
.
.
ItemLis.add(items); //Itemlist is a ArrayList<HashMap<String, String>>()
}
but my problem is to parsing jsonobject of "meta" and add its data to my ListItem Arraylist
any solution appreciated :D
Like this:
JSONObject meta = jsonObj.getJSONObject("meta");
Iterator<String> iterator = meta.keys();
HashMap<String,String> metaMap = new HashMap<String,String>();
while (it.hasNext()) {
String key = iterator.next();
String value = meta.getString(key);
metaMap.put(key,value);
}
ItemLis.add(items);
Also, if I may, here are a couple of quick suggestions on some things I've noticed that could improve your coding style:
Per Java naming conventions, variables and member names start with a lower case letter, so it should be itemLis instead of ItemLis. You already do this on most of your names except for ItemLis and Items. While this is not a must, following convention will make your code more readable, not only to you, but also when you seek help here on SO.
Unless you specifically require that the items in ItemLis be HashMaps (that is, your algorithm will not work with any other Map implementation), it's usually considered good practice to hide that detail from the implementation. I.e. instead of HashMap<...> items = new HashMap, go like Map<...> items = new HashMap, and change the type of ItemLis from <ArrayList<HashMap<...>> to List<Map<...>>. That way, if you ever decide to change the implementation backing the list or map, your code changes will be confined to only one place, instead of breaking much of your code. As a rule of thumb: Try to declare types with the most abstract type you require.
You can use the GSON lib. Very simple and fast implemented. Best practise at this case.
Just create an object which looks like your json string.
Then call:
Gson gson = new Gson();
YourObject obj = gson.fromJson(jsonString, YourObject.class);
Then you have the data in an object and can use it with getter and setter. Maybe you have to annotate the variables in the object. For that take a look here: https://code.google.com/p/google-gson/
I am a new developer on android application. I would like to get the ISO Country code when I pass the mobile number with country code. If I pass the mobile number as 1-319-491-6338, can I get country ISO code as US / USA in android?
I have written the code as follows:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
String mobileno="1-319-491-6338";
Here, where can I pass the mobile number?
Can anybody please help me ?
Thanks in advance
You may not be able to query the country code programmatically via the standard API but you could include a table in your app. Such a table is easily found via Google (e.g. http://countrycode.org/).
Danger Will Robinson!: However, one should ask yourself what question you are trying to answer. Implicit in your question is that assumption that there is a one-to-one mapping between international dialling codes and ISO country codes. This is not true. For example, both the USA and Canada have the international dialling code '1'.
Perhaps think about re-structuring your app's interface. Allow the user to select a country to associate with the phone number but use the table from http://countrycode.org/ to order the most likely candidates at the top?
Had the same problem. Eventually I put all the data in excel and read the excel sheet.
Here is the implementation:
copy-past the country code table from http://countrycode.org/ to Microsoft Excel file.
Save the Excel file as 97-2003 compatible (.xls) in \res\raw\countrycode_org.xls
Download JExcelApi from here
Use the following class to read the file:
public class CountryCodes {
private HashMap mCountryByName = new HashMap();
private HashMap mCountryByCode = new HashMap();;
private ArrayList mCountries = new ArrayList();
public void addCountry(String countryName,String ISO_code,String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
Country country = new Country();
country.Name = countryName;
country.Code = countryCode;
country.ISO_code = ISO_code;
mCountryByName.put(countryName, country);
mCountryByCode.put(countryCode, country);
mCountries.add(country);
return;
}
public Country getCountryByCode(String countryCode){
countryCode = PhoneNumberUtil.normalizeDigitsOnly(countryCode);
return mCountryByCode.get(countryCode);
}
public Country getCountryByName(String countryName){
return mCountryByName.get(countryName);
}
public Country getCountryByIsoCode(String ISO_code){
ISO_code = ISO_code.toUpperCase();
for (Country country:mCountries){
String [] strArr = country.ISO_code.split("/| ");
for (String s:strArr){
if (ISO_code.equals(s))
return country;
}
}
return null;
}
public String[] getCountryNamesList(){
String[] res = new String [mCountries.size()];
int i=0;
for (Country c:mCountries){
res[i] = c.Name;
i++;
}
return res;
}
public void readCountryCodesFromExcelWorkbook()
{
Context context = GlobalData.getInstance().getApp();
Workbook mWorkbook;
InputStream myRawResource = context.getResources().openRawResource(R.raw.countrycode_org);
if (myRawResource == null)
Toast.makeText(context,"XML file not found",Toast.LENGTH_LONG).show();
else
try {
WorkbookSettings ws = new WorkbookSettings();
ws.setEncoding("Cp1252");
mWorkbook = Workbook.getWorkbook(myRawResource);
//ArrayList<String[]> currentSheet = new ArrayList<String[]>();
Sheet sheet = mWorkbook.getSheet(0);
int rowsNum = sheet.getRows();
for (int rowNum = 1; rowNum < rowsNum; rowNum++) {
//Log.d("RowNum", ""+rowNum);
int colsNum = sheet.getColumns();
String[] strArr = new String[colsNum];
boolean rowIsFull = true;
for (int colNum = 0; colNum < colsNum; colNum++) {
strArr[colNum] = sheet.getCell(colNum, rowNum).getContents();
if (strArr[colNum].length() == 0)
rowIsFull = false;
}
if (rowIsFull)
addCountry(strArr[0],strArr[1],strArr[2]);
}
} catch (BiffException e) {
Toast.makeText(context,"Error Reading xml file: BiffException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
} catch (IOException e) {
Toast.makeText(context,"Error Reading xml file: IOException",Toast.LENGTH_LONG).show();
e.printStackTrace();
return ;
}
}
public Country[] getCountries(){
return mCountries.toArray(new Country[0]);
}
public class Country {
public String Name;
public String Code;
public String ISO_code;
}
}
Step-1
You can get country calling code as well as its ISO name in the following URL
http://en.wikipedia.org/wiki/List_of_country_calling_codes
or
http://www.unc.edu/~rowlett/units/codes/country.htm
Step-2 You can get page source of that file using java program. You will get file in HTMl format
Step-3 you can convert those HTML files into XML format using any of available parsers. see Open Source HTML Parsers in Java
Step-4 Form the phone number you can get the calling code. Example if the number is "1-319-491-6338" then calling code is 1
Step-5 Match this calling code against the calling code and country name list that you have got from XML parser. In this way you can get iso country