Passing data between activity - java

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);

Related

color listview line with condition android/java

I'm searching to get a little useful option to my app, the basics are simple, I have a list of questions (in listView) when we click in the question, we have another activity with details of questions and the answer that is setting ( true or false), if the answer is right, I want to color the question in the listview in green, red if false:
My code to generate questions:
public void showQuest(View view){
ModelHelper md = new ModelHelper(this);
db = openHelper.getWritableDatabase();
Spinner s = (Spinner) findViewById(R.id.spn_ques);
Integer para = 2;
para = Integer.parseInt( s.getSelectedItem().toString()) ;
ArrayList<String> lstQ = md.getOnlyQuestions(para);
ArrayAdapter lstad = new ArrayAdapter(this, android.R.layout.simple_list_item_1,lstQ);
lst.setAdapter(lstad);
The listView OnclickListener:
String quest = (String) parent.getAdapter().getItem(i);
int pos = lst.getCheckedItemPosition();
Intent inte = new Intent(view.getContext(),Reponse.class);
cursor = db.rawQuery("SELECT * FROM "+ ModelHelper.TABLE_QUESTION + " WHERE " + ModelHelper.KEY_QUESTION + " = ? ",new String[] {quest});
if (cursor != null)
if (cursor.getCount() > 0) {
cursor.moveToFirst();
final Intent intent = getIntent();
String matr= intent.getStringExtra("id");
String repA = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFIL_WAITEDANSWER));
String cible = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PROFILE));
String plan = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PLAN));
int ID = cursor.getInt(cursor.getColumnIndex(ModelHelper.KEY_ID_QUESTION));
inte.putExtra("Question", quest);
inte.putExtra("answ", repA);
inte.putExtra("ID", ID);
inte.putExtra("pos", pos);
inte.putExtra("position", i);
inte.putExtra("matr", matr);
Toast.makeText(new.this, "" + ID, Toast.LENGTH_SHORT).show();
startActivity(inte);
}
}
});
The answer is selected in another activity, in the first one I have only the questions' list.
Thanks.
When you are rendering the item in the listview set the background color based on the logic you described.

getIntExtra() always returning the default value

I have two different apps, AppA and AppB, I am trying to send an int from AppB to AppA, but the getIntExtra() in AppA is always getting the default value 0. Currently in AppA, gameRecords_str is receiving the correct string value, but I keep getting the default value 0 for gameCounter. What went wrong?
AppB:
String query = "SELECT * FROM gameRecord";
Cursor mcursor = database.rawQuery(query, null);
int counter = mcursor.getCount(); // Find out the number of records found in database
System.out.println("Number of record : " + counter);
Intent sendCounter = new Intent();
sendCounter.setAction("com.joy.AppA.LAUNCH_IT");
sendCounter.putExtra("counter", counter);
startActivity(sendCounter);
String gameRecord_str;
int flag;
mcursor.moveToFirst();
if (mcursor != null) {
if (mcursor.moveToFirst()) {
do {
String record = mcursor.getString(mcursor.getColumnIndex("record"));
gameRecord_str = record;
Intent i = new Intent();
i.setAction("com.joy.AppA.LAUNCH_IT");
i.putExtra("gameRecord", gameRecord_str);
startActivity(i);
} while (mcursor.moveToNext());
AppA:
Intent intent = getIntent();
int gameCounter = intent.getIntExtra("counter", 0); //Number of records from game AppB
System.out.println("gameCounter : " + gameCounter);
for (int i=0; i<=gameCounter; i++) {
String gameRecords_str = intent.getStringExtra("gameRecord");
System.out.println("Game record received from AppB : " + gameRecords_str);
Thanks in advance for your help!

Arraylist elements starting too much activity

I am developing an application, that sends a string array with putStringArrayListExtra. In the second activity I am receiving. The problem, if I send 2 item, 2 activity will open. The second element is on the listview(shows just one), when i click back, there is now the first item. I want the 2 item in the SAME listview. What am I doing wrong?
First activity
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
// String result = "";
String ar="";
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
cnt++;
ar = nev[i];
selectImages = nev[i] + "|";
// List<String> myList = new ArrayList<String>(Arrays.asList(selectImages));
ArrayList<String> arr = new ArrayList<String>();
arr.add(selectImages);
Intent intent = new Intent(Gallery.this,Upload.class);
intent.putStringArrayListExtra("array_list", arr);
startActivity(intent);
// Log.i("adat","galleri:" + arr);
}
}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"You've selected Total " + cnt + " image(s).",
Toast.LENGTH_LONG).show();
}
}
});
Second activity
ListView listView;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.list);
Bundle b = getIntent().getExtras();
// ArrayList<String> arr = (ArrayList<String>)b.getStringArrayList("array_list");
ArrayList<String> arr = b.getStringArrayList("array_list");
Log.i("adat","UPLOAD:"+arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, arr);
listView.setAdapter(adapter);
}
Do like below while you are creating new arraylist everytime when you loop thats why you are not getting correct values.
And also take you intent outside the loop too.
ArrayList<String> arr = new ArrayList<String>();
for (int i =0; i<len; i++){
if (thumbnailsselection[i]){
cnt++;
ar = nev[i];
selectImages = nev[i] + "|";
arr.add(selectImages);
}
}
Intent intent = new Intent(Gallery.this,Upload.class);
intent.putStringArrayListExtra("array_list", arr);
startActivity(intent);

View permission names of a specific app on android ListView

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();
}

Create Preference dynamically

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();

Categories