Multiple Application Uninstall by checkboxes - android

I want to uninstall multiple applications by checking checkbox.. problem is when i check multiple apps to uninstall it alerts "Are you sure you want to uninstall this App" every time. I want only one alert and the code uninstalls all checked Applications.
private void displayListView() {
ArrayList<App> appList = new ArrayList<App>();
App app = null;
List<PackageInfo> list = getPackageManager().getInstalledPackages(0);
String name = "";
String path = "";
String capName = "";
for (PackageInfo p : list) {
if ((p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
} else {
name = p.applicationInfo.loadLabel(getPackageManager())
.toString();
capName = getApplicationContext().getPackageName();
path = p.applicationInfo.packageName;
if ((!name.equals("com.android.gesture.builder"))
&& (!capName.equals(path))) {
app = new App(path, name, false);
app.setVersionCode(p.versionCode);
app.setVersionName(p.versionName);
app.setIcon(p.applicationInfo.loadIcon(getPackageManager()));
appList.add(app);
}
}
}
// create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(this, R.layout.layout_app_list,
appList);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// app app = (app)
// parent.getItemAtPosition(position);
App ap = (App) parent.getItemAtPosition(position);
// Toast.makeText(getApplicationContext(), ap.getName(),
// Toast.LENGTH_SHORT).show();
Intent itn = new Intent(AppManagement.this, AppInfo.class);
Bundle extras = new Bundle();
extras.putString("name", ap.getName());
extras.putString("path", ap.getpath());
extras.putString("vName", ap.getVersionName());
extras.putString("vCode", ap.getVersionCode() + "");
itn.putExtras(extras);
startActivity(itn);
}
});
}
public void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
ArrayList<App> appList = dataAdapter.appList;
App app = null;
for (int i = 0; i < appList.size(); i++) {
app = appList.get(i);
if (app.isSelected()) {
urr = Uri.fromParts("package", app.getpath(), null);
Log.d("", urr.toString());
responseText.append("\n" + app.getName() + " \t "
+ app.getpath());
Intent intent = new Intent(Intent.ACTION_DELETE, urr);
startActivityForResult(intent, 1);
}
}
if (responseText.length() == 0) {
Toast.makeText(getApplicationContext(), "No App selected ",
Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(getApplicationContext(), responseText,
// Toast.LENGTH_LONG).show();
}
}
});
}
public void onActivityResult(int rCode, int resultCode, Intent data) {
if (rCode == 1) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Ok", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
displayListView();
}
}
}

This is not currently available to third party applications. You will have to take permission from user for each install/uninstall.

Related

How to refresh the activity's data when we return from another activity?

Here, I want to make an app which is having profile activity and user can see his/her information in that and the activity has one button for editing the profile. When button is clicked the new activity is opened where user can edit there information & press save button and then return to profile activity.
So my question is how can I reload the profile activity with edited information?
here is my Edit profile activity
public class EditProfileActivity extends AppCompatActivity implements View.OnClickListener {
Button save_profile;
RadioGroup radioGroup;
EditText user_name,user_email,user_phone,user_addhar_number,birthdate;
ImageView user_profile_bg,user_profile,back_arrow;
private static final int RESULT_LOAD_IMAGE=24;
//db_details
String db_email="",db_name="",db_birthday,db_phone=" ";
String db_profile_pic = "",db_profile_pic_bg = "",db_token="";
String email,phone,name,profile_pic_url=" ",gender=" ",birthday;
String token="",addhar_number,new_profile_pic_url;
private double currentLatitude;
private double currentLongitude;
private boolean check_flag = false;
byte[] profile_pic_array;
byte[] profile_pic_bg_array;
Bitmap bitmap_profile= null,bitmap_bg=null;
Calendar mycalender;
ImageView CurrentImageView = null;
int choosebutton;
private long imei_number = 0;
private ProgressDialog pDialog;
Bitmap selectedImage = null;
Bitmap selectedImage2 = null;
SQliteHandler db;
private static final String TAG = EditProfileActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
user_name =(EditText)findViewById(R.id.et_user_name);
user_email =(EditText)findViewById(R.id.et_user_email);
user_phone =(EditText)findViewById(R.id.et_user_phone);
user_addhar_number =(EditText)findViewById(R.id.et_user_aadhar_number);
birthdate = (EditText)findViewById(R.id.et_user_birthday);
user_profile_bg =(ImageView)findViewById(R.id.header_cover_image);
user_profile=(ImageView) findViewById(R.id.user_profile_photo);
back_arrow = (ImageView)findViewById(R.id.iv_back);
mycalender = Calendar.getInstance();
save_profile =(Button)findViewById(R.id.btn_profile_save);
db=new SQliteHandler(getApplicationContext());
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
back_arrow.setOnClickListener(this);
save_profile.setOnClickListener(this);
user_profile_bg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_flag =true;
CurrentImageView = (ImageView) v;
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery,RESULT_LOAD_IMAGE);
choosebutton=1;
}
});
user_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check_flag =true;
CurrentImageView = (ImageView) v;
Intent gallery = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery,RESULT_LOAD_IMAGE);
choosebutton=2;
}
});
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
mycalender.set(Calendar.YEAR, year);
mycalender.set(Calendar.MONTH, monthOfYear);
mycalender.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
if(db_birthday != null && db_birthday != " " ){
birthdate.setText(db_birthday);
birthdate.setClickable(false);
}else {
birthdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(EditProfileActivity.this, date, mycalender.get(Calendar.YEAR),
mycalender.get(Calendar.MONTH), mycalender.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
Intent data = getIntent();
if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")) {
name = data.getStringExtra("name");
email = data.getStringExtra("email");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}else if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")){
name = data.getStringExtra("name");
phone = data.getStringExtra("phone");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}
//load user data from sqlite
if(email != null && email !=" ") {
HashMap<String, String> user = db.getuserdetails(email);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
db_token= user.get("token");
}else if(phone != null && phone !=" "){
HashMap<String, String> user = db.getuserdetails(phone);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
db_token= user.get("token");
}
user_name.setText(name);
if ((email != " " && email != null)&&(Patterns.EMAIL_ADDRESS.matcher(email).matches())){
user_email.setText(email);
KeyListener keyListener = user_email.getKeyListener();
user_email.setKeyListener(null);
}else if((phone !=" " && phone !=null)&& (Pattern.compile("^[789]\\d{9}$").matcher(phone).matches())) {
user_phone.setText("+91 " + phone);
KeyListener keyListener = user_phone.getKeyListener();
user_phone.setKeyListener(null);
}
Glide.with(this)
.load(profile_pic_url)
.placeholder(R.drawable.default_avtar)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(user_profile);
radioGroup =(RadioGroup)findViewById(R.id.gender_rg);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int i) {
RadioButton rb=(RadioButton)radioGroup.findViewById(i);
switch (i){
case R.id.rb_male:
gender = "male";
break;
case R.id.rb_female:
gender = "female";
break;
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_profile_save:
name = user_name.getText().toString();
email = user_email.getText().toString();
phone = user_phone.getText().toString();
addhar_number = user_addhar_number.getText().toString();
birthday = birthdate.getText().toString();
if(!check_flag) {
if (profile_pic_url != null && !profile_pic_url.equals(" ") && !profile_pic_url.isEmpty()) {
BitMap m = new BitMap();
try {
bitmap_profile = m.execute(profile_pic_url).get();
bitmap_bg = BitmapFactory.decodeResource(getResources(),R.drawable.beach);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
profile_pic_array = bitmapToByte(bitmap_profile);
profile_pic_bg_array = bitmapToByte(bitmap_bg);
} else {
bitmap_profile = BitmapFactory.decodeResource(getResources(),R.drawable.default_avtar);
bitmap_bg = BitmapFactory.decodeResource(getResources(),R.drawable.beach);
profile_pic_array = bitmapToByte(bitmap_profile);
profile_pic_bg_array = bitmapToByte(bitmap_bg);
}
}else{
profile_pic_array = bitmapToByte(selectedImage2);
profile_pic_bg_array = bitmapToByte(selectedImage);
}
String profile_pic= null;
String profile_pic_bg = null;
profile_pic = Base64.encodeToString(profile_pic_array,Base64.DEFAULT);
profile_pic_bg = Base64.encodeToString(profile_pic_bg_array,Base64.DEFAULT);
db.updateUser(name,email,phone,addhar_number,gender,profile_pic,profile_pic_bg,birthday,token);
updateProfile();
break;
case R.id.iv_back:
Intent home = new Intent(getApplicationContext(),ProfileActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home);
break;
}
}
private void updateLabel() {
String myFormat = "dd/mm/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
birthdate.setText(sdf.format(mycalender.getTime()));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selected_image = data.getData();
new_profile_pic_url = selected_image.toString();
Log.d("new profile_pic_url",new_profile_pic_url);
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selected_image,filePath,null,null,null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
if(choosebutton==1) {
selectedImage = BitmapFactory.decodeFile(imagePath, options);
Glide.with(this)
.load(selected_image)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(CurrentImageView);
}else if(choosebutton ==2){
selectedImage2 = BitmapFactory.decodeFile(imagePath, options);
Glide.with(this)
.load(selected_image)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(CurrentImageView);
}
cursor.close();
}
}
public byte[] bitmapToByte(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,0,baos);
return baos.toByteArray();
} private class BitMap extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream(url.openStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
And my profile activity class is here
public class ProfileActivity extends Activity implements View.OnClickListener {
ImageView heder_bg,profile_pic,back;
Button edit_profile;
TextView tv_name,tv_email,tv_phone,tv_birthday;
String email=" ",phone=" ",name,profile_pic_url,token;
//db_details
String db_email="",db_name="",birthday = " ",db_phone=" ";
String db_profile_pic = "",db_profile_pic_bg = "";
private double currentLatitude;
private double currentLongitude;
//datetbase variables
SQliteHandler db;
private static final String TAG = ProfileActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
heder_bg =(ImageView)findViewById(R.id.profile_header_cover_image);
profile_pic = (ImageView)findViewById(R.id.profile_user_profile_photo);
back = (ImageView)findViewById(R.id.iv_profile_back);
edit_profile = (Button)findViewById(R.id.btn_edit_profile);
tv_name = (TextView)findViewById(R.id.profile_name);
tv_email = (TextView)findViewById(R.id.profile_email);
tv_phone = (TextView)findViewById(R.id.profile_phone);
tv_birthday = (TextView)findViewById(R.id.profile_birthday);
Intent data = getIntent();
if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")) {
name = data.getStringExtra("name");
email = data.getStringExtra("email");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}
else if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")){
name = data.getStringExtra("name");
phone = data.getStringExtra("phone");
profile_pic_url = data.getStringExtra("profile_url");
token = data.getStringExtra("token");
currentLatitude = data.getDoubleExtra("latitude",0.0);
currentLongitude = data.getDoubleExtra("longitude",0.0);
}
db = new SQliteHandler(getApplicationContext());
//load user data from sqlite
if(email != null && email !=" ") {
HashMap<String, String> user = db.getuserdetails(email);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
}else if(phone != null && phone !=" "){
HashMap<String, String> user = db.getuserdetails(phone);
db_name = user.get("name");
db_email = user.get("email");
db_phone = user.get("phone");
db_profile_pic = user.get("profile_pic");
db_profile_pic_bg = user.get("profile_pic_bg");
birthday = user.get("birthday");
}
edit_profile.setOnClickListener(this);
back.setOnClickListener(this);
load_user_info();
}
public void load_user_info(){
if(name != null && name !=""){
tv_name.setText(name);
}else if(db_name != null && db_name !=""){
tv_name.setText(db_name);
}
if (email != " " && email != null){
tv_email.setText(email);
}else if(db_email != null && db_email != "") {
tv_email.setText(db_email);
}else {
tv_email.setText(" ");
}
if(phone !=" " && phone !=null) {
tv_phone.setText("+91 " + phone);
}else if(db_phone !=null && db_phone !=" ") {
tv_phone.setText(db_phone);
}else {
tv_phone.setText("");
}
if(profile_pic_url!=null && profile_pic_url != "") {
Glide.with(this)
.load(profile_pic_url)
.error(R.drawable.default_avtar)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(profile_pic);
Glide.with(this)
.load(R.drawable.beach)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(heder_bg);
}
else if((db_profile_pic !=null && !db_profile_pic.equals(" "))&&(db_profile_pic_bg !=null && !db_profile_pic_bg.equals(" "))){
byte[] db_profile;
byte[] db_profile_bg;
Bitmap db_profile_bitmap,db_profile_pic_bg_bitmap;
db_profile = Base64.decode(db_profile_pic,Base64.DEFAULT);
db_profile_bitmap = getBitmap(db_profile);
db_profile_bg = Base64.decode(db_profile_pic_bg,Base64.DEFAULT);
db_profile_pic_bg_bitmap = getBitmap(db_profile_bg);
Glide.with(this)
.load(db_profile_bitmap)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(profile_pic);
Glide.with(this)
.load(db_profile_pic_bg_bitmap)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(heder_bg);
}else {
Glide.with(this)
.load(R.drawable.default_avtar)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.bitmapTransform(new CropCircleTransformation(this))
.into(profile_pic);
Log.d("Default image set",TAG);
}
if(birthday !=" " && birthday !=null && birthday.equals("test")){
tv_birthday.setText("Born on " + birthday);
} else {
tv_birthday.setText(" ");
}
}
#Override
public void onResume(){
super.onResume();
load_user_info();
Log.d("in resume methode",TAG);
}
public Bitmap getBitmap(byte[] bitmap) {
return BitmapFactory.decodeByteArray(bitmap , 0, bitmap.length);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_edit_profile:
Intent edit_profile = new Intent(getApplicationContext(),EditProfileActivity.class);
edit_profile.putExtra("name",name);
if((email !=null && email !="") && Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
edit_profile.putExtra("email", email);
}else if(phone != null && phone !="") {
edit_profile.putExtra("phone", phone);
}
edit_profile.putExtra("profile_url",profile_pic_url);
edit_profile.putExtra("token",token);
edit_profile.putExtra("latitude",currentLatitude);
edit_profile.putExtra("longitude",currentLongitude);
startActivity(edit_profile);
break;
case R.id.iv_profile_back:
Intent home = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(home);
break;
}
}
}
Before OP posted code
You can define a function that loads your data for ProfileActivity and call it in onResume().
#Override
public void onResume() {
super.onResume();
if (this.reloadNedeed)
this.reloadProfileData();
this.reloadNeeded = false; // do not reload anymore, unless I tell you so...
}
This way, since onResume() is also called after onCreate(),
you'd be using the same code both for when the the activity is first created and for when you re-open it (e.g. when you come back from another activity, or another app).
In order to make it work, reloadNedeed must be set to true by default:
private boolean reloadNeed = true;
In order to start the EditActivity you can do:
startActivityForResult(new Intent(EditActivity.class), EDIT_CODE);
where EDIT_CODE can be any number, e.g:
private static final int EDIT_CODE = 31;
When you want to get back to from EditActivity you just call:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_OK,returnIntent); // or RESULT_CANCELED if user did not make any changes
// it would be better to use some custom defined codes here
finish();
This would trigger the function onActivityResult(int, int Intent) in ProfileActivity, in which you can tell the activity to reload the data.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDIT_CODE) { // Ah! We are back from EditActivity, did we make any changes?
if (resultCode == Activity.RESULT_OK) {
// Yes we did! Let's allow onResume() to reload the data
this.reloadNeeded = true;
}
}
onResume() is called after onActivityResult(), so we can safely decide whether to put reloadNeeded to true, or just leave it to false.
Edit: After OP posted code
I haven't tested your code, but I may have found some oddities just by looking at it.
I believe you may have a problem with some if-else conditions in your load_user_info() function.
When you get back from EditActivity the activity is (most likely) not created again. Only onResume() is called, which calls load_user_info();
But since the Activity isn't recreated, your variables hold the same values from when they were initialized in onCreate().
When he does check the data:
if(name != null && name !=""){
tv_name.setText(name);
}else if(db_name != null && db_name !=""){
tv_name.setText(db_name);
}
your activity says:
Heyy, name is not null and is different than "" (by the way you should use equals(), even for literals)
Therefore, I will execute this piece of code tv_name.setText(name);, and since it's an if else statement, the second block will NOT be executed.
So your activity, never really displays the updated data. The same data as before is displayed.
You should try to apply the same logic as I posted in my original answer.
Hope I understood your question right...
There are multiple ways to accomplish what you are asking. There's the simple(ish) way and the hard(er) and more correct way.
The easiest way is to refresh the data you're expecting in the onResume of the activity you are returning to. If you navigate to a different activity, the previous activity will call onPause, then onResume when you return, and at that time you can check for new data and load it in place. That's the quicker way.
A better, more correct way of doing it would be to implement a ViewModel and use LiveData to allow the Activity to always have the most up to date data. This does require a bit of extra effort on your end to make sure your app has proper architecture, but in the long run pays off way better. Check out Android's architecture components.
To refresh your activity data:
finish();
startActivity(getIntent());
onBackPressed or finish() then its call and refresh
#Override
public void onRestart()
{
super.onRestart();
finish();
startActivity(getIntent());
}
I hope this helpful...

Activity becomes black while calling the run time permissions

I want to call run time permissions to read contacts on click of some view. So I checking if app has the permissions and if not requesting for the permissions. But When the request dialog appears the activity gets black and gets finished if allow or deny is clicked on dialog. When I debug the app, it dose not go to the onRequestPermissionsResult method after clicking allow or deny.
Also I am calling the contact Intent if permissions are accepted. I want to show these in the same activity as a list of selected contacts. So for this I have a list and added contacts to the list onActivitResult method.
But for this also if I select some contact from contacts, the activity gets finished. It dose not go to the onActivityResult method.
public class PlanEventActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener,
DatePickerDialog.OnDateSetListener {
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
private boolean mHoursMode, updateEvent, subevent,permissionsAccepted;
RelativeLayout chooseEvent, time, date;
EditText eventName, chooseEventText, timeTextView, dateTextView;
private RelativeLayout parent;
static final int CUSTOM_DIALOG_ID = 0;
private String mEventId, mMainEventId;
ListView dialog_ListView;
private Intent mIntent;
private SharedPreferences sharedPreferences;
private TextView title;
private ImageView addOrganizer;
private ArrayList<Organizers> mSelectedContacts;
private RecyclerViewAdapter mAdapter;
private RecyclerView mContactsList;
private ArrayList<Event> subEventArrayList;
public static final String MyPREFERENCES = "MyPrefs1";
private Button mSubmit;
private String mEventType, mEventName, mEventDate, mEventTime, mOraganizerName, mOrganizerPhone,
mOrganizersId, mOrganizersEmail, mOrganizersLastName, mOrganizerFirstName, userName;
private Event mEvent;
private static final int RESULT_PICK_CONTACT = 10;
private Organizers mOrganizers;
private ImageButton add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plan_event);
mIntent = getIntent();
subEventArrayList = new ArrayList<>();
setUpUI();
mContactsList.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new RecyclerViewAdapter(this, mSelectedContacts);
mContactsList.setAdapter(mAdapter);
((RecyclerViewAdapter) mAdapter).setMode(Attributes.Mode.Single);
}
public void setUpUI() {
addOrganizer = (ImageView) findViewById(R.id.addOrganizer);
mContactsList = (RecyclerView) findViewById(R.id.selectedContactsList);
mSubmit = (Button) findViewById(R.id.submit);
add = (ImageButton) findViewById(R.id.addButton);
mSelectedContacts = new ArrayList<>();
updateEvent = mIntent.getBooleanExtra("updateEvent", false);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
permissionsAccepted = sharedPreferences.getBoolean("permission1",false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
}
else if (permissionsAccepted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
else {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}
});
addOrganizer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
permissionsAccepted = sharedPreferences.getBoolean("permission1",false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
Log.d("request","Request permission is called");
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
}
else if (permissionsAccepted && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
else {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}
});
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
String date = dayOfMonth + "/" + (++monthOfYear) + "/" + year;
dateTextView.setText(date);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if(requestCode == PERMISSIONS_REQUEST_READ_CONTACTS)
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// If request is cancelled, the result arrays are empty.
permissionsAccepted = true;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("permission1", permissionsAccepted);
editor.commit();
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
mOrganizers = new Organizers();
contactPicked(data);
mOrganizers.setFName(mOrganizerFirstName);
mOrganizers.setMobile(mOrganizerPhone);
mOrganizers.setEmail(mOrganizersEmail);
mOrganizers.setId(mOrganizersId);
mOrganizers.setLName(mOrganizersLastName);
mSelectedContacts.add(mOrganizers);
mAdapter.notifyDataSetChanged();
if (mSelectedContacts.size() != 0) {
addOrganizer.setVisibility(View.INVISIBLE);
mContactsList.setVisibility(View.VISIBLE);
add.setVisibility(View.VISIBLE);
} else {
addOrganizer.setVisibility(View.VISIBLE);
}
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int contactIdIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
mOrganizerPhone = cursor.getString(phoneIndex);
mOraganizerName = cursor.getString(nameIndex);
mOrganizersId = cursor.getString(contactIdIndex);
final String[] projection = new String[]{ContactsContract.CommonDataKinds.Email.DATA, // use
// Email.ADDRESS
// for API-Level
// 11+
ContactsContract.CommonDataKinds.Email.TYPE};
Cursor emailCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection,
ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(mOrganizersId)}, null);
if (emailCursor.moveToFirst()) {
final int contactEmailColumnIndex = emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
while (!emailCursor.isAfterLast()) {
mOrganizersEmail = emailCursor.getString(contactEmailColumnIndex) + ";";
emailCursor.moveToNext();
}
}
String[] parts = mOraganizerName.split(" ", 2);
mOrganizerFirstName = parts[0]; // 004
mOrganizersLastName = parts[1];
} catch (Exception e) {
e.printStackTrace();
}
}
public void resetOrganizer(Context context) {
addOrganizer.setVisibility(View.VISIBLE);
mContactsList.setVisibility(View.GONE);
}
#Override
public void onResume() {
super.onResume();
}
public void showAlert(String alert,PlanEventActivity activity) {
parent = (RelativeLayout)activity.findViewById(R.id.parentPanel);
Snackbar snackbar = Snackbar.make(parent, alert, Snackbar.LENGTH_LONG);
snackbar.show();
}
}
}
Strange thing the same code was working fine before. For the older version. I also tried to copy the same activity of older version to the new version, but still it dose not work.
Not getting whats wrong.
Can anyone help please? Thank you..
Make sure you don't have android:noHistory=true attribute entered in the activity declaration in AndroidMenifest.xml.
Replace requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
with ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);

Mapping listView items with photos from the cloud

I have some places in a listView. These are picked from a Google Map, for which I would like to take a picture. One for each. These photos should be available online, so I have searched for some proper solutions. I've choosed imgur's API.
Is it possible to link pictures with places? I would like to make mapping between uploaded pictures and listView items.
Photo picker and uploader class:
public class OAuthTestActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 1001;
private static final String AUTHORIZATION_URL = "https://api.imgur.com/oauth2/authorize";
private static final String CLIENT_ID = "CLIENT_ID";
private LinearLayout rootView;
private String accessToken;
private String refreshToken;
private String picturePath = "";
private Button send;
private String uploadedImageUrl = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = new LinearLayout(this);
rootView.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(llp);
rootView.addView(tv);
setContentView(rootView);
String action = getIntent().getAction();
if (action == null || !action.equals(Intent.ACTION_VIEW)) { // We need access token to use Imgur's api
tv.setText("Start OAuth Authorization");
Uri uri = Uri.parse(AUTHORIZATION_URL).buildUpon()
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("response_type", "token")
.appendQueryParameter("state", "init")
.build();
Intent intent = new Intent();
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else { // Now we have the token, can do the upload
tv.setText("Got Access Token");
Uri uri = getIntent().getData();
Log.d("Got imgur's access token", uri.toString());
String uriString = uri.toString();
String paramsString = "http://callback?" + uriString.substring(uriString.indexOf("#") + 1);
Log.d("tag", paramsString);
List<NameValuePair> params = URLEncodedUtils.parse(URI.create(paramsString), "utf-8");
Log.d("tag", Arrays.toString(params.toArray(new NameValuePair[0])));
for (NameValuePair pair : params) {
if (pair.getName().equals("access_token")) {
accessToken = pair.getValue();
} else if (pair.getName().equals("refresh_token")) {
refreshToken = pair.getValue();
}
}
Log.d("tag", "access_token = " + accessToken);
Log.d("tag", "refresh_token = " + refreshToken);
Button chooseImage = new Button(this);
rootView.addView(chooseImage);
chooseImage.setText("Choose an image");
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
});
send = new Button(this);
rootView.addView(send);
send.setText("send to imgur");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (picturePath != null && picturePath.length() > 0 &&
accessToken != null && accessToken.length() > 0) {
(new UploadToImgurTask()).execute(picturePath);
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
if (send == null) return;
if (picturePath == null || picturePath.length() == 0) {
send.setVisibility(View.GONE);
} else {
send.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("tag", "request code : " + requestCode + ", result code : " + resultCode);
if (data == null) {
Log.d("tag" , "data is null");
}
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_PICK_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
Log.d("tag", "image path : " + picturePath);
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
}
// Here is the upload task
class UploadToImgurTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
final String upload_to = "https://api.imgur.com/3/upload";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(upload_to);
try {
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("image", new FileBody(new File(params[0])))
.build();
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(entity);
final HttpResponse response = httpClient.execute(httpPost,
localContext);
final String response_string = EntityUtils.toString(response
.getEntity());
final JSONObject json = new JSONObject(response_string);
Log.d("tag", json.toString());
JSONObject data = json.optJSONObject("data");
uploadedImageUrl = data.optString("link");
Log.d("tag", "uploaded image url : " + uploadedImageUrl);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean.booleanValue()) { // after sucessful uploading, show the image in web browser
Button openBrowser = new Button(OAuthTestActivity.this);
rootView.addView(openBrowser);
openBrowser.setText("Open Browser");
openBrowser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setData(Uri.parse(uploadedImageUrl));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
}

Android Fabric Twitter share listener

I use Fabric SDK to send tweets from my application.
I build a share dialog and send tweet from activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(this, new TwitterCore(authConfig), new TweetComposer());
Bundle bundle = getIntent().getExtras().getBundle(SHARE_DATA);
String description = bundle.getString(SHARE_DESCRIPTION);
String title = bundle.getString(SHARE_TITLE);
String picture = bundle.getString(SHARE_PICTURE_LINK);
String link = bundle.getString(SHARE_LINK);
TweetComposer.Builder builder = null;
try {
InputStream in = new java.net.URL(picture).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Uri yourUri = getImageUri(this,bitmap);
builder = new TweetComposer.Builder(this)
.text(title + "\n" + description)
.url(new URL(link))
.image(yourUri);
//??? IS THERE ANY LISTENER ???
builder.show();
} catch (IOException e1) {
e1.printStackTrace();
}
}
I want to know status of sharing, like an success or not, but i can't find any listener for this action. I missed something?
Instead of use builder.show(), you should use builder.createIntent() :
Intent intent = new TweetComposer.Builder(getActivity())
.text("TEXT")
.url("URL")
.createIntent();
startActivityForResult(intent, TWEET_COMPOSER_REQUEST_CODE);
To get the result feedback in onActivityResult() :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TWEET_COMPOSER_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
onTwitterSuccess();
} else if(resultCode == Activity.RESULT_CANCELED) {
onTwitterCancel();
}
}
}
use below method to twitt via rest service and pass media id as null.i m successfully posting tweets from my app
public void postToTwitter(ArrayList<String>mediaIds) {
String message;
if(Validator.isNotNull(preferences.getFbShareMessage())){
message=preferences.getFbShareMessage()+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
else {
message = getString(R.string.google_status, HWUtil.getFullName(preferences.getUserInfo().getFirstName(), preferences.getUserInfo().getLastName()), userHistory.getSportName(), HWUtil.secondToTime(userHistory.getDuration()))+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
String mediaId;
if (Validator.isNotNull(mediaIds) && mediaIds.size() > 0) {
mediaId="";
for (int i = 0; i < mediaIds.size(); i++) {
if (i == 0) {
mediaId = mediaIds.get(i);
} else {
mediaId += "," + mediaIds.get(i);
}
}
}
else {
mediaId=null;
}
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.update(message, null, null, null, null, null, null, null, mediaId, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
dismissProgressDialog();
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
com.aimdek.healthwel.network.Request.getRequest().sendRequest(com.aimdek.healthwel.network.Request.SHARE_USER_HISTORY, TwitterIntegration.this, TwitterIntegration.this, RequestParameterBuilder.buildMapForShareUserHistory(userHistory.getId(), TwitterIntegration.this));
}
#Override
public void failure(TwitterException exception) {
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
dismissProgressDialog();
finish();
HWUtil.showToast(TwitterIntegration.this,exception.getMessage());
}
});
}

SQLite Database not updating properly after deleting row

When I delete any data then listitem click is showing error when opening listitem and data are also not correct on custom listview. After deleting row 0 data is not updating properly. Please help..
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
// means this is the view part not the add contact part.
Cursor crs = mydb.getData(Value);
id_To_Update = Value;
crs.moveToFirst();
String nam = crs.getString(crs.getColumnIndex(DBHelper.C_NAME));
String phon = crs.getString(crs
.getColumnIndex(DBHelper.C_PHONE));
String addr = crs.getString(crs
.getColumnIndex(DBHelper.C_ADDRESS));
String dat = crs.getString(crs.getColumnIndex(DBHelper.C_DATE));
String typ = crs.getString(crs.getColumnIndex(DBHelper.C_TYPE));
if (!crs.isClosed()) {
crs.close();
}
Button b = (Button) findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
name.setText((CharSequence) nam);
name.setFocusable(false);
name.setClickable(false);
phone.setText((CharSequence) phon);
phone.setFocusable(false);
phone.setClickable(false);
type.setText((CharSequence) typ);
type.setFocusable(false);
type.setClickable(false);
address.setText((CharSequence) addr);
address.setFocusable(false);
address.setClickable(false);
date.setText((CharSequence) dat);
date.setFocusable(false);
date.setClickable(false);
}
}
}
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(),
"Deleted Successfully",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
if (mydb.updateContact(id_To_Update, name.getText().toString(),
phone.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "Updated",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "not Updated",
Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertContact(name.getText().toString(), phone
.getText().toString(), type.getText().toString(),
address.getText().toString(), date.getText().toString())) {
Toast.makeText(getApplicationContext(), "done",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "not done",
Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),
com.example.addressbook.MainActivity.class);
startActivity(intent);
}
DBHelper.java
public Integer deleteContact(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ",
new String[] { Integer.toString(id) });
}
}
Finally I have got the solution. I have a text view in custom list view which has Table id which is unique for every row and after deleting the row it's value does not change so I am opening the data of that row on different activity.

Categories

Resources