Hello I am pretty basic new to Java and Android world. Currenty working on a project of my own. Basically I need to show permission names of a specific app on a ListView.
Though I already implemented it and it working well. but on my list view I am getting permission names as something like "android.permission.MANAGE_ACCOUNTS"
But I want to show that string as "Manage Accounts"
Here is the code block that I have written.
final PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
try {
PackageInfo packageInfo = pm.getPackageInfo(appPackageName, PackageManager.GET_PERMISSIONS);
//Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if(requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
Log.d("test", requestedPermissions[i]);
itemname.add(requestedPermissions[i]);
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
It lists permission names as "android.permission.PERMISSION_NAME" or something like that. But I want to show them as a bit like human readable. for example showing "android.permission.PERMISSION_NAME" as "Permission Name".
Converting a string like "android.permission.MANAGE_ACCOUNTS" to "Manage Accounts" is possible. But it cannot be safe to apply a same algorithm (removing android.permission., then replacing _ whit space and the convert string to lowercase) to all permissions.
If you are sure that all permission names follow a same rule you can do something like this:
String permissionName = "android.permission.PERMISSION_NAME";
permissionName = permissionName.replace("android.permission.", "");
String[] words = permissionName.split("_");
String newPermissionName = "";
for(String word: words){
newPermissionName+= word.substring(0,1) + word.substring(1).toLowerCase() + " ";
}
(Maybe it is not the best way but it works)
Also because the permissions are static, you can use a HashMap to store a name for each permission:
map.put("android.permission.MANAGE_ACCOUNTS", "Manage Accounts");
By this way you are not worry about different permission styles and also you can use your desired permission name.
final PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
try {
PackageInfo packageInfo = pm.getPackageInfo("ashish.app.com.getpremissions", PackageManager.GET_PERMISSIONS);
//Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if (requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
Log.d("test", requestedPermissions[i]);
String[] last = requestedPermissions[i].toString().split("\\.");
String lastOne = last[last.length - 1];
if (!lastOne.contains("_")) {
Log.e("app", "permissions is----" + lastOne.toLowerCase());
} else {
String[] permissions = lastOne.split("_");
StringBuffer sb = new StringBuffer();
for (int index = 0; index < permissions.length; index++) {
sb.append(permissions[index].toLowerCase());
sb.append(" ");
}
Log.e("app", "permissions is----" + sb.toString());
}
// itemname.add();
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
Related
I have a CSV file with the following information:
2,Cars
5,Cars
5,Planes
5,Boats
10,Planes
10,Boats
28,Planes
I want to split the numbers from the type of transportation. How can I count the total of cars + planes + boats to be '3' and not '7'?
I am using the following Java code that someone else provided to split the CSV:
try {
BufferedReader br2 = new BufferedReader(new FileReader("transport.csv"));
System.out.println("\nTESTING");
String sCurrentLine2;
java.util.HashMap<String, String>();
while ((sCurrentLine2 = br2.readLine()) != null) {
String[] information2 = sCurrentLine2.split(",");
String transCode = information2[1];
System.out.println(transCode);
}
} catch (IOException e) {
e.printStackTrace();
}
In the array String transCode = information2[1]; when I change to 0 it will give the numbers, when I change to 1 gives the names.
while((sCurrentLine2 = br2.readLine()) != null{
String[] entries = sCurrentLine2.split(",");
Set<String> types = new Hashset<>();
for(int i = 0; i < entries.length; i++){
String[] entry = entries[i].split(" ");
types.add(entry[0]);
}
System.out.println(types.size());
}
I modified the code you provided. Maybe there is another way to do it better, but this is what I did. I forced it a little and gave '3' as result. But it should have done it counting the words not considering duplicated.
while ((line2 = br2.readLine()) != null) {
String[] entries = line2.split(",");
for (int i = 0; i < entries.length; i++) {
String[] entry = entries[i].split(" ");
termsDup.add(entry[0]);
}
}
System.out.println(termsDup.size()-4);
I am trying to load a file from a previously saved values from an editText. On the next load I am trying to make the fields populated with the previously entered data using split to get everything on that line after the split, as seen in this picture. For some reason every time I try and split with .split("Name") everything between the quotation marks goes black instead of green and I get that #NonNull.
public void loadList(){
loadText = new ArrayList<String>();
Context context = getApplicationContext();
File file = new File (path + "/personalProfile.txt");
try{
editText_name.setText("");
editText_dob.setText("");
editText_mobile.setText("");
editText_journal.setText("");
editText_medical.setText("");
String line = "";
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
while((line = reader.readLine()) != null)
{
loadText.add(line);
}public void loadList(){
String loadedText = String.valueOf(loadText.get(0));
String rname = "Hello: Name";
String helloName [] = rname.split("Hello: ");
//String nameToText [] = loadedText.split("");
for(int i = 0; i < loadText.size(); i++){
editText_name.setText(String.valueOf(loadText.get(0).split("Name:")));
}
//set all the editText values accordingly
}catch (Exception e){
System.out.println("Error " + e);
}
}
There is no string you have entered that would satisfy "Name: " in
"Hello: Name"
And I think what you want in your for loop is not element 0 all the time for your arraylist, it should be:
for (int i = 0; i < loadText.size(); i++){
editText_name.setText(String.valueOf(loadText.get(i).split("Hello: ")));
}
But the more correct way would be:
for (int i = 0; i < loadText.size(); i++){
editText_name.setText(String.valueOf(loadText.get(i).replace("Hello: ")));
}
If you just wanted the name.
However I think the problem with not retrieving the values is you have to add:
#Override
public void onSaveInstanceState(Bundle out) {
out.putStringArrayList("loadValues", loadValues);
}
and to retrieve them:
#Override
public void onRestoreInstanceState(Bundle in) {
loadValues = in.getStringArrayList("loadValues");
//call method to set values again
}
Let me explain my problem.
(I'm new to java so maybe this type of thing might be easy but I can't figure it out !)
I have a JSONObject which looks like :
{
notes:[
{
"scolaryear":2013,
"codemodule":"B-CPE-042",
"titlemodule":"B1 - Unix & C Lab Seminar",
"codeinstance":"NCE-1-1",
"codeacti":"acti-134315",
"title":"Piscine Jour 1",
"date":"2013-10-04 13:33:51",
"correcteur":"ramassage-tek",
"final_note":0,
"comment":"Ex_00 -> output differs"
},
{} // And so on ..
]
}
For now I can get all the data doing something like :
try {
// Pulling items from the array
JSONArray notesArr = jsonObject.getJSONArray("notes");
try {
ListView lv = (ListView) _modulesActivity.findViewById(R.id.listView);
List < String > notesList = new ArrayList < String > ();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
String code_module = tmp.getString("codemodule");
String module = tmp.getString("titlemodule");
String title = tmp.getString("title");
String final_note = tmp.getString("final_note");
String year = tmp.getString("scolaryear");
String comment = tmp.getString("comment");
String display = year + " | " + title + " | " + final_note;
notesList.add(display);
}
ArrayAdapter < String > arrayAdapter = new ArrayAdapter < String > (
_mainContext, android.R.layout.simple_list_item_1, notesList);
lv.setAdapter(arrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
So with that technique I got all my data in one array and an only listView which looks like :
2014 | PROJECT #1 | 13/20
2015 | PROJECT #2 | 20/20
But I need to order my data with year, and module.
It would look like :
> YEAR (year)
> TITLE OF MODULE (module) - MODULE CODE (codemodule)
> PROJECT NAME (title) | MARK (final_note)
- COMMENT (comment)
You have a first header with the year, when you click on a year, you can see all the module :
> MODULE #1
> MODULE #2
...
And when you click on a module you can see all project :
> PROJECT #1 | MARK : 20
> PROJECT #2 | MARK : 13
...
And finally when you click on a project you can see the comment !
^ PROJECT #1 | MARK : 20
- Great project .. bla bla bla
(or maybe display a popup window which contains the comments if it's possible)
I know it may be a complexe thing but I really want to achieve that !
Thanks in advance for your help !
In my opinion you have two possibilities:
Implement a Note Java object, during the form initialize this objects and put them in an ArrayList. In the end sort it with some algorithm.
For example it would look like:
List<Note> notesList = new ArrayList<Note>();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
noteListe.add(new Note(tmp.getString("codemodule"), tmp.getString("titlemodule"),...);
}
Now sort it with a proper method and in the end print it maybe overriding toString() Note method.
If possible sort the JsonObjectArray when you create it.
Hope it can help you
So I found a solution !
I used this library : https://github.com/bmelnychuk/AndroidTreeView
Here is my Code :
try {
// Pulling items from the array
TreeNode root = TreeNode.root();
TreeNode child;
String year = "YEAR";
String moduleName = "";
YearHolder.IconTreeItem nodeItem = new YearHolder.IconTreeItem(1, year);
ModuleHolder.IconTreeItem nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
TreeNode parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
TreeNode parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
JSONArray modArr = jsonObject.getJSONArray("notes");
try {
for (int i = 0; i < modArr.length(); i++) {
JSONObject tmp = modArr.getJSONObject(i);
/*String title = tmp.getString("title");*/
String final_note = tmp.getString("final_note");
String newModuleName = tmp.getString("titlemodule");
String newYear = tmp.getString("scolaryear");
if (!(newYear.equals(year))) {
year = newYear;
nodeItem = new YearHolder.IconTreeItem(1, year);
parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
root.addChild(parent);
}
if (!(newModuleName.equals(moduleName))) {
moduleName = newModuleName;
nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
parent.addChild(parentModule);
}
NoteHolder.IconTreeItem nodeNote = new NoteHolder.IconTreeItem(1, final_note);
child = new TreeNode(nodeNote).setViewHolder(new NoteHolder(_mainContext));
parentModule.addChildren(child);
/*String display = year + " | " + title + " | " + final_note;*/
}
AndroidTreeView tView = new AndroidTreeView(_notesActivity, root);
_notesActivity.setContentView(tView.getView());
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
YearHolder class looks like this :
public class YearHolder extends TreeNode.BaseNodeViewHolder<YearHolder.IconTreeItem> {
public YearHolder (Context context ) {
super(context);
}
#Override
public View createNodeView(TreeNode node, IconTreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.custom_notes_view, null, false);
TextView tvValue = (TextView) view.findViewById(R.id.text_title);
tvValue.setText(value.text);
return view;
}
public static class IconTreeItem {
public int icon;
public String text;
IconTreeItem(int icon_, String text_) {
this.icon = icon_;
this.text = text_;
}
}
}
Super easy to use !
I am using this code to get a list of permission required by a specific application. I would like to create a Preference for each permission requested. How can I do this? The code is:
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(myPackageName, PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = packageInfo.requestedPermissions;
if ( requestedPermissions != null ) {
for (int i = 0; i < requestedPermissions.length; i++) {
permission.setSummary(requestedPermissions[i] + "\n");
}
}
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}
Mario i ´d like to know for what are you going to create preferences with the name of App´s permissions, but here you got a solution.
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(myPackageName, PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = packageInfo.requestedPermissions;
if ( requestedPermissions != null ) {
for (int i = 0; i < requestedPermissions.length; i++) {
//permission.setSummary(requestedPermissions[i] + "\n");
//method to create a preference with the name of your permission.
setPreference(this, requestedPermissions[i]);
}
}
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}
Method to create a preference .
public static void setPreference(Context context, String preferenceName)
{
SharedPreferences settings = context.getSharedPreferences(preferenceName, 0);
SharedPreferences.Editor editor = settings.edit();
//Add a key to this preference and his value.
editor.putString(preferenceName+"_value", "Value stored in preference called: " + preferenceName);
editor.commit();
}
create a method to read the value stored in your preferences
public static String getPreference(Context context, String preferenceName){
SharedPreferences settings = context.getSharedPreferences(preferenceName, 0);
return settings.getString(preferenceName+"_value", "");
}
then you can read values stored in your preferences, for example, read a value stored in a preference called
"android.permission.INTERNET"
:
Log.i("Preferences", getPreference(this,"android.permission.INTERNET"));
example Displayin data in Toast:
Toast.makeText(this, "the value stored in \"android.permission.INTERNET\" preference is: " + getPreference(this,"android.permission.INTERNET"), Toast.LENGTH_LONG).show();
I'd like to get the amount on internal and external space in a device and after going to through a couple of posts on StackOverflow, I found that this is easy. I can get the amount of internal space using this:
StatFs sfsInternal = new StatFs(Environment.getRootDirectory().getAbsolutePath());
return Long.valueOf(sfsInternal.getBlockCount()) * Long.valueOf(sfsInternal.getBlockSize());
...and I can get the amount of external space using this:
StatFs sfsExternal = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
return Long.valueOf(sfsExternal.getBlockCount()) * Long.valueOf(sfsExternal.getBlockSize());
When I read about "internal" storage, I assumed that it would be the non-removable onboard storage on the device and "external" would the removable flash card storage but this hasn't been case entirely.
I found that Samsung devices e.e. Galaxy Note 2, show a large chunk of the internal storage as external. Here's an answer that discusses the same thing. https://stackoverflow.com/a/12087556/304151
How can I get the amount of internal storage (on-board and non-removable) and the amount of external storage (flash and removable) while factoring in the edge cases of Samsung's Galaxy devices. I'm yet to find an answer on StackOverflow that provides a complete working solution for this scenario. My code is for API level 17.
Thanks.
Here is the code to get available free space on different devices i have tested that code on samsung GALAXY Tab7 2.2 Froyo and Nexus 7 4.2.2 Jelly Beans
// calculate frespace on external storage
public static int getExternalStorageFreeSpace(String storagePath)
{
try
{
File file = new File(storagePath);
StatFs stat = new StatFs(file.getPath());
double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize();
int valueinmb = (int) (sdAvailSize / 1024) / 1024;
return valueinmb;
}
catch (Exception e)
{
System.out.println("Message//////" + e.getMessage() + "Cause555555555555" + e.getCause());
}
return 0;
}
to diffrentiate between internal and external storages i have used this class and some logic
public class GetRemoveableDevices
{
private final static String TAG = "GetRemoveableDevice";
public GetRemoveableDevices()
{
}
public static String[] getDirectories()
{
Log.d(TAG, "getStorageDirectories");
File tempFile;
String[] directories = null;
String[] splits;
ArrayList<String> arrayList = new ArrayList<String>();
BufferedReader bufferedReader = null;
String lineRead;
try
{
arrayList.clear(); // redundant, but what the hey
bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));
while ((lineRead = bufferedReader.readLine()) != null)
{
Log.d(TAG, "lineRead: " + lineRead);
splits = lineRead.split(" ");
// System external storage
if (splits[1].equals(Environment.getExternalStorageDirectory().getPath()))
{
arrayList.add(splits[1]);
Log.d(TAG, "gesd split 1: " + splits[1]);
continue;
}
// skip if not external storage device
if (!splits[0].contains("/dev/block/"))
{
continue;
}
// skip if mtdblock device
if (splits[0].contains("/dev/block/mtdblock"))
{
continue;
}
// skip if not in /mnt node
if (!splits[1].contains("/mnt"))
{
continue;
}
// skip these names
if (splits[1].contains("/secure"))
{
continue;
}
if (splits[1].contains("/mnt/asec"))
{
continue;
}
// Eliminate if not a directory or fully accessible
tempFile = new File(splits[1]);
if (!tempFile.exists())
{
continue;
}
if (!tempFile.isDirectory())
{
continue;
}
if (!tempFile.canRead())
{
continue;
}
if (!tempFile.canWrite())
{
continue;
}
// Met all the criteria, assume sdcard
arrayList.add(splits[1]);
}
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
}
}
}
// Send list back to caller
if (arrayList.size() == 0)
{
arrayList.add("sdcard not found");
}
directories = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++)
{
directories[i] = arrayList.get(i);
}
return directories;
}
}
now i am showing you my logic
String[] dirs = GetRemoveableDevices.getDirectories();
ArrayList<String> directories=new ArrayList<String>();
for(String directory:dirs)
{
if(!directory.contains("."))
directories.add(directory);
}
String externalStorage = "";
String internalStorage = "";
if (directories.size()>= 2)
{
internalStorage = directories.get(0).toString();
externalStorage = directories.get(1).toString();
}
else if (directories.size() < 2)
{
internalStorage = directories.get(0).toString();
externalStorage = null;
}
hope it will be helpful
"Internal storage" is for privately held data. It's called internal because it's relative to the application itself. It's for sandboxing the application's data and keeping it private.
Environment.getRootDirectory() gets the phone's system folder. Which is not internal storage, but external storage.
External storage is for publicly shared data, external to the application.
Since mounting naming conventions vary greatly between phones, it can be difficult to differentiate from an SD card and normal onboard directories. But generally, the sd card is mounted to the directory /sdcard/.
I found some code that does this on this blog post.
package com.sapien.music.importer.util;
import java.io.File;
#SuppressLint("NewApi")
public class StorageOptions {
public static String[] labels;
public static String[] paths;
public static int count = 0;
private static Context sContext;
private static ArrayList<String> sVold = new ArrayList<String>();
public static void determineStorageOptions(Context context) {
sContext = context.getApplicationContext();
readVoldFile();
testAndCleanList();
setProperties();
}
private static void readVoldFile() {
/*
* Scan the /system/etc/vold.fstab file and look for lines like this:
* dev_mount sdcard /mnt/sdcard 1
* /devices/platform/s3c-sdhci.0/mmc_host/mmc0
*
* When one is found, split it into its elements and then pull out the
* path to the that mount point and add it to the arraylist
*
* some devices are missing the vold file entirely so we add a path here
* to make sure the list always includes the path to the first sdcard,
* whether real or emulated.
*/
sVold.add("/mnt/sdcard");
try {
Scanner scanner = new Scanner(new File("/system/etc/vold.fstab"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (element.contains("usb"))
continue;
// don't add the default vold path
// it's already in the list.
if (!sVold.contains(element))
sVold.add(element);
}
}
} catch (Exception e) {
// swallow - don't care
e.printStackTrace();
}
}
private static void testAndCleanList() {
/*
* Now that we have a cleaned list of mount paths, test each one to make
* sure it's a valid and available path. If it is not, remove it from
* the list.
*/
for (int i = 0; i < sVold.size(); i++) {
String voldPath = sVold.get(i);
File path = new File(voldPath);
if (!path.exists() || !path.isDirectory() || !path.canWrite())
sVold.remove(i--);
}
}
private static void setProperties() {
/*
* At this point all the paths in the list should be valid. Build the
* public properties.
*/
ArrayList<String> labelList = new ArrayList<String>();
int j = 0;
if (sVold.size() > 0) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD)
labelList.add("Auto");
else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
if (Environment.isExternalStorageRemovable()) {
labelList.add(sContext
.getString(R.string.text_external_storage) + " 1");
j = 1;
} else
labelList.add(sContext
.getString(R.string.text_internal_storage));
} else {
if (!Environment.isExternalStorageRemovable()
|| Environment.isExternalStorageEmulated())
labelList.add(sContext
.getString(R.string.text_internal_storage));
else {
labelList.add(sContext
.getString(R.string.text_external_storage) + " 1");
j = 1;
}
}
if (sVold.size() > 1) {
for (int i = 1; i < sVold.size(); i++) {
labelList.add(sContext
.getString(R.string.text_external_storage)
+ " " + (i + j));
}
}
}
labels = new String[labelList.size()];
labelList.toArray(labels);
paths = new String[sVold.size()];
sVold.toArray(paths);
count = Math.min(labels.length, paths.length);
/*
* don't need these anymore, clear the lists to reduce memory use and to
* prepare them for the next time they're needed.
*/
sVold.clear();
}
try this out:
private boolean is_sdCardSaveToUse(){
/**default disk cache size in bytes*/
final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; //10 MB
/**get sdCard state*/
String sdCardState = Environment.getExternalStorageState();
/**check if the sdCard is mounted*/
/**check if we can write to sdCard*/if (Environment.MEDIA_MOUNTED.equals(sdCardState)) {
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(sdCardState)) {
Log.d("sdCard", "mounted readOnly");
} else {
Log.d("sdCard", "mounted readWrite");
/**get free usable space in bytes */
long freeUsableSpace = Environment.getExternalStorageDirectory().getUsableSpace();
int temp = Math.round(((float) freeUsableSpace / 1024) / 1024); //convert from bytes to MB.
Log.d("usableSpace= ", Integer.toString(temp) + " MB");
if (freeUsableSpace > DEFAULT_DISK_CACHE_SIZE){
return true;
} else {
Log.d("sdCard","not enough space");
return false;
}
}
} else{
Log.d("sdCard","not mounted");
return false;
}
return false;
}