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.
Related
I have created an app in which the user can take pics using their default camera.It works fine in older versions that is till lollipop but when i try to run the app in marshmallow the app gets closed.
So i have added some codes to give permission for the camera app by the user but even it is not working.
public class Cam extends Activity{
String receivingdata;
TextView namecat;
String amount,vat;
private static final String TAG = Cam.class.getSimpleName();
ImageButton imgview,imgchart,imgexit;
Boolean isInternetPresent = false;
ConnectionDetector cd;
AlertDialog alert;
ImageButton btgoback,btcaptureagain,btnpreview;
static TextView tv;
private ImageView imgPreview;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
public static Bitmap bitmap;
final Context context=this;
ConnectionClass connectionClass;
private static final String IMAGE_CAPTURE_FOLDER = "Receipt";
private static final int CAMERA_PIC_REQUEST = 1111;
private static File file;
private Uri ImagefileUri;
private static final String PREF_FIRSTLAUNCH_HELP = "helpcmaera";
private boolean helpDisplayed = false;
private static final String LOGIN_URL = "http://balajee2777-001-site1.1tempurl.com/backup-07032016/Receiptphp/receipts.php";
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Receipt");
alertDialogBuilder
.setMessage("Would you Like to go previous Page!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent i=new Intent(Cam.this,ListAct.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camcod);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Bundle b = getIntent().getExtras();
receivingdata = b.getString("key");
tv = (TextView)findViewById(R.id.camcodname);
tv.setText(receivingdata);
tv.setVisibility(View.INVISIBLE);
String[] bits=receivingdata.split("_");
String catname = bits[0];
String vatname= bits[1];
connectionClass= new ConnectionClass();
imgPreview = (ImageView) findViewById(R.id.imgpreview);
namecat=(TextView)findViewById(R.id.tvcatnamess);
namecat.setText(catname);
imgview=(ImageButton)findViewById(R.id.camlinearrecep);
imgchart=(ImageButton)findViewById(R.id.camlinearchart);
imgexit=(ImageButton)findViewById(R.id.camlinearexit);
btgoback=(ImageButton)findViewById(R.id.bgoback);
btnpreview=(ImageButton)findViewById(R.id.btnpreview);
btcaptureagain=(ImageButton)findViewById(R.id.bcaptureagain);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
showHelpForFirstLaunch();
btgoback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isInternetPresent) {
showreceipt();
}else{
neti();
}
}
});
btnpreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Cam.this,DeleteMainAct.class);
startActivity(i);
}
});
btcaptureagain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
});
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to view receipts!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Viewreceipt.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgchart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to see report!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Chartboy.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode==CAMERA_PIC_REQUEST){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
Toast.makeText(this,"Camera permission not granted",Toast.LENGTH_SHORT).show();
}
}else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
private void showHelpForFirstLaunch() {
helpDisplayed = getPreferenceValue(PREF_FIRSTLAUNCH_HELP, false);
if (!helpDisplayed) {
showHelp();
savePreference(PREF_FIRSTLAUNCH_HELP, true);
}else if(helpDisplayed){
return;
}
}
private void showHelp() {
final View instructionsContainer = findViewById(R.id.container_help);
instructionsContainer.setVisibility(View.VISIBLE);
instructionsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
instructionsContainer.setVisibility(View.INVISIBLE);
}
});
}
private boolean getPreferenceValue(String key, boolean defaultValue) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
return preferences.getBoolean(key, defaultValue);
}
private void savePreference(String key, boolean value) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private File getFile() {
String filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath, IMAGE_CAPTURE_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
String names=tv.getText().toString();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(file + File.separator + names+"_"+timeStamp
+ ".jpg");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
imgPreview.setVisibility(View.VISIBLE);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int dw = size.x;
int dh = size.y;
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
imgPreview.setImageBitmap(bmp);
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void neti() {
final LayoutInflater layoutInflater = LayoutInflater.from(Cam.this);
final View promptView = layoutInflater.inflate(R.layout.connectionlost, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false);
final Button retry=(Button)promptView.findViewById(R.id.btnretry);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=getIntent();
finish();
startActivity(intent);
}
});
alert= alertDialogBuilder.create();
alert.show();
}
private void showreceipt() {
LayoutInflater repcard=LayoutInflater.from(Cam.this);
View promptView=repcard.inflate(R.layout.moneyreceipt,null);
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setView(promptView);
final EditText amt=(EditText)promptView.findViewById(R.id.edamt);
final EditText vta=(EditText)promptView.findViewById(R.id.edvat);
final TextView tvs=(TextView)promptView.findViewById(R.id.tvamount);
final TextView tvat=(TextView)promptView.findViewById(R.id.tvvat);
tvs.setVisibility(View.INVISIBLE);
tvat.setVisibility(View.INVISIBLE);
amt.setRawInputType(Configuration.KEYBOARD_12KEY);
vta.setRawInputType(Configuration.KEYBOARD_12KEY);
final Button save=(Button)promptView.findViewById(R.id.btnmoneysave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tvs.setText(amt.getText().toString());
tvat.setText(vta.getText().toString());
amount=tvs.getText().toString();
vat=tvat.getText().toString();
// Toast.makeText(Cam.this, amount, Toast.LENGTH_LONG).show();
//Toast.makeText(Cam.this, vat, Toast.LENGTH_LONG).show();
detailsreceiptupload();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void detailsreceiptupload() {
String[] bits=receivingdata.split("_");
String catname = bits[0];
String cdte=bits[1];
String[] nyte=cdte.split("#");
String email=nyte[0];
String cdate=nyte[1];
String cimagetag=tv.getText().toString();
//String amt=tvs.getText().toString();
userLogin(catname, cdate,email,cimagetag,amount,vat);
}
private void userLogin(String catname, String cdate, String email, String cimagetag, String amount, String vat) {
class UserLoginClass extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Cam.this, "Connecting to Cloud", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")) {
DoLogin dologin=new DoLogin();
dologin.execute("");
}
else
{
Toast.makeText(Cam.this,s,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("catname",params[0]);
data.put("cdate",params[1]);
data.put("email",params[2]);
data.put("cimagetag",params[3]);
data.put("amount",params[4]);
data.put("vat",params[5]);
RegisterUserClass ruc = new RegisterUserClass();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(catname,cdate,email,cimagetag,amount,vat);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DoLogin extends AsyncTask<String,String,String> {
String z="";
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
File destinationdir = new File(Environment.getExternalStorageDirectory() ,"/CompressedImage");
if (!destinationdir.exists()) {
destinationdir.mkdirs();
}
for(File file1:files){
FileOutputStream fos=null;
try{
File file=new File(destinationdir,file1.getName());
fos=new FileOutputStream(file);
Bitmap bm = BitmapFactory.decodeFile(file1.getAbsolutePath());
bm.compress(Bitmap.CompressFormat.JPEG, 25, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), destinationdir.getPath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
file.delete();
}
Intent i=new Intent(Cam.this,ReceiptGrid.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Cam.this.finish();
dismissDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}}
I have used an condition to check the phones version.If it is marshmallow then i have given a method name showcamera to do the functions for marshmallow
ShowCamera:
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
I want to make an application in the way that when I speak, can answer me without the necessity of press any button. I want that my recordings guard on a string, and then depending of the record, the TTS can answer diferent things. This is my source code.
protected static final int RESULT_SPEACH =1;
private Button record, speak;
TextToSpeech t1;
String SpokedText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mai);
record = (Button) findViewById(R.id.record);
speak = (Button) findViewById(R.id.speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reconize = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
try {
startActivityForResult(reconize, RESULT_SPEACH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Your divece cannot execute this kind of operation", Toast.LENGTH_LONG);
t.show();
}
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode,resultCode,Data);
switch (requestCode) {
case RESULT_SPEACH: {
if (resultCode == RESULT_OK && null != Data) {
final String spoked = (RecognizerIntent.EXTRA_RESULTS);
if (spoked == "Good Morning") {
String SpokedText= "Good Morning";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
} else {
if (spoked== "I need your help") {
String SpokedText= "Alright sir";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.getDefault());
}
}
});
}}
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);
}
I'm trying get name and email from a facebook session opened. I want to get these informations an add in a EditText. When I try get these informations the Facebook is opened to type my login and password to access after this doesn't return the informations.
How can I do it ?
I'm trying this.
public class CadUsuarioFrag extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener{
private EditText etNome, etEmail, etSenha;
private ImageButton ibImage;
private Button btnSingUp;
private String pathImage;
private static final int RESULT_LOAD_IMAGE = 1;
private ProgressDialog progress;
private final String TAG = getClass().getSimpleName() + "->";
//radiogroup
private RadioGroup rgTipoCad;
//
private String nome = "";
private String email = "";
private String senha = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CustomDrawerLayout)getActivity()).getSupportActionBar().hide();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
pathImage = cursor.getString(columnIndex);
cursor.close();
}
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.form_cadusuario, container, false);
etNome = (EditText)view.findViewById(R.id.etNome);
etEmail = (EditText)view.findViewById(R.id.etEmail);
etSenha = (EditText)view.findViewById(R.id.etSenha);
ibImage = (ImageButton)view.findViewById(R.id.ibImage);
btnSingUp = (Button)view.findViewById(R.id.btnSingUp);
rgTipoCad = (RadioGroup)view.findViewById(R.id.rgTipoCad);
//listeners
rgTipoCad.setOnCheckedChangeListener(this);
ibImage.setOnClickListener(this);
btnSingUp.setOnClickListener(this);
etNome.requestFocus();
return view;
}
#Override
public void onClick(View v) {
if(v == ibImage){
Intent i = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}else if(v == btnSingUp){
if(checkFields()){
addUsuario();
}
}
}
/** verifica se todos os campos foram informados para o insert */
private boolean checkFields(){
nome = etNome.getText().toString().trim();
email = etEmail.getText().toString().trim();
senha = etSenha.getText().toString().trim();
int selected = rgTipoCad.getCheckedRadioButtonId();
if(nome.length() == 0 || email.length() == 0 || senha.length() == 0){
Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
etNome.requestFocus();
etNome.selectAll();
return false;
}else{
return true;
}
}
private void addUsuario(){
progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
progress.show();
Usuario u = new Usuario(nome, email, senha, "1");
JsonObjectRequest app = new UsuarioDAO().addUsuario(u, new UsuarioAdapter(){
#Override
public void onUsuarioCadastrado(Boolean value) {
if(!value){
Toast.makeText(getView().getContext(), "Usuário não cadastrado", Toast.LENGTH_SHORT).show();
}else{
sucesso();
}
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
private void sucesso(){
AlertDialog.Builder alert = new AlertDialog.Builder(getView().getContext());
alert.setTitle("Guia Store");
alert.setMessage("Obrigado por se cadastrar\nEfetue agora seu login para acesso");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
FragmentTransaction ft;
Fragment frag;
frag = new LoginFrag();
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fl, frag, "InicioFrag");
ft.commit();
removeFrag();
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.rbGuiaStore){
//Log.i(TAG, "rbGuiaStore selecionado");
etNome.setHint("Nome");
etEmail.setHint("Email");
etSenha.setHint("Senha");
etNome.requestFocus();
}else{
//Log.i(TAG, "rbFacebook selecionado");
etNome.setHint("Nome");
etEmail.setHint("Email facebook");
etSenha.setHint("Senha facebook");
etNome.requestFocus();
checkFacebookSession();
}
}
private void checkFacebookSession(){
// start Facebook Login
Session.openActiveSession(getActivity(), true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Toast.makeText(getView().getContext(), user.getName(), Toast.LENGTH_SHORT).show();
etNome.setText(user.getName());
Log.i("usuario", user.getName());
}
}
}).executeAsync();
}
}
});
}
/** remove o fragment da fila */
private void removeFrag(){
getActivity().getSupportFragmentManager().popBackStack();
//getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
super.onStop();
CustomVolleySingleton.getInstance(getView().getContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
}
}
You can do something like below.
Request.newMeRequest(session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if (response != null)
{
try
{
String name = user.getName();
String email = (String) user.getProperty("email");
Log.e(LOG_TAG, "Name: " + name + " Email: " + email);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}).executeAsync();
P.S. Session should be opened before running this request. You can check sessionState through isOpened() method
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