how to set wallpaper as lockscreen or both(home and lock)? - android

I have done implementing "set wallpaper as home screen".but im not getting how can I set wallpaper as lock screen and both(home and lock).in following code "if" part is for setting as homescreen..rest is for "lock" and "both(home and lock)"..what will the logic for it to set wallpaper as lock and both(home and lock).?
code:
public class ViewImage extends AppCompatActivity {
Button button1, button2;
public List<RetroPhoto> product_lists=new ArrayList<>();
private RecyclerView recyclerView;
WallpaperManager myWallpaperManager;
public static FavoriteDatabase favoriteDatabase;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewimage_layout);
ImageView mPlace = findViewById(R.id.imagewall);
button1 = findViewById(R.id.button1);
button2 = findViewById(R.id.button2);
ImageButton back = (ImageButton) findViewById(R.id.backToMain);
ImageButton downloadimage = findViewById(R.id.downloadimg);
ImageView favimg = findViewById(R.id.favimg);
recyclerView = findViewById(R.id.rec);
favoriteDatabase = Room.databaseBuilder(getApplicationContext(), FavoriteDatabase.class, "myfavdb").allowMainThreadQueries().build();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
final Bundle bundle = this.getIntent().getExtras();
final String imgUrl = bundle.getString("Title");
Glide.with(this).load(imgUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(mPlace);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ViewImage.this);
// Set the alert dialog title
builder.setTitle("Set Wallpaper");
// Initialize a new string array of flowers
final String[] flowers = new String[]{
"Home Screen",
"Lock screen",
"Both"
};
// Set a list for alert dialog
builder.setItems(
flowers, // Items array
new DialogInterface.OnClickListener() // Item click listener
{
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Get the alert dialog selected item's text
String selectedItem = Arrays.asList(flowers).get(i);
if(selectedItem.equals(flowers[0])) {
Glide.with(ViewImage.this)
.load(imgUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
try {
WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
Toast.makeText(ViewImage.this, "successfully set as home wallpaper", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
else if(selectedItem.equals(flowers[1]))
{
Uri bitmap = MediaStore.Images.Media.getContentUri(imgUrl);
final Uri finalBitmap = bitmap;
try {
WallpaperManager.getInstance(getApplicationContext()).setBitmap(finalBitmap,null,false,WallpaperManager.FLAG_LOCK);
// myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_LOCK);
Toast.makeText(ViewImage.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(ViewImage.this, "successfully set as Lock wallpaper", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(ViewImage.this, "successfully set as both", Toast.LENGTH_LONG).show();
}
}
});
// Create the alert dialog
AlertDialog dialog = builder.create();
// Get the alert dialog ListView instance
ListView listView = dialog.getListView();
// Set the divider color of alert dialog list view
listView.setDivider(new ColorDrawable(Color.RED));
// Set the divider height of alert dialog list view
listView.setDividerHeight(0);
// Finally, display the alert dialog
dialog.show();
}
});
}
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte= Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}

Check my code if its working for you :)
WallpaperManager myWallpaperManager;
private static final int CHOOSE_IMAGE = 22;
private Button btnSetWallpaper;
String[] options = new String[]{
"Home Screen",
"Lock Screen",
"Both"
};
In OnCreate()
btnSetWallpaper = findViewById(R.id.btnSetWallpaper);
btnSetWallpaper.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "choose image"), CHOOSE_IMAGE);
}
});
In OnActivityResult()
if (requestCode == CHOOSE_IMAGE && data != null) {
mCropImageUri = data.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mCropImageUri);
Log.e(TAG, "onActivityResult: BIT " + bitmap);
} catch (IOException e) {
e.printStackTrace();
}
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose from below");
final Bitmap finalBitmap = bitmap;
builder.setItems(options, new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String selectedItem = Arrays.asList(options).get(i);
if (selectedItem.equals(options[0])) {
try {
myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_SYSTEM);
Toast.makeText(MainActivity.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (Exception e) {
Log.e(TAG, "onResourceReady: " + e.getMessage());
}
} else if (selectedItem.equals(options[1])) {
try {
myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_LOCK);
Toast.makeText(MainActivity.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (Exception e) {
Log.e(TAG, "onResourceReady: " + e.getMessage());
}
} else if (selectedItem.equals(options[2])) {
try {
myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(finalBitmap, null, false, WallpaperManager.FLAG_LOCK | WallpaperManager.FLAG_SYSTEM);
Toast.makeText(MainActivity.this, "Wallpaper set successfully!", Toast.LENGTH_SHORT).show();
dialog.dismiss();
} catch (Exception e) {
Log.e(TAG, "onResourceReady: " + e.getMessage());
}
}
}
});
dialog = builder.create();
dialog.show();
}
You wanna just set Flags for various Wallpaper Options.
Flags like...
WallpaperManager.FLAG_LOCK | WallpaperManager.FLAG_SYSTEM : for both Screen
WallpaperManager.FLAG_SYSTEM : for Home Screen
WallpaperManager.FLAG_LOCK :for Lock Screen
Thanks :)

Related

How to update activity after image upload in Android

I have an activity where the user can update some data related to his profile (for example, his name) and he can also upload a new profile image.
After the update operation, the user is redirected to a new activity.
The problem is that when the user comes back to his profile activity, the showed image is still the old one and not the new one while the name updated correctly.
In order to see the new profile image, the user needs to close the app and open is again.
How can I solve this problem?
I use a function updateInfo(), but it seems to not work as I would like.
Can you help me, please?
public class ProfileActivity extends BaseActivity implements ProfileView {
#BindView(R.id.avatar)
ImageView p_avatar;
#BindView(R.id.ib_back)
ImageButton ibBack;
#BindView(R.id.txt_title)
TextView txtTitle;
#BindView(R.id.ib_right)
ImageButton ibRight;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.et_fullname)
EditText etFullname;
#BindView(R.id.et_email)
EditText etEmail;
#BindView(R.id.btn_update)
Button btnUpdate;
#BindView(R.id.txt_logout)
TextView txtLogout;
#BindView(R.id.ll_main)
LinearLayout llMain;
private static final String TAG = "ProfileActivity";
private String userName = null, userEmail = null;
private ProfilePresenter profilePresenter;
private Dialog dialog;
Bitmap FixBitmap;
Bitmap bitmap_to_save;
ImageView ShowSelectedImage;
String converted_img;
ByteArrayOutputStream byteArrayOutputStream;
byte[] byteArray ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ButterKnife.bind(this);
byteArrayOutputStream = new ByteArrayOutputStream();
init_view();
upDateInfo();
}
private void init_view() {
txtTitle.setText(R.string.profileActivity_title);
ibRight.setImageResource(R.drawable.ic_edit);
dialog = commonUtils.createCustomLoader(ProfileActivity.this, false);
profilePresenter = new ProfilePresenterImpl(this);
upDateInfo();
}
private void upDateInfo() {
if (Conts.USERINFO != null) {
String subName = firstTwoChar(Conts.USERINFO.getName());
// Picasso.get().load("http://www.server.com/uploads/avatars/73.png").transform(transformation).into(p_avatar);
final int radius = 30;
final int margin = 1;
final RoundedCornersTransformation transformation = new RoundedCornersTransformation(radius, margin);
Picasso.get().load("http://www.server.com/uploads/avatars/"+Conts.USERINFO.getId()).transform(transformation).into(p_avatar);
etFullname.setText(Conts.USERINFO.getName().toLowerCase());
etFullname.setEnabled(false);
etEmail.setText(Conts.USERINFO.getEmail());
etEmail.setEnabled(false);
btnUpdate.setVisibility(View.INVISIBLE);
}
}
#OnClick({R.id.ib_back, R.id.ib_right, R.id.btn_update, R.id.txt_logout, R.id.avatar})
public void onClick(View view) {
switch (view.getId()) {
case R.id.ib_back:
onBackPressed();
break;
case R.id.ib_right:
etFullname.setEnabled(true);
etFullname.setSelection(etFullname.getText().toString().length());
btnUpdate.setVisibility(View.VISIBLE);
Log.d(TAG, "validate ID: " + Conts.USERINFO.getId());
return;
case R.id.avatar:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);
return;
case R.id.btn_update:
if (validate()) {
if (!commonUtils.isNetworkAvailable()) {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
return;
}
profilePresenter.dataListAPI(Conts.USERINFO.getId(), userName, Conts.USERINFO.getEmail(), converted_img);
}
break;
case R.id.txt_logout:
get_dialog();
break;
}
}
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
FixBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
bitmap_to_save = scaleBitmapAndKeepRation(FixBitmap, 320, 320);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap_to_save);
final float roundPx = (float) bitmap_to_save.getWidth() * 0.15f;
roundedBitmapDrawable.setCornerRadius(roundPx);
roundedBitmapDrawable.setAntiAlias(true);
p_avatar.setImageDrawable(roundedBitmapDrawable);
bitmap_to_save.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
converted_img = Base64.encodeToString(byteArray, Base64.DEFAULT); // this is the image string to send to the server!
} catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(this, "An error has occurred!", Toast.LENGTH_SHORT).show();
}
}
public static Bitmap scaleBitmapAndKeepRation(Bitmap TargetBmp, int reqHeightInPixels, int reqWidthInPixels)
{
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, TargetBmp.getWidth(), TargetBmp.getHeight()), new RectF(0, 0, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.CENTER);
Bitmap scaledBitmap = Bitmap.createBitmap(TargetBmp, 0, 0, TargetBmp.getWidth(), TargetBmp.getHeight(), m, true);
return scaledBitmap;
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private void get_dialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_logout, null);
builder.setView(view);
final AlertDialog alertDialog = builder.create();
alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
alertDialog.show();
TextView txtyes, txtno;
txtyes = view.findViewById(R.id.txt_yes);
txtno = view.findViewById(R.id.txt_no);
txtyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
sharedPref.setBoolean(Conts.IsLogin, false);
sharedPref.clearAllPref();
Conts.USERINFO = null;
Intent iLogin = new Intent(ProfileActivity.this, MainActivity.class);
iLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(iLogin);
}
});
txtno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}
public String firstTwoChar(String str) {
return str.length() < 2 ? str : str.substring(0, 2);
}
#Override
public void showLoader() {
dialog.show();
}
#Override
public void hideLoader() {
if (dialog != null)
dialog.dismiss();
}
#Override
public void showError(String msg) {
Snackbar snackbar = Snackbar
.make(llMain, msg, Snackbar.LENGTH_INDEFINITE)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
// nothing anything
}
});
snackbar.show();
// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
#Override
public Context getContextAppp() {
return this;
}
#Override
public void onBackPress() {
}
#Override
public void successResponse(Data data) {
if (data != null) {
Toast.makeText(this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
UserInfo userInfo = new UserInfo(data.getId(), data.getName(), data.getEmail());
Conts.USERINFO = userInfo;
String userinfo = gson.toJson(Conts.USERINFO, UserInfo.class);
sharedPref.setDataInPref(Conts.UserInfo, userinfo);
startActivity(getIntent());
Intent iPlace = new Intent(ProfileActivity.this, AddPlaceActivity.class);
iPlace.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
Toast.makeText(this, "Profile saved!", Toast.LENGTH_SHORT).show();
startActivity(iPlace);
}
}
#Override
public void errorResponce(String msg) {
if (msg != null) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
private boolean validate() {
commonUtils.hideKeyboard(this);
if (etFullname.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Please enter Fullname", Toast.LENGTH_SHORT).show();
} else if (etFullname.getText().toString().trim().length() <= 2) {
Toast.makeText(this, "Minimum 3 character require", Toast.LENGTH_SHORT).show();
} else if (etFullname.getText().toString().trim().length() > 30) {
Toast.makeText(this, "Maximum 30 character require", Toast.LENGTH_SHORT).show();
}
/*else if (etEmail.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
} else if (!validation.checkEmail(etEmail)) {
Toast.makeText(this, "Please enter valid Email", Toast.LENGTH_SHORT).show();
}
*/
if (!etFullname.getText().toString().trim().isEmpty() && etFullname.getText().toString().trim().length() > 2 && etFullname.getText().toString().trim().length() <= 30) {
userName = etFullname.getText().toString().trim();
} else {
userName = null;
}
/*if (!etEmail.getText().toString().trim().isEmpty() && validation.checkEmail(etEmail)) {
userEmail = etEmail.getText().toString().trim();
} else {
userEmail = null;
}
*/
if (userName != null /*&& userEmail != null*/) {
Log.d(TAG, "validate: " + userName);
return true;
} else {
return false;
}
}
}
When you turn back to your profile activity your application's task stack is bringing back your profile activity which is already in memory. So you should inform your profile activity that it was updated. In the onStart callback of your profile activity check if it is updated. If so load the new image. In short put your upDateInfo() method inside onStart().
After you update the information, in callback method onResponse you need to call updateInfo() to make an update on your UI after update of information is successfully finished. Make sure you provide new values from server especially to static variables because they will keep values as long as app is live. If you don't update them with new values they will keep old ones.
Currently on that way you are trying to update informations only in onCreate() which is called when Activity needs to be created. In this scenario it is when you exit and enter app again only by pressing Back button while on Home button it will not work as well until app is destroyed by OS.
You could also use onResume method which is called after Activity is returned from pause and that will happen when you create a new Activity upon already exiting one.

Flashlight function crashes after returning from activity

I have this android app which connects to an mqtt broker and listens for instructions to play/pause a ringtone or open/close the flashlight.
It runs as supposed to until i change my settings and call the function flashOnOff after this. Then i get a null pointer exception but i can not understand why.
This is my code (i did not include my imports to save some space):
public class MainActivity extends AppCompatActivity {
// Layout related parameters
Toolbar myToolbar;
Spinner mySpinner;
ImageButton flashlightButton;
Button ringtone;
EditText message;
// Camera/flashlight related parameters
Camera camera;
Camera.Parameters parameters;
// MQTT related parameters
private String BrokerIp = "tcp://192.168.1.3:1883";
private int qos = 2;
static String Username = "user1";
static String Password = "user1";
String topicStr = "commands";
String clientId = "AndroidClient";
MqttConnectOptions options;
MqttAndroidClient client;
Vibrator vibrator;
// Ringtone related parameters
Ringtone myRingtone;
MediaPlayer ringtoneMP ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
myRingtone = RingtoneManager.getRingtone(getApplicationContext(),uri);
myToolbar = (Toolbar) findViewById(R.id.toolbar);
mySpinner = (Spinner) findViewById(R.id.spinner);
flashlightButton = (ImageButton) findViewById(R.id.image);
myToolbar.setLogo(R.drawable.twoguyswatchmrrobot);
myToolbar.setTitle(getResources().getString(R.string.app_name));
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_itam,
getResources().getStringArray(R.array.Toolbar_dropdown_entries));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(myAdapter);
ringtoneMP = MediaPlayer.create(this,R.raw.games_of_thrones);
ringtone = (Button) this.findViewById(R.id.ringtone);
message = (EditText)findViewById(R.id.messagePublish);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,
mySpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT)
.show();
if (mySpinner.getSelectedItem().toString().equals("Exit App")){
exit();
}else if(mySpinner.getSelectedItem().toString().equals("Settings"))
{
Intent intent;
intent = new Intent(MainActivity.this, SettingsActivity.class);
intent.putExtra("CURRENT_IP",client.getServerURI());
intent.putExtra("CURRENT_QOS", Integer.toString(qos));
intent.putExtra("CURRENT_TOPIC",topicStr);
startActivityForResult(intent,1); // this is so we can take the results back to mainActivity later
}else{
System.out.println("ara3e, den exw diale3ei tipota");
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
//Flashlight on Create start
if(isFlashAvailable()) // check if flash is available on this device, if it is open camera (module) and make button clickable
{
camera = Camera.open();
parameters = camera.getParameters();
}else
{ // if flashlight is not supported dont let the user click the button
flashlightButton.setEnabled(false);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error.");
builder.setMessage("Flashlight not available on this device. \nExit?"); // inform the user and let him choose how to continue
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
exit();
}
});
builder.setNegativeButton("Stay without flashlight", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
flashlightButton.setOnClickListener(new View.OnClickListener() { // listen for flash button clicks
#Override
public void onClick(View view) {
flashOnOff();
}
});
ringtone.setOnClickListener(new View.OnClickListener() { // Ringtone listener
#Override
public void onClick(View view) {
ringtoneOnOff(ringtoneMP);
}
});
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
// client = pahoMqttClient.getMqttClient(MainActivity.this,BrokerIp,clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
Log.d("Connection:"," Lost");
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.d("Delivery"," completed with iMqttDeliveryToken: " + iMqttDeliveryToken);
}
});
}
//Flashlight start
#Override
protected void onStop() {
super.onStop();
if(camera!=null)
{
camera.release();
camera = null;
}
}
//Flashlight end
//Backkey exit confirmation
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit application?")
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
// when yes is clicked exit the application
public void onClick(DialogInterface arg0, int arg1) {
exit();
}
})
.setNegativeButton("No", new
DialogInterface.OnClickListener() {
// when no is clicked do nothing
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
//Backkey end
// PUBLISH MESSAGE
private void setSubscription(MqttAndroidClient client, String topic, int qos){
try{
client.subscribe(topic, qos);
}
catch (MqttException e){
e.printStackTrace();
}
}
private void unsetSubscription(MqttAndroidClient client,String topic){
try{
client.unsubscribe(topic);
}catch (MqttException e){
e.printStackTrace();
}
}
public void conn(View v){
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
// pub();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "not connected", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconn(View v){
if (client.isConnected()) {
try {
IMqttToken token = client.disconnect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "could not disconnect", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}else {
Toast.makeText(MainActivity.this, "Client is already disconnected", Toast.LENGTH_LONG).show();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void pub(View v) {
String topic = topicStr;
try {
client.publish(topic, String.valueOf(message.getText()).getBytes(),qos,false);
} catch (MqttException e) {
e.printStackTrace();
}
}
private void ringtoneOnOff(MediaPlayer ringtoneMP){
if (ringtoneMP.isPlaying()){
ringtoneMP.pause();
}else{
ringtoneMP.start();
}
}
private void myMessageArrived(String s,MqttMessage mqttMessage){
if ((mqttMessage.toString()).equals("Flash on")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Flashlight already on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Turning flashlight on", Toast.LENGTH_SHORT).show();
flashOnOff();
}
} else if ((mqttMessage.toString()).equals("Flash off")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Turning flashlight off", Toast.LENGTH_SHORT).show();
flashOnOff();
} else {
Toast.makeText(MainActivity.this, "Flashlight already off", Toast.LENGTH_SHORT).show();
}
} else if ((mqttMessage.toString()).equals("Ringtone on")) {
if (ringtoneMP.isPlaying()) {
Toast.makeText(MainActivity.this, "Ringtone already playing", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Playing ringtone", Toast.LENGTH_SHORT).show();
ringtoneMP.start();
}
} else if ((mqttMessage.toString()).equals("Ringtone off")) {
if (ringtoneMP.isPlaying()) {
ringtoneMP.pause();
} else {
Toast.makeText(MainActivity.this, "Ringtone already not being played", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("INFO:", "This Command does not exist");
}
vibrator.vibrate(500);
myRingtone.play();
}
public void exit(){
finish();
System.exit(0);
}
public boolean isFlashAvailable(){ // boolean function that returns true if flash is supported on this device
return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
public void flashOnOff(){ // self explanatory
if (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH)){ // if the flash is on torch mode
Log.d("BHKE","408");
this.flashlightButton.setImageResource(R.drawable.off);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // turn it off
}else{
Log.d("BHKE","412");
this.flashlightButton.setImageResource(R.drawable.on);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); // else turn it on
}
this.camera.setParameters(this.parameters);
this.camera.startPreview();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String tempBrokerIp;
String temptopic="";
Integer tempqos;
Boolean BrokerIpChanged = true;
Boolean qosChanged = true;
Boolean topicChanged = true;
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (1) : {
if (resultCode == Activity.RESULT_OK) {
tempBrokerIp = data.getStringExtra("CURRENT_IP");
tempqos = Integer.parseInt(data.getStringExtra("CURRENT_QOS"));
temptopic = data.getStringExtra("CURRENT_TOPIC");
Log.d("Info BROKER, TOPIC, QOS", ":"+ tempBrokerIp+ " " + temptopic+ " " + tempqos);
if (tempBrokerIp.equals(BrokerIp)) {
BrokerIpChanged=false;
Log.i("BrokerIpChanged =", BrokerIpChanged.toString());
}
if (tempqos.equals(qos)) {
qosChanged=false;
Log.i("qosChanged =", qosChanged.toString());
}else {
qos = tempqos;
}
if (temptopic.equals(topicStr)){
topicChanged=false;
Log.i("topicChanged =", topicChanged.toString());
}else{
topicStr = temptopic;
}
if (!BrokerIpChanged && !qosChanged && !topicChanged) return;
if (BrokerIpChanged){
try {
client.disconnect();
BrokerIp = tempBrokerIp;
topicStr = temptopic;
qos = tempqos;
// final String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
// options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1); // to user the latest mqtt version
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
Log.w("Mqtt","Connected to:"+ BrokerIp);
try{
Log.v("INFO 11111:", "about to subscribe with: "+ topicStr + qos);
client.subscribe(topicStr,qos);
}catch (MqttException e){
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
System.out.println(client.isConnected());
// if (client.isConnected()){
// Log.v("INFO 22222:", "about to subscribe with: "+ temptopic + tempqos);
// client.subscribe(temptopic,tempqos);
// }
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}catch (MqttException e){
e.printStackTrace();
}
}else
{
try {
client.unsubscribe(topicStr);
client.subscribe(temptopic,tempqos);
topicStr = temptopic;
qos = tempqos;
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public boolean isFlashOn(){
return (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH));
}
I can provide the settings activity code too is needed
It seems that the two variables needed for the flashOnOff where not initiallized after i returned from the settings activity.
Ι added :
if (isFlashAvailable()){
camera = Camera.open();
parameters = camera.getParameters();
}
at the onActivityResult start and it works like a charm.

load image with image-chooser-library

I try to use this library https://github.com/coomar2841/image-chooser-library to load image on my application.
When I select a image, I have this message "could'nt process no such file"
My code:
public class EditListeModelActivity extends Activity implements ImageChooserListener{
EditText titre;
CheckBox isvisible;
ActionBar actionBar;
ImageView ProfileImage;
private static int RESULT_LOAD_IMAGE = 1;
private boolean imageModifie=false;
private Bitmap newImage;
Builder b;
private ProgressBar pbar;
private ImageChooserManager imageChooserManager;
private String filePath;
private int chooserType;
private String uriFile;
private Button btnValide;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_liste_model);
if(savedInstanceState!=null)
{
if (savedInstanceState.containsKey("uri_path")) {
uriFile = savedInstanceState.getString("uri_path");
}
}
actionBar = getActionBar();
actionBar.setDisplayOptions( ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_SHOW_TITLE|ActionBar.DISPLAY_SHOW_CUSTOM);
titre=(EditText)findViewById(R.id.nomEdit);
isvisible=(CheckBox)findViewById(R.id.isvisible);
btnValide=(Button)findViewById(R.id.EditListeModelNow);
ProfileImage = (ImageView) findViewById(R.id.profileImageEdit);
if(uriFile==null)
{
}
else
{
ProfileImage.setImageURI(Uri.parse(uriFile));
newImage=BitmapFactory.decodeFile(uriFile);
ProfileImage.setImageBitmap(newImage);
imageModifie=true;
}
b = new Builder(this);
b.setTitle("Choisir photo");
String[] types = {"Prendre une nouvelle photo", "Choisir une photo existante"};
b.setItems(types, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch(which){
case 0:
takePicture();
break;
case 1:
chooseImage();
break;
}
}
});
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
b.show();
//chooseImage();
/*
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);*/
}
});
pbar = (ProgressBar) findViewById(R.id.progressBarEditProfile);
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_liste_model, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK
&& (requestCode == ChooserType.REQUEST_PICK_PICTURE || requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
if (imageChooserManager == null) {
reinitializeImageChooser();
}
Log.e("imageChooserManager data ",data.toString());
imageChooserManager.submit(requestCode, data);
} else {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
}
}
#Override
public void onImageChosen(final ChosenImage image) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
if (image != null) {
File f=new File(image.getFileThumbnail());
ProfileImage.setImageURI(Uri.parse(f.toString()));
uriFile=f.toString();
newImage=BitmapFactory.decodeFile(f.toString());
ProfileImage.setImageBitmap(newImage);
imageModifie=true;
}
}
});
}
#Override
public void onError(final String reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
pbar.setVisibility(View.GONE);
ProfileImage.setVisibility(View.VISIBLE);
Toast.makeText(EditListeModelActivity.this, reason,
Toast.LENGTH_LONG).show();
}
});
}
// Should be called if for some reason the ImageChooserManager is null (Due
// to destroying of activity for low memory situations)
private void reinitializeImageChooser() {
imageChooserManager = new ImageChooserManager(this, chooserType,
"myfolder", true);
imageChooserManager.setImageChooserListener(this);
imageChooserManager.reinitialize(filePath);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("chooser_type", chooserType);
outState.putString("media_path", filePath);
outState.putString("uri_path", uriFile);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("chooser_type")) {
chooserType = savedInstanceState.getInt("chooser_type");
}
if (savedInstanceState.containsKey("media_path")) {
filePath = savedInstanceState.getString("media_path");
}
if (savedInstanceState.containsKey("uri_path")) {
uriFile = savedInstanceState.getString("uri_path");
}
}
}
private void takePicture() {
chooserType = ChooserType.REQUEST_CAPTURE_PICTURE;
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_CAPTURE_PICTURE, "myfolder", true);
imageChooserManager.setImageChooserListener(this);
try {
pbar.setVisibility(View.VISIBLE);
ProfileImage.setVisibility(View.GONE);
filePath = imageChooserManager.choose();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void chooseImage() {
chooserType = ChooserType.REQUEST_PICK_PICTURE;
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_PICK_PICTURE, "myfolder", true);
imageChooserManager.setImageChooserListener(this);
try {
pbar.setVisibility(View.VISIBLE);
ProfileImage.setVisibility(View.GONE);
filePath = imageChooserManager.choose();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
At ligne `Log.e("imageChooserManager data ",data.toString());
the result is
Intent { dat=content://com.android.providers.media.documents/document/image:22501 flg=0x1 }
I think that the probleme is where is stoked my image. How I do to load my image in my application?
That is a Uri. A Uri is not a file, and so you cannot pass it to decodeFile() on BitmapFactory. Either use an image loading library like Picasso or Universal Image Loader, or have your own background thread that uses openInputStream() on a ContentResolver to read in the contents of that Uri, passing the stream to decodeStream() on BitmapFactory.

Android contact picker returning nulll (resultCode == 0)

I'm new to Android and I'm trying to attach a contact picker to a form. This "contact picker code" works well when I test it with other forms but with this form, the resultCode = RESULT_CANCELED. I have checked other examples, but it doesn't work with this from but still works with other forms.
public class EmergencyButtonActivity extends Activity {
static private MoreEditText mPhonesMoreEditText = null;
private static final String DEBUG_TAG = "EmergencyButtonActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, new StackMailer());
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first phone
if (cursor.moveToFirst()) {
phone = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtPhoneNo.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Phone : "+ phone, Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
private void popup(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyButtonActivity.this);
builder.setMessage(text)
.setTitle(title)
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void initUI() {
setContentView(R.layout.main);
this.restoreTextEdits();
ImageButton btnEmergency = (ImageButton) findViewById(R.id.btnEmergency);
btnEmergency.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// try sending the message:
EmergencyButtonActivity.this.redButtonPressed();
}
});
ImageButton btnHelp = (ImageButton) findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupHelp();
}
});
}
public void popupHelp() {
final String messages [] = {
"Welcome To App xxxxxx",
"XXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXX."
};
// inverted order - They all popup and you hit "ok" to see the next one.
popup("3/3", messages[2]);
popup("2/3", messages[1]);
popup("1/3", messages[0]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
initUI();
}
private class StackMailer implements ExceptionHandler.StackTraceHandler {
public void onStackTrace(String stackTrace) {
EmailSender.send("a#zzz.com", "Error", "ButtonError\n" + stackTrace);
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
initUI();
//IntroActivity.openOnceAfterInstallation(this);
helpOnceAfterInstallation();
}
#Override
protected void onPause() {
super.onPause();
this.saveTextEdits();
}
#Override
protected void onStop() {
super.onStop();
}
public void helpOnceAfterInstallation() {
// runs only on the first time opening
final String wasOpenedName = "wasOpened";
final String introDbName = "introActivityState";
SharedPreferences settings = this.getSharedPreferences(introDbName, Context.MODE_PRIVATE);
boolean wasOpened = settings.getBoolean(wasOpenedName, false);
if (wasOpened) {
return;
}
// mark that it was opened once
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(wasOpenedName, true);
editor.commit();
popupHelp();
}
private class EditTextRow {
LinearLayout mLinlay;
EditText mEditText;
ImageButton mRemoveBtn;
public EditTextRow(String text, EditText example) {
mEditText = new EditText(EmergencyButtonActivity.this);
mEditText.setLayoutParams(example.getLayoutParams());
mEditText.setText(text);
mEditText.setInputType(example.getInputType());
mRemoveBtn = new ImageButton(EmergencyButtonActivity.this);
mRemoveBtn.setBackgroundResource(R.drawable.grey_x);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mRemoveBtn.setLayoutParams(params);
mLinlay = new LinearLayout(EmergencyButtonActivity.this);
mLinlay.setOrientation(LinearLayout.HORIZONTAL);
mLinlay.addView(mEditText);
mLinlay.addView(mRemoveBtn);
}
}
private class MoreEditText {
private LinearLayout mContainer;
private ArrayList<EditText> mEditTextList = null;
public MoreEditText(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from scratch, this should only happen onCreate
mContainer = container;
mEditTextList = new ArrayList<EditText>();
EditText edit;
edit = textWidget;
if(! stringsList.isEmpty()) {
edit.setText(stringsList.get(0));
}
mEditTextList.add(edit);
for (int i = 1; i < stringsList.size(); i++) {
addRow(stringsList.get(i));
}
}
public void restore(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from older existing rows, this can happen on
// changes of orientation, onResume, etc
mContainer = container;
for(int i = 0; i < mEditTextList.size(); i++) {
EditText edit;
if (i == 0) {
edit = textWidget;
mEditTextList.set(0, edit);
if (stringsList.size() > 0) {
edit.setText(stringsList.get(0));
}
} else {
edit = mEditTextList.get(i);
View viewRow = (LinearLayout) edit.getParent();
((LinearLayout)viewRow.getParent()).removeView(viewRow);
mContainer.addView(viewRow);
}
}
}
#SuppressWarnings("unused")
public EditText getDefaultTextEdit(LinearLayout container) {
// TODO: turn this into something like "getEditTextChild" rather than counting on the index "0"
return (EditText) ((LinearLayout)container.getChildAt(0)).getChildAt(0);
}
public void removeRow(EditText editText) {
mContainer.removeView((View) editText.getParent());
mEditTextList.remove(editText);
}
public void addRow(String text) {
final EditTextRow editRow = new EditTextRow(text, mEditTextList.get(0));
editRow.mRemoveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MoreEditText.this.removeRow(editRow.mEditText);
}
});
mContainer.addView(editRow.mLinlay);
mEditTextList.add(editRow.mEditText);
}
public List<String> GetTexts() {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < mEditTextList.size(); i ++) {
texts.add(mEditTextList.get(i).getText().toString());
}
return texts;
}
}
private void addPhonesEmailsUI(List<String> phones, List<String> emails) {
LinearLayout phoneNoLin = (LinearLayout)findViewById(R.id.linPhoneNo);
EditText txtPhoneNo = (EditText)findViewById(R.id.txtPhoneNo);
// NOTE: we don't always create from scratch so that empty textboxes
// aren't erased on changes of orientation.
if (mPhonesMoreEditText == null) {
mPhonesMoreEditText = new MoreEditText(phoneNoLin, txtPhoneNo, phones);
} else {
mPhonesMoreEditText.restore(phoneNoLin, txtPhoneNo, phones);
}
}
public void restoreTextEdits() {
EmergencyData emergencyData = new EmergencyData(this);
addPhonesEmailsUI(emergencyData.getPhones(), emergencyData.getEmails());
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(emergencyData.getMessage());
}
#SuppressWarnings("unused")
public void saveTextEdits() {
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
EmergencyData emergencyData = new EmergencyData(this);
emergencyData.setPhones(mPhonesMoreEditText.GetTexts());
emergencyData.setMessage(txtMessage.getText().toString());
}
public void redButtonPressed() {
this.saveTextEdits();
EmergencyData emergency = new EmergencyData(this);
if ((emergency.getPhones().size() == 0) && (emergency.getEmails().size() == 0)) {
Toast.makeText(this, "Enter a phone number or email.",
Toast.LENGTH_SHORT).show();
return;
}
EmergencyActivity.armEmergencyActivity(this);
Intent myIntent = new Intent(EmergencyButtonActivity.this, EmergencyActivity.class);
EmergencyButtonActivity.this.startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ebutton_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(Intent.ACTION_VIEW);
switch (item.getItemId()) {
case R.id.project_page:
i.setData(Uri.parse("http://#/"));
startActivity(i);
break;
case R.id.credits:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.credits_dialog);
dialog.setTitle("Credits");
TextView text = (TextView) dialog.findViewById(R.id.textView);
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.credits);
byte[] b = new byte[in_s.available()];
in_s.read(b);
text.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
text.setText("Error: can't show credits.");
}
dialog.show();
break;
}
return true;
}
}
Finally found a solution, the problem was with the android:launchMode in the manifest.

Sharing Image and Text On twitter not working

This is my code given below.FrameLayout is Used to share as JPEG Image on twitter.This is the code Im trying .
sharesp=(Spinner)findViewById(R.id.spnrShare);
sharesp.setAdapter(new MyShAdapter(MainActivity.this, R.layout.rowview, Sharestring));
sharesp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long arg3) {
// TODO Auto-generated method stub
selectitem=parent.getItemAtPosition(position).toString();
selecetint=position;
if(selectitem=="FaceBook" || selecetint==R.drawable.fbbtn){
shareFbook();
}
else if(selectitem=="Twitter" || selecetint==R.drawable.twitbtn){
shareTwitter();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
public void shareTwitter(){
FrameLayout savFrame_layout=(FrameLayout)findViewById(R.id.frame);
try {
if(MainActivity.this.mainFrame_layout==null){
MainActivity.this.mainFrame_layout.setDrawingCacheEnabled(true);
MainActivity.this.mainFrame_layout.refreshDrawableState();
MainActivity.this.mainFrame_layout.buildDrawingCache();
MainActivity.this.bm_ImgFrame = mainFrame_layout.getDrawingCache();
int i1=100000;
Random random=new Random();
i1=random.nextInt(i1);
MainActivity.fname = "Quick_"+ i1 + ".jpg";
String pathy=Environment.getExternalStorageDirectory()+File.separator+"/MYAnApps";
MainActivity.this.rootFile=new File(pathy);
MainActivity.this.sdImageMainDirectory = new File(MainActivity.this.rootFile + MainActivity.fname);
FileOutputStream fileOutputStream = new FileOutputStream(MainActivity.this.sdImageMainDirectory);
bm_ImgFrame.compress(CompressFormat.JPEG, 80, fileOutputStream);
Uri uri = Uri.parse(MainActivity.this.sdImageMainDirectory.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("/*");
intent.setClassName("com.twitter.android", "com.twitter.android.PostActivity");
intent.putExtra(Intent.EXTRA_TEXT, "MyAndroidApp: https://play.google.com/store/apps/details?id=com.example.MyApp");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(MainActivity.this.sdImageMainDirectory));
startActivity(intent);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try using "*/*" as MIME, so you can send any generic data type.
intent.setType("*/*");
Also try changing ACTION_SEND to ACTION_SEND_MULTIPLE which specialized for delivering multiple data.
More info about ACTION_SEND_MULTPLE and handling MIME types.
Check this Example this is working for me
Twitter Image And text sharing Example
twitter sharing using this one
private void showTwittDialog() {
final Dialog dialog = new Dialog(getApplicationContext());
dialog.setContentView(R.layout.twitt_dialog);
dialog.setTitle("Twitter");
Button btnPost = (Button) dialog.findViewById(R.id.btnpost);
final EditText et = (EditText) dialog.findViewById(R.id.twittext);
et.setText(sharingStr);
et.setSelection(et.getText().length());
btnPost.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
twitt_msg = et.getText().toString().trim();
if (twitt_msg.length() == 0) {
showToast("Tweet is empty!!!");
return;
} else if (twitt_msg.length() > 140) {
showToast("Tweet of more than 140 characters not allowed!!!");
return;
}
dialog.dismiss();
new PostTwittTask().execute(twitt_msg);
}
});
dialog.show();
}
protected void Share_to_twitter() {
Intent tweetIntent = new Intent();
tweetIntent.setType("text/plain");
tweetIntent.putExtra(Intent.EXTRA_TEXT, sharingStr);
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : list) {
twitter_dialog = resolveInfo.activityInfo.packageName;
}
if (twitter_dialog != null && twitter_dialog.startsWith("com.twitter.android")) {
// if the native twitter app is found
tweetIntent.setPackage(twitter_dialog);
startActivity(tweetIntent);
} else {
showTwittDialog();
}
mTwitter.resetAccessToken();
}
class PostTwittTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(getApplicationContext());
pDialog.setMessage("Posting Twitt...");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... twitt) {
try {
mTwitter.updateStatus(twitt[0]);
return "success";
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
return "Posting Failed because of Duplicate message...";
}
e.printStackTrace();
return "Posting Failed!!!";
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
if (null != result && result.equals("success")) {
View popUpView = getLayoutInflater().inflate(R.layout.share_successfully_popup,null);
final PopupWindow popUp = new PopupWindow(popUpView,UtilityClass.dynamicScalingForWidth(100),
UtilityClass.dynamicScalingForWidth(100),true);
popUp.showAtLocation(popUpView.findViewById(R.id.share_successfully_ctr),Gravity.CENTER,0, 0);
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
popUp.dismiss();
}
};
handler.postDelayed(r, 3000);
} else {
showToast(result);
}
super.onPostExecute(result);
}
}

Categories

Resources