How to add multiple locations in single EditText in android.We want to create Tags of locations.
I have to written code to add multiple location in single EditText in android.
void updateAddressLayout() {
final ViewGroup locationGroup = (ViewGroup) getActivity().findViewById(R.id.locationsLayout);
for (int i = locationGroup.getChildCount() - 1; i >= 0; i--) {
locationGroup.removeViewAt(i);
}
final LayoutInflater inflater =getActivity().getLayoutInflater();
for (int i=0; i < mylocations.size(); i++){
final View locationView = inflater.inflate(R.layout.include_location_tag_chip, locationGroup, false);
final TextView locationText = (TextView)locationView.findViewById(R.id.info_text);
final ImageView delImage = (ImageView)locationView.findViewById(R.id.icon_del);
final String primaryAddress = mylocations.get(i).getAddressLine(0) + " " + mylocations.get(i).getAddressLine(1) + " " + mylocations.get(i).getLocality() + " " + mylocations.get(i).getPostalCode();
locationText.setText(primaryAddress);
final int finalI = i;
delImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new AlertDialog.Builder(getActivity())
.setTitle("Alert!")
.setMessage("Are you sure you want to delete location ")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mylocations.remove(finalI);
locationGroup.removeViewAt(finalI);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
});
locationGroup.addView(locationView);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_GET_LOCATION) {
mCurrentAddress = data.getParcelableExtra("LOC_ADDRESS");
Toast.makeText(getActivity(),"You can add only three locations", Toast.LENGTH_LONG).show();
if (mCurrentAddress.getAddressLine(0) != null || mCurrentAddress.getAddressLine(1) != null || mCurrentAddress.getLocality() != null || mCurrentAddress.getPostalCode() != null) {
if (mylocations.size() <3) {
mylocations.put(mylocations.size(), (Address) data.getParcelableExtra("LOC_ADDRESS"));
}
updateAddressLayout();
}
return;
}
}
if (resultCode == Activity.RESULT_CANCELED && requestCode == REQUEST_GET_LOCATION) {
}
super.onActivityResult(requestCode, resultCode, data);
}
Related
public class DirectionActivity extends AppCompatActivity implements View.OnClickListener{
Button scanBtn;
TextView messageText, messageFormat, messageText2, messageFormat2, HTTPResult;
String Result = null;
QRResultData datum;
String myServer = "https://swulj.000webhostapp.com/bus_fetch.php";
String BUS_NUMBER= "EXTRA_BUS_NUMBER";
String Param = "PARAM";
String Stop = "STOP";
Context cntxt = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_direction);
scanBtn = findViewById(R.id.scanBtn);
messageText = findViewById(R.id.textContent);
messageFormat = findViewById(R.id.textFormat);
messageText2 = findViewById(R.id.textContent2);
messageFormat2 = findViewById(R.id.textFormat2);
HTTPResult = findViewById(R.id.HTTPResult);
// adding listener to the button
scanBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
IntentIntegrator intentIntegrator = new IntentIntegrator(this);
intentIntegrator.setPrompt("Scan a barcode or QR Code");
intentIntegrator.setOrientationLocked(true);
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
// if the intentResult is null then
// toast a message as "cancelled"
if (intentResult != null) {
if (intentResult.getContents() == null) {
Toast.makeText(getBaseContext(), "Cancelled", Toast.LENGTH_SHORT).show();
} else {
// if the intentResult is not null we'll set
// the content and format of scan message
Result = intentResult.getContents();
datum = parseResult(Result, myServer);
showDialog(cntxt);
//messageText.setText(Result);
//messageFormat.setText(intentResult.getFormatName());
messageText.setText(datum.seatNumber);
messageFormat.setText(datum.busNumber);
messageText2.setText(datum.original);
messageFormat2.setText(Result);
//Toast.makeText(getApplicationContext(),"You download is resumed2",Toast.LENGTH_LONG).show();
HTTPConnection1 conn = new HTTPConnection1();
conn.execute(datum);
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
public void showDialog(Context cntxt)
{
final CharSequence[] items = {"On-Direction", "Return-Direction"};
AlertDialog.Builder builder = new AlertDialog.Builder(cntxt);
builder.setTitle("Alert Dialog with ListView and Radio button");
//builder.setIcon(R.drawable.icon);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(cntxt, "Success", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(cntxt, "Fail", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public QRResultData parseResult(String Result, String urlArg)
{
QRResultData data = new QRResultData();
/*StringTokenizer multiTokenizer = new StringTokenizer(Result, ";");
if(multiTokenizer.hasMoreTokens())
{
data.busNumber = multiTokenizer.nextToken();
}
if(multiTokenizer.hasMoreTokens())
{
data.seatNumber = multiTokenizer.nextToken();
}*/
data.url = urlArg;
data.original = Result;
String[] split = Result.split(";");
data.busNumber = split[0];
if (split.length > 1) {
data.seatNumber = split[1];
}
return data;
}
.....
.....
I am trying to create a dialog. After the dialog shows, I should select on-direction or return-direction. If on-direction is selected, it should return true, if return-direction is selected, it should return false. But my dialog does not wait for user-inputs. It disappears after a moment.
I am trying to scan a barcode. after scanning the barcode, I am opening a dialog to get true or false. I will send the scanned result, boolean value to the HTTP SERVER.
I want my application to continue accepting image from the gallery if I chose Upload Image from the dialog box, but the problem is that the function will continue to finish (the log for count is printed even if I didn't pressed any button, and the conditional statement will set cont = false). The decision variable is a global string variable.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
boolean cont = true;
while (cont == true) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
functionHere();
}
if (requestCode == OPEN_DOCUMENT_CODE && resultCode == RESULT_OK) {
if (data != null) {
// this is the image selected by the user
try {
functionHere();
} catch (Exception ex) {
Log.i("Error", ex.toString());
}
}
}
continuePrompt();
if(decision == "Upload"){
requestCode = OPEN_DOCUMENT_CODE;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, OPEN_DOCUMENT_CODE);
}
else if(decision == "Take Picture"){
//code here
}
else if(decision == "End"){
cont = false;
}
else{
cont = false;
}
Log.d("Count", Integer.toString(count));
}
if (cont == false) {
//output result
}
}
Here is my code for my dialog which I get from another question here in stackoverflow
public void continuePrompt() {
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Platelet detection");
builder.setMessage("Are all microscopic slide image uploaded?");
// add the buttons
builder.setPositiveButton("Upload Image", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "Upload";
}
});
builder.setNeutralButton("Take Picture", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "Take Picture";
}
});
builder.setNegativeButton("End", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "End";
}
});
// create and show the alert dialog
builder.show();
}
you still have below line in your code
while (cont == true)
even when you show your dialog this loop is iterating over and over again. you should fix your logic, there shouldn't be any while loop, everything is already in UI thread and with above line you are hanging it showing dialogs one after another. you should show your prompt once and instead of setting global decision variable just place your code response for action in listener
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
functionHere();
continuePrompt();
}
else if (requestCode == OPEN_DOCUMENT_CODE && resultCode == RESULT_OK) {
if (data != null) {
// this is the image selected by the user
try {
functionHere();
continuePrompt();
} catch (Exception ex) {
Log.i("Error", ex.toString());
}
}
}
else{
super.onActivityResult(requestCode, resultCode, data);
}
}
private void continueFlow(){
if("Upload".equals(decision)){
requestCode = OPEN_DOCUMENT_CODE;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, OPEN_DOCUMENT_CODE);
}
else if("Take Picture".equals(decision)){
//code here
}
}
just call continueFlow(); after every decision change (in every listener). or move code form if("Upload".equals(decision)){ straight to setPositiveButton and so on
btw. decision == "Upload" won't ever be true as == operator is comparing same objects. decision is already declared variable and "Upload" String is freshly created in if statement, its brand new variable. for comparing content of Strings (same text) use stringOne.equals(stringTwo);
I have a Bitmap as a general variable to set, but when I run my App, it doesn't show anything.
Here my Code:
public AlertDialog FragmentDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.imagenfoto,null);
dg_image=view.findViewById(R.id.dlg_image);
dg_image.setImageBitmap(bitmap);
builder.setView(inflater.inflate(R.layout.imagenfoto,null))
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//dg_image.setImageBitmap(bitmap);
dialogInterface.cancel();
}
});
return builder.create();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode== getActivity().RESULT_OK && requestCode==10){
Uri path=data.getData();
foto.setImageURI(path);
}
*/
if(requestCode==CAMARA_REQUEST && resultCode==Activity.RESULT_OK){
Bitmap photo=(Bitmap)data.getExtras().get("data");
bitmap=(Bitmap)data.getExtras().get("data");
foto.setImageBitmap(photo);
Log.d("Debug",bitmap.toString());
//comunicador.setFoto(bitmap);
/*try {
setFoto(photo);
}catch (Exception e){
Log.d("setGaleria:",e.getMessage());
}*/
//cd_imagen.setImageBitmap(photo);
}
//***//
Uri selectedImageUri=null;
Uri selectedImage;
if(requestCode==SELECT_FILE && resultCode==Activity.RESULT_OK){
selectedImage=data.getData();
String selectedPath=selectedImage.getPath();
if(selectedPath != null){
InputStream imageStream=null;
try {
imageStream=getActivity().getContentResolver().openInputStream(
selectedImage);
}catch (FileNotFoundException e){
e.printStackTrace();
}
//Transformamos la URI de la imagen a ImputStream y este a un Bitmap
Bitmap bmp=BitmapFactory.decodeStream(imageStream);
bitmap=BitmapFactory.decodeStream(imageStream);
Log.d("Debug",bitmap.toString());
/*try {
setFoto(bmp);
}catch (Exception e){
Log.d("setGaleria:",e.getMessage());
}*/
//Ponemos nuestro Bitmap en un ImageView que tengamos en la vista
foto.setImageBitmap(bmp);
//comunicador.setFoto(bmp);
//cd_imagen.setImageBitmap(bmp);
}
}
}
you should pass the view on which you have set the bitmap
not the one using new inflator.
don't pass this
builder.setView(inflater.inflate(R.layout.imagenfoto,null))
instead, use the existing view
builder.setView(view)
Final code
public AlertDialog FragmentDialog(){
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
LayoutInflater inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.imagenfoto,null);
dg_image=view.findViewById(R.id.dlg_image);
dg_image.setImageBitmap(bitmap);
builder.setView(view))
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//dg_image.setImageBitmap(bitmap);
dialogInterface.cancel();
}
});
return builder.create();
}
function(element, percentX, percentY){
var tolerance = 0.01; //needed because the rects returned by getBoundingClientRect provide the position up to 10 decimals
if(percentX == null){
percentX = 100;
}
if(percentY == null){
percentY = 100;
}
var elementRect = element.getBoundingClientRect();
var parentRects = [];
while(element.parentElement != null){
parentRects.push(element.parentElement.getBoundingClientRect());
element = element.parentElement;
}
var visibleInAllParents = parentRects.every(function(parentRect){
var visiblePixelX = Math.min(elementRect.right, parentRect.right) - Math.max(elementRect.left, parentRect.left);
var visiblePixelY = Math.min(elementRect.bottom, parentRect.bottom) - Math.max(elementRect.top, parentRect.top);
var visiblePercentageX = visiblePixelX / elementRect.width * 100;
var visiblePercentageY = visiblePixelY / elementRect.height * 100;
return visiblePercentageX + tolerance > percentX && visiblePercentageY + tolerance > percentY;
});
return visibleInAllParents;
};
I have two different activities with which I want to interact, this means that I want to use the onActivityResult() method...
But when I use it, I just have this result code : RESULT_CANCELED... I dont understand why...
Could you please help me ?
Here is my MainActivity part, which calls the SecureKeyActivity below :
((TextView)layout.findViewById(R.id.profile_forgot_password)).setOnClickListener(new TextView.OnClickListener() {
#Override
public void onClick(View v2) {
dialog = new AlertDialog.Builder(MainActivity.this)
.setTitle("Mot de passe oublié")
.setMessage("L\'envoi de SMS peut engendrer des frais supplémentaires dont la Zwedge Corporation n\'est pas responsable.\nÊtes-vous sûr d\'avoir oublié votre mot de passe ?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface box, int which) {
Intent secureKey = new Intent(MainActivity.this, SecureKeyActivity.class);
secureKey.putExtra("securePass", Common.data.requestByName(((TextView)v.findViewById(R.id.connect_profile_pseudo)).getText().toString()).getPassword());
secureKey.putExtra("securePseudo", ((TextView)v.findViewById(R.id.connect_profile_pseudo)).getText().toString());
startActivityForResult(secureKey, 2890, null);
}
})
.setNegativeButton(R.string.no, null)
.create();
dialog.show();
}
});
MainActivity.onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO: Implement this method
Log.v("LoggerActivity", String.valueOf(requestCode));
if (requestCode == 2890) {
Log.v("LoggerActivity", resultCode + ";" + RESULT_OK + ";" + RESULT_CANCELED + ";" + RESULT_FAIL);
// never reached...
if (resultCode == RESULT_OK) {
new CustomToast(MainActivity.this, getLayoutInflater(), "SMS reçu de Zwedge : votre mot de passe est \"" + data.getStringExtra("Pass") + "\"", Toast.LENGTH_LONG, false).show();
}
if (resultCode == RESULT_CANCELED) {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
SecureKeyActivity :
public class SecureKeyActivity extends Activity {
int key;
int keyGot;
String pass;
String pseudo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_secure_key);
pass = getIntent().getStringExtra("securePass");
pseudo = getIntent().getStringExtra("securePseudo");
keyGot = Common.data.getSecureKey(Common.data.requestForId(pseudo));
TextWatcher watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence p1, int p2, int p3, int p4) {
// TODO: Implement this method
}
#Override
public void onTextChanged(CharSequence p1, int p2, int p3, int p4) {
try {
key = Integer.decode(p1.toString());
if (key == keyGot) {
Intent result = getIntent();
result.putExtra("Pass", pass);
Intent main = new Intent(SecureKeyActivity.this, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
setResult(RESULT_OK, result);
finish();
startActivity(main);
}
} catch (NumberFormatException e) {}
}
#Override
public void afterTextChanged(Editable p1) {
// TODO: Implement this method
}
};
((EditText)findViewById(R.id.insert_key)).addTextChangedListener(watcher);
}
}
So...I just logged the results...and it seems that these arent the same in my activities...RESULT_CANCELED = RESULT_OK and RESULT_OK = RESULT_CANCELED (first is MainActivity result, second is SecureKeyActivity result)
i read DialogFragment, and make one in one like this.
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
public class MyDialogFragment extends DialogFragment {
public static MyDialogFragment newInstance(int title) {
MyDialogFragment frag = new MyDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.plus_icon)
.setTitle(title)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AddExerciseFragment.doPositiveClick();
}
}
)
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AddExerciseFragment.doNegativeClick();
}
}
)
.create();
}
}
and in another SherlockFragment i make next:
public void doPositiveClick() {
}
public void doNegativeClick() {
}
void showDialog() {
DialogFragment newFragment = MyDialogFragment.newInstance(
R.string.name);
newFragment.show(getFragmentManager(), "dialog");
}
But methods doPositiveClick(),doNegativeClick() wants to be static - it is bad for me.
public void doPositiveClick() {
DialogFlag = 0;
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
// dialog.cancel();
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
String path = null;
if (DialogFlag == 0) {
switch (requestCode) {
case GALLERY_REQUEST:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
path = getRealPathFromURI(selectedImage);
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
if (DialogFlag == 1) {
Uri uri;
if (requestCode == CAMERA_RESULT) {
Cursor cursor = getActivity().getContentResolver().query(
Media.EXTERNAL_CONTENT_URI,
new String[] { Media.DATA, Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION },
Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToFirst()) {
do {
uri = Uri.parse(cursor.getString(cursor
.getColumnIndex(Media.DATA)));
path = uri.toString();
} while (cursor.moveToNext());
cursor.close();
}
Log.d("myLogs", path);
if (btnID == 1) {
pathOne = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathOne);
ivOne.setImageBitmap(bmImg);
one = bmImg;
} else {
pathTwo = path;
Bitmap bmImg = BitmapFactory.decodeFile(pathTwo);
ivTwo.setImageBitmap(bmImg);
two = bmImg;
}
}
}
}
In your Fragment class
Declare the below
public static final int DIALOG_FRAGMENT = 1;
public static final int RESULT_OK = 101;
Then
DialogFragment newFragment = MyDialogFragment.newInstance(
R.string.name);
newFragment.setTargetFragment(SherLockFragmentName.this, DIALOG_FRAGMENT);
newFragment.show(getFragmentManager(), "dialog");
Then in Dialog Fragment
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Intent i =getActivity().getIntent();
i.putExtra("key", true);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//AddExerciseFragment.doNegativeClick();
Intent i =getActivity().getIntent();
i.putExtra("key", false);
getTargetFragment().onActivityResult(getTargetRequestCode(), 101, i);
}
}
)
Then override onActivityResult in Fragment class
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case DIALOG_FRAGMENT:
if (resultCode == RESULT_OK) {
boolean check = data.getBooleanExtra("key", true);
if(check)
{
dopositiveClick();
}
else
{
donegativeClick();
}
}
break;
}
}
If you don't want want a static access here's another option:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
final AddExerciseFragment aef = new AddExerciseFragment(SomeParameters...);
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.plus_icon)
.setTitle(title)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
aef.doPositiveClick();
}
//and so on