Google Place Picker Not Opening on One click in Android Studio Java - java

I have used google place picker in android app for selecting location of the user by their wish. But when clicking the button it opened and suddenly it gets closed and if i click again only it opened to choose the location. And after opening also i can't search the location by typing the name.
Here i tried like this,
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/myButton"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Check Here"
android:textSize="16dp"
android:textStyle="normal"
android:textColor="#color/colorPrimary"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Button button = (Button)findViewById(R.id.myButton);
location_tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
try {
startActivityForResult(builder.build(PreviousAddressActivity.this),PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("dataview", String.valueOf(data));
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
StringBuilder stringBuilder = new StringBuilder();
String latitude = String.valueOf(place.getLatLng().latitude);
String longitude = String.valueOf(place.getLatLng().longitude);
stringBuilder.append("LATITUDE :");
stringBuilder.append(latitude);
stringBuilder.append("\n");
stringBuilder.append("Longitude");
stringBuilder.append(longitude);
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
Toast.makeText(getApplicationContext(),address, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Totally frustrated with this issue. Can anybody help me?
Thanks in Advance...

Related

How to fix an app from continuously requesting to be updated [duplicate]

This question already has answers here:
App on Google Play always shows "Update" instead of open [closed]
(6 answers)
Closed 4 years ago.
I have uploaded an update to my app on Play and as soon as I update it, it asks to update again.
The app comprises a few button on an otherwise simple WebView app, and Google Play keeps wanting to update the app.
I cannot find any errors causing this.
I would appreciate heads-up as so what could be causing this.
public class PilatesTimetable extends AppCompatActivity {
WebView rootView;
boolean installed;
ImageButton myWhatsApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pilates_timetable);
rootView = findViewById(R.id.timetable);
rootView.loadUrl("http://www.example.com");
rootView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
WebView.setWebContentsDebuggingEnabled(false);
installed = appInstalledOrNot("com.whatsapp");
myWhatsApp = findViewById(R.id.whatsAppButton);
if (installed) {
myWhatsApp.setVisibility(View.VISIBLE);
}
if (myWhatsApp.getVisibility() == View.VISIBLE) {
myWhatsApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = "+3530871234567";
String url = "https://api.whatsapp.com/send?phone=" + number;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
}
public void callUs(View v){
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:0871234567"));
startActivity(callIntent);
}
public void textUs(View v){
try{
Intent textIntent = new Intent(Intent.ACTION_SENDTO);
textIntent.setData((Uri.parse("smsto:0871234567")));
startActivity(textIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PilatesTimetable.this, "You do not have a texting application installed.", Toast.LENGTH_LONG).show();
}
}
public void emailUs (View v){
try {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData((Uri.parse("mailto:user#example.com")));
startActivity(emailIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PilatesTimetable.this, "You do not have an email application installed.", Toast.LENGTH_LONG).show();
}
}
public void bookOnline (View v){
try {
Intent bookIntent = new Intent(Intent.ACTION_VIEW);
bookIntent.setData((Uri.parse("http://www.example.com")));
startActivity(bookIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PilatesTimetable.this, "You do not have an Internet viewing application installed.", Toast.LENGTH_LONG).show();
}
}
public boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
boolean app_installed;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
}
catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
}
Example code from the activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ie.myPackage.PilatesTimetable">
<WebView
android:id="#+id/timetable"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
app:layout_constraintBottom_toTopOf="#+id/linearLayout"
app:layout_constraintTop_toTopOf="parent">
</WebView>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="85dp"
android:background="#color/primaryLightColor"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<ImageButton
android:id="#+id/whatsAppButton"
android:layout_width="0dp"
android:layout_height="85dp"
android:layout_weight="1"
android:background="#null"
android:backgroundTint="#color/primaryLightColor"
android:contentDescription="#string/whats_app_us"
android:tint="#color/white"
android:visibility="gone"
app:srcCompat="#drawable/wa_55" />
I have just finished chatting to Google and they confirmed that they have an ongoing issue with this at the moment.
So nothing to do with the app, it's their system.

How to Save google profile after google signin in another activity

I am new to Android Programming. I successfully integrated the Google sign-in and successful in Passing data to another Activity. But When I am going back to the activity through the navigation drawer where I passed the data it sowing empty screen. I Want to Save user Profile in that Activity. I want to save user details by clicking the save button permanently in the app to show as a user profile. Please help me in solving this Problem. Thanks, in Advance for the Solution.
Here are my java files and XML files.
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main3Activity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="90dp"
android:layout_height="125dp"
android:src="#drawable/profilep" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Disply Name Here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Disply Email Here"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/butn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/butn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
</com.google.android.gms.common.SignInButton>
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Detail">
<ImageView
android:id="#+id/dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="#+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
Detail.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
dp = (ImageView) findViewById(R.id.dp);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
name.setText(i_name);
email.setText(i_email);
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(i_url);
InputStream is = url.openConnection().getInputStream();
final Bitmap bmp = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
#Override
public void run() {
dp.setImageBitmap(bmp);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Main3Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main2Activity.class));
finish();
}
Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.butn_logout);
SignIn = (SignInButton) findViewById(R.id.butn_login);
Name = (TextView) findViewById(R.id.name);
Email = (TextView) findViewById(R.id.email);
Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.butn_login:
signIn();
break;
case R.id.butn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, REQ_CODE);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void updateUI(boolean isLogin) {
if (isLogin) {
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
} else {
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount account = googleSignInResult.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
updateUI(true);
preferenceConfig.writeLoginStatus(true);
try {
Intent sendData = new Intent(Main3Activity.this, Detail.class);
name = account.getDisplayName();
email = account.getEmail();
img_url = account.getPhotoUrl().toString();
sendData.putExtra("p_name", name);
sendData.putExtra("p_email", email);
sendData.putExtra("p_url", img_url);
startActivity(sendData);
} catch (Exception e) {
Toast.makeText(Main3Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main3Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Use shared preferences for your purpose. You can read more about it here.
An example is provided here sharedPreferences

How to add button in Zxing Scanner Camera View?

I want to add a button in Zxing Scanner Camera View, tried many procedures and seen many answers related to add button in Zxing library and refered this " How to add buttons in Zxing Scanner Camera View " , but it's not working anyone guide me, Thanks in advance, My code is
MainActivity.Java
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
final static String serverUrl = "";
private ZXingScannerView scannerView;
String res;
ImageButton img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
Log.e("OnCreate", "OnCreated");
//ZXingScannerView zxing=(ZXingScannerView)findViewById(R.id.zxscan);
scannerView = (ZXingScannerView) findViewById(R.id.zxscan);
img=(ImageButton)findViewById(R.id.img1);
//scannerView.setResultHandler(this);
//scannerView.startCamera();
//zxing.addView(scannerView);
//setContentView(scannerView);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
Log.e("M", "Permission");
Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();
} else {
Log.e("R", "Permission");
requestPermission();
}
}
}
private boolean checkPermission() {
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
Log.e("Successfull", "Success");
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted) {
Log.e("accpt", "Accpt");
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
} else {
Log.e("ntaccpt", "Not Acpt");
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onResume() {
super.onResume();
int capi = android.os.Build.VERSION.SDK_INT;
if (capi >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if (scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
scannerView = null;
}
#Override
public void handleResult(final Result result) {
res = result.getText();
Log.d("Scanner Result", result.getText());
Log.d("Scanner Result", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
GetText();
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setMessage(result.getText());
AlertDialog alert = builder.create();
alert.show();
}
public void GetText() //throws UnsupportedEncodingException
{
String data = res;
String text = "";
BufferedReader reader = null;
Log.e("Datafirst", data);
String requesturi = serverUrl + data;
// Send data
try {
URL url = new URL(requesturi);
Log.e("DataSecond", requesturi);
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
Log.e("Data Third", data);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
}
text = sb.toString();
} catch (Exception ex) {
Log.e("Exceptionio", "Error", ex);
ex.printStackTrace();
} finally {
try {
reader.close();
Log.e("Closed", "Closed");
} catch (Exception ex) {
Log.e("Except2", "Error", ex);
ex.printStackTrace();
}
}
Log.e("setText", data);
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<me.dm7.barcodescanner.zxing.ZXingScannerView
android:id="#+id/zxscan"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/img1"
android:layout_marginBottom="15dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:src="#drawable/imgbut"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Try my code, It will look like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.package.name.TakeSingleScanActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarAdjustScan"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="56dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/titleToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:layout_weight="1"
android:maxLines="1"
android:textColor="#color/white"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dp"
android:id="#+id/searchAdjustBtn"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:maxLines="1"
android:text="SEARCH "
android:textColor="#color/white"
android:textSize="13dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/textv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Point at any barcode to scan"
android:textColor="#color/white"
android:textSize="14sp"
android:textStyle="normal" />
<RelativeLayout
android:layout_marginBottom="120dp"
android:layout_below="#+id/textv"
android:id="#+id/relative_scan_take_single"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:background="#color/colorPrimaryDark"
android:layout_height="120dp"
android:orientation="horizontal">
<Button
android:id="#+id/doneBtn"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:text="Done"
android:textAllCaps="true"
android:textColor="#color/white"
android:textSize="22dp" />
</LinearLayout>
</RelativeLayout>
Java code for Scanner :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_single_scan);
init();
}
private void init() {
//Scanner
mScannerView = new ZXingScannerView(this);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relative_scan_take_single);
rl.addView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setSoundEffectsEnabled(true);
mScannerView.setAutoFocus(true);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.e(TAG, rawResult.getText()); // Prints scan results
Log.e(TAG, rawResult.getBarcodeFormat().toString());
Log.e("SCAN_RESULT", "" + rawResult.getText());
//dataSingle.put("0",rawResult.getText());
}

How to ZXING Barcode Scanner not full screen only half screen

I want create application
Scan Barcode using ZXING Barcode Scanner
Like Blackberry Messenger
This is my code "MainActivity.java"
package com.example.ridwan.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import info.vividcode.android.zxing.CaptureActivity;
import info.vividcode.android.zxing.CaptureActivityIntents;
public class MainActivity extends AppCompatActivity {
private TextView tvScanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent captureIntent = new Intent(MainActivity.this, CaptureActivity.class);
CaptureActivityIntents.setPromptMessage(captureIntent, "Barcode scanning...");
startActivityForResult(captureIntent, 0);
tvScanResult = (TextView) findViewById(R.id.tv_scanresult);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK && data != null) {
String value = data.getStringExtra("SCAN_RESULT");
tvScanResult.setText(value);
} else if (resultCode == Activity.RESULT_CANCELED) {
tvScanResult.setText("Scanning Gagal, mohon coba lagi.");
}
} else {
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Then this is my "activity_main.xml"
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ridwan.myapplication.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_marginTop="50dp"
android:id="#+id/tv_scanresult_title"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result Scan : " />
<TextView
android:layout_below="#id/tv_scanresult_title"
android:id="#+id/tv_scanresult"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:textColor="#ff1493"
android:layout_height="wrap_content"
android:text="_" />
</RelativeLayout>
Can you give me solution ?
i want to barcode in fragment.
I have achieved the same effect/UI you are looking for by using ZXing Android Embedded. Very straightforward to implement - and it also includes a torch functionality.
Step 1:
Add This Libray in Gradle in Dependancy
implementation 'com.google.zxing:core:3.2.1'
implementation 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
Step 2:
BarcodeActivity.java
public class BarcodeActivity extends AppCompatActivity {
private EditText editTextProductId;
private Button buttonGenerate, buttonScan;
private ImageView imageViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
initView();
}
private void initView() {
editTextProductId = findViewById(R.id.editTextProductId);
imageViewResult = findViewById(R.id.imageViewResult);
buttonGenerate = findViewById(R.id.buttonGenerate);
buttonGenerate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonGenerate_onClick(view);
}
});
buttonScan = findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonScan_onClick(view);
}
});
}
private void buttonGenerate_onClick(View view) {
try {
String productId = editTextProductId.getText().toString();
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
Writer codeWriter;
codeWriter = new Code128Writer();
BitMatrix byteMatrix = codeWriter.encode(productId, BarcodeFormat.CODE_128,400, 200, hintMap);
int width = byteMatrix.getWidth();
int height = byteMatrix.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
bitmap.setPixel(i, j, byteMatrix.get(i, j) ? Color.BLACK : Color.WHITE);
}
}
imageViewResult.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private void buttonScan_onClick(View view) {
IntentIntegrator intentIntegrator = new IntentIntegrator(this);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
intentIntegrator.setCameraId(0);
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult != null) {
String productId = intentResult.getContents();
Toast.makeText(getApplicationContext(), productId, Toast.LENGTH_LONG).show();
}
}
}
Step 3:
activity_barcode.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText">
<EditText
android:id="#+id/editTextProductId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Product Id"
android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/buttonGenerate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Generate Barcode" />
<Button
android:id="#+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Scan Barcode" />
</LinearLayout>
<ImageView
android:id="#+id/imageViewResult"
android:layout_width="match_parent"
android:layout_height="335dp" />
</LinearLayout>
Please Add this code in MainActivity
Add This Libray in Gradle in Dependancy
compile 'com.journeyapps:zxing-android-embedded:3.3.0#aar'
compile 'me.dm7.barcodescanner:zxing:1.9'
Add jar zbar.jar
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QCscanner = (Button) findViewById(R.id.QCscanner);
mScannerView = new ZXingScannerView(this);
QCscanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
/*Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);*/
mScannerView = new ZXingScannerView(MainActivity.this); // Programmatically initialize the scanner view<br />
setContentView(mScannerView);
mScannerView.setResultHandler(MainActivity.this); // Register ourselves as a handler for scan results.<br />
mScannerView.startCamera();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void handleResult(Result result) {
Log.e("", result.getText()); // Prints scan results<br />
Log.e("", result.getBarcodeFormat().toString());
Toast.makeText(MainActivity.this, "" + result.getText() + "\n" + result.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
}
}
ZXING library allows you to launch an intent(activity) to scan barcodes. If you wants to make changes in that you have to make changes in CaptureActivity of ZXING lib.
Also, now since Google has included scanning feature in its playservices you can use Vision api for scanning in a fragment without integration of any third party library. https://github.com/googlesamples/android-vision/tree/master/visionSamples
Please use
https://github.com/journeyapps/zxing-android-embedded
Just include Scanner view and remove scan paddings by adding:
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
attributes.
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/zxing_barcode_scanner"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
app:zxing_preview_scaling_strategy="fitXY"
app:zxing_use_texture_view="false"
/>
try this. (It very simplified example):
First step. Add dependency in build.gradle(module app):
From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:
implementation 'com.google.zxing:core:3.3.0'
Second step. Paste DecoratedBarcodeView view in you layout (activity_main.xml in this example):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</com.journeyapps.barcodescanner.DecoratedBarcodeView>
<TextView
android:id="#+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/barcode_scanner" />
</androidx.constraintlayout.widget.ConstraintLayout>
Third step. Add this code to MainActivity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val formats: Collection<BarcodeFormat> = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39)
binding.barcodeScanner.decoderFactory = DefaultDecoderFactory(formats)
binding.barcodeScanner.initializeFromIntent(Intent())
binding.barcodeScanner.decodeContinuous(object : BarcodeCallback {
override fun barcodeResult(result: BarcodeResult?) {
binding.resultTextView.text = result?.result?.text
}
})
}
override fun onResume() {
super.onResume()
binding.barcodeScanner.resume()
}
override fun onPause() {
super.onPause()
binding.barcodeScanner.pause()
}
}
Important! Implements onResume/onPause methods for activate DecoratedBarcodeView view. And don't forget grant Camera permissions for you app!
In this example i use this library:
https://github.com/journeyapps/zxing-android-embedded

How to navigate from QR Code Reader to Paticular URL?

Project is working fine But my problem is How to navigate from QR Code Reader to Particular URL. what is code to navigate please anyone tell me and help me.
AndroidBarcodeQrExample.java
public class AndroidBarcodeQrExample extends Activity {
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void scanQR(View v) {
try {
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (Exception e) {
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG);
toast.show();
}
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical" >
<Button
android:id="#+id/scanner"
android:layout_width="250dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_margin="10dp"
android:gravity="center"
android:onClick="scanQR"
android:text="QR Code"
android:textSize="18dp" >
</Button>
</LinearLayout>
The code to open url in browser is as follow:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("Your url here"));
startActivity(browserIntent);

Categories