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();
Related
I have unchecked the checkbox(per item) to remove it . I am using to sharedpreferences with HashSet concept. I want to pass arraylist value from one page to another page. What i do what is my mistake some one help me.
My code is:
adapterpage.java
public static final String MY_PREFS_NAME = "";
#Override
public void onClick(View view) {
boolean isChecked = mainHolder.chekenitem.isChecked();
// arr=getResources().getStringArray( mainHolder.txtenimgid.getText().toString());
// boolean isChecked = mainHolder.chekenitem.isChecked();
int i;
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
// editor.putString("key_name",itemId );
// editor.apply();
// }
} else {
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
// set.remove(addmembers);
addmembers.remove(k);
edit.remove(addmembers.get(k));
edit.commit();
break;
}
}
You are making mistake here ...
for (j = 0; j < addmembers.size(); j++) {
//set.addAll(addmembers);this will add every time whole data of list into set
set.add(addmembers.get(j));
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
And also here while removing change to this...
edit.remove("yourKey");
Try this code:
public static final String MY_PREFS_NAME = "";
#Override
public void onClick(View view) {
boolean isChecked = mainHolder.chekenitem.isChecked();
// arr=getResources().getStringArray( mainHolder.txtenimgid.getText().toString());
// boolean isChecked = mainHolder.chekenitem.isChecked();
int i;
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
} else {
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
edit.remove("yourKey");
edit.commit();
}
}
what you have to do is that whenever the item is checked you are simply clearing the shared pref value. Hope it helps
thanks to all, i got the solution in my code working fine.
String itemId1 = mainHolder.txtenimgid.getText().toString();
SharedPreferences prefs=view.getContext().getSharedPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor edit=prefs.edit();
Set<String> set = new HashSet<String>();
try {
restart:
if (isChecked) {
addmembers.add(itemId1);
for (j = 0; j < addmembers.size(); j++) {
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
Toast.makeText(view.getContext(), "Clicked on Checkbox addmembers[pos] : " + addmembers.get(j) + " Item Id is " + itemId1
, Toast.LENGTH_LONG).show();
}
} else {
//editor.remove("username").commit();
for(int k=0;k<=addmembers.size();k++){
if(addmembers.get(k).equals(itemId1)){
addmembers.remove(k);
edit.remove("yourKey");
set.addAll(addmembers);
edit.putStringSet("yourKey", set);
edit.commit();
break restart;
}
}
}
}
catch (Exception ex){
ex.toString();
}
the code is working fine to me.
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();
}
I'm using flexicapture processor for recognizing my document. I've a case where i've a document with multiple pages i.e. a document have multiple images and each image is need to recognize.
I'm following below procedure to achieve my general task ,either one image in document or multiple image in a document;
create a processor
add document definition file or afl file
run recognition as IDocument document = processor.RecognizeNextDocument();
But when it return a document, document, it has only one page,which is the first page of document, why is it so?
On the other case, if i use project instead processor,IProject, with below procedure
create a project
get batches from project project.getBatches(),
add a document (that have multiple page) to batch
recognize them
The i've all pages information of document,IDocuments documents = batch.getDocuments(),
How i can achieve the same task wit processor? I want processor recognize all pages in a document and return a document with all pages in it. ?
if something is unclear, pls ask for more information.
Please reply asap...
Code :1 using flexicapture processor
/**
*
*/
/**
* #author Nitin
*
*/
import java.sql.BatchUpdateException;
import com.abbyy.FCEngine.*;
public class FlexicaputreVerificationUsingProcessor {
private static Object verificationWorkSet(Object object) {
// TODO Auto-generated method stub
return null;
}
private static void trace( String txt )
{
System.out.println( txt );
}
static private String samplesFolder;
static private String projectFolder;
static private String serialNumber;
static private String dllPath;
static {
samplesFolder = "C:\\ProgramData\\ABBYY\\SDK\\10\\FlexiCapture Engine\\Samples\\";
projectFolder = "C:\\Users\\Nitin\\FlexicaptureTest\\flexiverificationtest" ;
try {
java.io.FileInputStream file = new java.io.FileInputStream( samplesFolder + "SampleConfig\\SamplesConfig.txt" );
java.io.BufferedReader reader = new java.io.BufferedReader( new java.io.InputStreamReader( file ) );
serialNumber = reader.readLine();
dllPath = reader.readLine();
file.close();
} catch( java.io.IOException e ) {
System.out.println( e.getMessage() );
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
// Load Engine
try {
trace("Loading engine");
IEngineLoader engineLoader= Engine.CreateEngineOutprocLoader();
IEngine engine = engineLoader.Load(serialNumber,dllPath);
try {
// Create and configure FlexiCaptureProcessor
trace("Creating and configureing FlexiCaptureProcessor");
IFlexiCaptureProcessor processor = engine.CreateFlexiCaptureProcessor();
processor.AddDocumentDefinitionFile( projectFolder + "\\Document_Definition_1.fcdot" );
trace("Adding images/pdf to processor");
final int fileCount = 1 ;
processor.AddImageFile(projectFolder + "\\don't upload to big .pdf");
engine.EnableRecognitionVariants( true );
trace("Creating Document collection");
IDocumentsCollection documentsCollection = engine.CreateDocumentsCollection();
trace( "Reconizing Images/pdfs..." );
int totalErrors = 0 ;
for ( int iterator = 0 ; iterator<fileCount; iterator++ ){
trace("Recongnizing image/pdf number: " +(iterator+1));
IDocument document = processor.RecognizeNextDocument();
trace("Getting last processing error for checksum");
IProcessingError lastProcessingError = processor.GetLastProcessingError() ;
if ( lastProcessingError !=null)
{
String errormsg = lastProcessingError.MessageText();
totalErrors++;
trace("Error occured while recognizeing document, Document number: "+(iterator+1)+ " with Error msg: "+errormsg);
//since we are not handling error (right now) so moving to next document for recognization
processor.ResumeProcessing(false);
}else {
trace("No error occured while recognization of document number : "+(iterator+1));
}
trace("Adding documents in Documents collection");
documentsCollection.Add(document);
}
if ( totalErrors == fileCount){
trace("Facing Error for all document while recongnization");
return ;
}
trace("Creaing Verification session");
try {
IVerificationSession verificationSession = engine.CreateVerificationSession(documentsCollection) ;
try {
//enabling context verification
verificationSession.getOptions().setVerifyFields(true);
//disabling group verification
verificationSession.getOptions().setVerifyBaseSymbols(false);
verificationSession.getOptions().setVerifyExtraSymbols(false);
try {
trace("Get NextWork Set");
IVerificationWorkSet verificationWorkSet = verificationSession.NextWorkSet();
if ( verificationWorkSet == null){
trace("first verificationWork set is null");
}else {
//process each work set in Verification session
trace("Processing Work Set");
while ( verificationWorkSet != null ){
try{
trace("Geting Verification group");
//get next group for verification
IVerificationGroup verificationGroup = verificationWorkSet.NextGroup();
if ( verificationGroup == null ){
trace("First verification group is null");
}else {
trace("processing each group of a workset");
//processing each group of a work set
while ( verificationGroup!= null){
int verificationObjectInAGroupCount = verificationGroup.getCount();
trace("Total number of verification object: " +verificationObjectInAGroupCount);
for ( int iterator = 0; iterator<verificationObjectInAGroupCount; iterator++){
trace ( "getting and Processing "+(iterator +1 ) + " verification object of A group");
//getting verification object
IVerificationObject verificationObject = verificationGroup.getElement(iterator);
if ( verificationObject == null){
trace("verification object is null");
}else {
if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Group ) {
IGroupVerificationObject groupVerificationObject = verificationObject.AsGroupVerificationObject();
if ( groupVerificationObject == null){
System.out.println("group verification object is null ");
}
}else if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Context) {
IContextVerificationObject contextVerificationObject = verificationObject.AsContextVerificationObject();
if ( contextVerificationObject == null){
trace("ContextVerification object is null");
}else {
IField field = contextVerificationObject.getField();
if ( field == null){
trace("field getting null");
}else {
System.out.println(" field full name: " +field.getFullName() + "\n Name: " +field.getName());
IFieldValue fieldValue = field.getValue();
if ( fieldValue == null){
trace("Field Value is Null");
}else {
trace ( "getting text from field value");
IText text = fieldValue.getAsText() ;
if ( text == null){
trace("text getting null in field value");
}else {
int wordCount = text.getRecognizedWordsCount() ;
trace("recognized word count: "+wordCount);
//getting words from text
for ( int wordIndex = 0 ; wordIndex<wordCount; wordIndex++ ){
trace ("processing word number :" +wordIndex);
IRecognizedWordInfo recognizedWordInfo = engine.CreateRecognizedWordInfo() ;
if ( recognizedWordInfo == null){
trace("Can't create recognizedWordInfo object using engine");
}else {
text.GetRecognizedWord(wordIndex, -1, recognizedWordInfo);
//getting characters from word
for (int characterIndex = 0 ; characterIndex<recognizedWordInfo.getText().length(); characterIndex++ ){
trace("processing character number : " +characterIndex);
IRecognizedCharacterInfo recognizedCharacterInfo = engine.CreateRecognizedCharacterInfo();
if ( recognizedCharacterInfo == null) {
trace("can't create recognizedCharacterInfo object");
}else {
recognizedWordInfo.GetRecognizedCharacter(characterIndex, -1, recognizedCharacterInfo);
System.out.println(" Character: " + recognizedCharacterInfo.getCharacter());
System.out.println(" Confidence level : " +recognizedCharacterInfo.getCharConfidence());
}
}
}
}
}
System.out.println(" Field Value : " +fieldValue.getAsString());
}
}
}
}
}
}
trace("Geting next Verification group");
verificationGroup = verificationWorkSet.NextGroup();
}
}
}catch (Exception e){
trace("Exception occured in getting next work group");
e.printStackTrace();
}
trace("Get next worksets");
//get next work set
verificationWorkSet = verificationSession.NextWorkSet();
}
}
}catch (Exception e){
e.printStackTrace();
}
}finally {
trace("closing Verification object");
verificationSession.Close();
}
} catch (Exception e) {
trace("Exception occured in creating verification sessions");
}
}catch (Exception e){
trace ("Exception occured in");
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
trace("unloading Engine");
Engine.Unload();
}
}
}
Code : 2 using project
import java.io.File;
import java.io.IOException;
import java.sql.BatchUpdateException;
import com.abbyy.FCEngine.*;
public class VerificationStep {
//same as above
public static void main( String[] args )
{
// Load Engine
try {
trace("Loading engine");
IEngineLoader engineLoader= Engine.CreateEngineOutprocLoader();
IEngine engine = engineLoader.Load(serialNumber,dllPath);
try{
IProject project = engine.OpenProject( projectFolder + "\\flexitest.fcproj" );
try {
IBatch batch = null ;
trace( "Creating Batch..." );
IBatches batchs = project.getBatches();
if (batchs == null || batchs.getCount() == 0){
batch = project.getBatches().AddNew("TestBatch");
}
batch = batchs.getElement(0);
assert(batch == null);
try{
trace("opening batch");
batch.Open();
trace( "Adding pdfs..." );
batch.AddImage(projectFolder + "\\don't upload to big .pdf");
trace( "Reconizing pdfs..." );
batch.Recognize(null, RecognitionModeEnum.RM_ReRecognizeAll,null);
trace("Creating Verification object");
try {
IVerificationSession verificationSession = project.StartVerification(null);
try {
//enabling context verification
verificationSession.getOptions().setVerifyFields(true);
//disabling group verification
verificationSession.getOptions().setVerifyBaseSymbols(false);
verificationSession.getOptions().setVerifyExtraSymbols(false);
try {
trace("Get NextWork Set");
IVerificationWorkSet verificationWorkSet = verificationSession.NextWorkSet();
if ( verificationWorkSet == null){
trace("first verificationWork set is null");
}else {
//process each work set in Verification session
trace("Processing Work Set");
while ( verificationWorkSet != null ){
try{
trace("Geting Verification group");
//get next group for verification
IVerificationGroup verificationGroup = verificationWorkSet.NextGroup();
if ( verificationGroup == null ){
trace("First verification group is null");
}else {
trace("processing each group of a workset");
//processing each group of a work set
while ( verificationGroup!= null){
int verificationObjectInAGroupCount = verificationGroup.getCount();
trace("Total number of verification object: " +verificationObjectInAGroupCount);
for ( int iterator = 0; iterator<verificationObjectInAGroupCount; iterator++){
trace ( "getting and Processing "+(iterator +1 ) + " verification object of A group");
//getting verification object
IVerificationObject verificationObject = verificationGroup.getElement(iterator);
if ( verificationObject == null){
trace("verification object is null");
}else {
if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Group ) {
IGroupVerificationObject groupVerificationObject = verificationObject.AsGroupVerificationObject();
if ( groupVerificationObject == null){
System.out.println("group verification object is null ");
}
}else if ( verificationObject.getType() == VerificationObjectTypeEnum.VOT_Context) {
IContextVerificationObject contextVerificationObject = verificationObject.AsContextVerificationObject();
if ( contextVerificationObject == null){
trace("ContextVerification object is null");
}else {
IField field = contextVerificationObject.getField();
if ( field == null){
trace("field getting null");
}else {
System.out.println(" field full name: " +field.getFullName() + "\n Name: " +field.getName());
IFieldValue fieldValue = field.getValue();
if ( fieldValue == null){
trace("Field Value is Null");
}else {
trace ( "getting text from field value");
IText text = fieldValue.getAsText() ;
if ( text == null){
trace("text getting null in field value");
}else {
int wordCount = text.getRecognizedWordsCount() ;
trace("recognized word count: "+wordCount);
//getting words from text
for ( int wordIndex = 0 ; wordIndex<wordCount; wordIndex++ ){
trace ("processing word number :" +wordIndex);
IRecognizedWordInfo recognizedWordInfo = engine.CreateRecognizedWordInfo() ;
if ( recognizedWordInfo == null){
trace("Can't create recognizedWordInfo object using engine");
}else {
text.GetRecognizedWord(wordIndex, -1, recognizedWordInfo);
//getting characters from word
for (int characterIndex = 0 ; characterIndex<recognizedWordInfo.getText().length(); characterIndex++ ){
trace("processing character number : " +characterIndex);
IRecognizedCharacterInfo recognizedCharacterInfo = engine.CreateRecognizedCharacterInfo();
if ( recognizedCharacterInfo == null) {
trace("can't create recognizedCharacterInfo object");
}else {
recognizedWordInfo.GetRecognizedCharacter(characterIndex, -1, recognizedCharacterInfo);
System.out.println(" Character: " + recognizedCharacterInfo.getCharacter());
System.out.println(" Confidence level : " +recognizedCharacterInfo.getCharConfidence());
}
}
}
}
}
System.out.println(" Field Value : " +fieldValue.getAsString());
}
}
}
}
}
}
verificationGroup = verificationWorkSet.NextGroup();
}
}
}catch (Exception e){
e.printStackTrace();
}
//get next work set
verificationWorkSet = verificationSession.NextWorkSet();
}
}
}catch (Exception e){
e.printStackTrace();
}
}finally {
verificationSession.Close();
}
}catch (Exception e){
e.printStackTrace();
}
trace ("Getting Documents");
IDocuments documents = batch.getDocuments();
trace ("Getting Fields and printing");
for ( int j = 0 ; j < documents.getCount(); j++){
trace ("Getting documnets:" +(j+1));
IDocument document = documents.getElement(j);
IDocumentDefinition definition = document.getDocumentDefinition();
assert( definition != null );
assert( document.getPages().getCount() == 1 );
trace( "DocumentType: " + document.getDocumentDefinition().getName() );
try {
trace("opening document");
document.Open(true);
IFields fields = document.getSections().Item( 0 ).getChildren();
for( int i = 0; i < fields.getCount(); i++ ) {
IField field = fields.getElement( i );
trace( field.getName() + ": " +
( field.getValue() != null ? field.getValue().getAsString() : "." ) );
}
}finally {
trace("closing document");
document.Close(true);
}
}
}finally {
trace("Closing Batch");
batch.Close();
}
}catch (Exception e){
System.out.println("Exception in creating Batch");
e.printStackTrace();
}
finally {
trace("closing project");
project.Close();
}
}catch (Exception e){
System.out.println("Exception occured while loading project");
e.printStackTrace();
}
}catch (Exception e) {
// TODO: handle exception
System.out.println("Exception occured while loading engine");
e.printStackTrace();
}
finally {
trace("unloading Engine");
Engine.Unload();
}
}
}
Finally i got my solution, actually it recognize correctly, i'm handling them wrong way...
I have to retrieve the total number of permits required by the application, and store this value for use in a second Activity, but without letting it open with the intent. I wrote this code. I will continue to use the Intent to pass data between the Activity. I wonder why she returned as 0. Maybe something wrong in the for loop? I just can not understand where is the error
try {
PackageInfo packageInfo = getActivity().getPackageManager().getPackageInfo(value2, PackageManager.GET_PERMISSIONS);
String[] requestedPermissions = packageInfo.requestedPermissions;
if ( requestedPermissions != null ) {
for ( i = 0; i < requestedPermissions.length; i++) {
permissions.append(requestedPermissions[i]+"\n");
int total = i++;
Intent intent = new Intent();
intent.putExtra("totalPermissions",total);
}
}
}
catch ( PackageManager.NameNotFoundException e ) {
e.printStackTrace();
}
In another PreferenceActivity
Bundle extras = getIntent().getExtras();
if(extras!=null) {
int tot = extras.getInt("totalPermissions");
permissionsPreference.setSummary(""+tot);
In the Summary of Prefence return 0. Why? Where is the error?
Try These Code After For Loop
Intent intent = new Intent();
intent.putExtra("totalPermissions",total);
and then Start Your Activity like startActivity(intent);
I'm using "Calls.CONTENT_URI" content provider. I already retrived column names, but now i would like to get let's say, ALL names from column name "name" in this content provider.
I have code below:
uri = Calls.CONTENT_URI;
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
cursor.moveToFirst();
for(int x=0; x<cursor.getCount(); x++){
s = cursor.getString(x);
Log.i("TUTORIAL", ""+s);
//cursor.moveToNext();
}
But this retrives only one name. I would like to have list of all names saved in my phone like:
John
Peter
Mark
Suzy
.
.
X
But now i got just one name like:
Peter.
Hope i've been clear enough.
What's the problem? Thanks for help in advance.
I think this would help you
ArrayList<String> nameList = new ArrayList<String>();
String[] projection = {"name"};
String selection = null;
String[] selectionArgs = null;
String sort = null;
resolver = getContentResolver();
cursor = resolver.query(uri, projection, selection, selectionArgs, sort);
Log.i("TUTORIAL", "counts :"+cursor.getCount());
String s;
if(cursor.moveToFirst()) {
do {
nameList.add(cursor.getString(0));
//your code
//s = cursor.getString(x);
Log.i("TUTORIAL", ""+cursor.getString(0));
}while(cursor.moveToNext());
}
you can try this one , it's working for me :
public void readContacts() {
Cursor cur = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
}
cur.close();
}
This is the code.
public class MainActivity extends AppCompatActivity {
SimpleCursorAdapter mAdapter;
MatrixCursor mMatrixCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.lv_layout,
null,
new String[] { "name","photo","details"},
new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = (ListView) findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
/** An AsyncTask class to retrieve and load listview with contacts */
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri, null, null, null,ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if(contactsCursor.moveToFirst()){
do{
long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone, work email etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri, null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName="";
String nickName="";
String homePhone="";
String mobilePhone="";
String workPhone="";
//String photoPath="" + R.drawable.blank;
byte[] photoByte=null;
String homeEmail="";
String workEmail="";
String companyName="";
String title="";
if(dataCursor.moveToFirst()){
// Getting Display Name
displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
do{
// Getting NickName
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
// Getting Phone numbers
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting EMails
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {
switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
case ContactsContract.CommonDataKinds.Email.TYPE_HOME :
homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK :
workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
break;
}
}
// Getting Organization details
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
}
// Getting Photo
if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
if(photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
// Temporary file to store the contact image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// photoPath = tmpFile.getPath();
}
}
}while(dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if(homePhone != null && !homePhone.equals("") )
details = "HomePhone : " + homePhone + "\n";
if(mobilePhone != null && !mobilePhone.equals("") )
details += "MobilePhone : " + mobilePhone + "\n";
if(workPhone != null && !workPhone.equals("") )
details += "WorkPhone : " + workPhone + "\n";
if(nickName != null && !nickName.equals("") )
details += "NickName : " + nickName + "\n";
if(homeEmail != null && !homeEmail.equals("") )
details += "HomeEmail : " + homeEmail + "\n";
if(workEmail != null && !workEmail.equals("") )
details += "WorkEmail : " + workEmail + "\n";
if(companyName != null && !companyName.equals("") )
details += "CompanyName : " + companyName + "\n";
if(title != null && !title.equals("") )
details += "Title : " + title + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,null,details});
}
}while(contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}