How to portrait QR code scanner using Zxing Library? - java

I'm quite new in Android Studio. How to portrait this simple qr code scanner?
Library
compile 'com.journeyapps:zxing-android-embedded:3.4.0'
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//View Objects
private Button buttonScan;
private TextView textViewName, textViewAddress;
//qr code scanner object
private IntentIntegrator qrScan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//View objects
buttonScan = (Button) findViewById(R.id.buttonScan);
textViewName = (TextView) findViewById(R.id.textViewName);
textViewAddress = (TextView) findViewById(R.id.textViewAddress);
//intializing scan object
qrScan = new IntentIntegrator(this);
//attaching onclick listener
buttonScan.setOnClickListener(this);
}
//Getting the scan results
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
//if qrcode has nothing in it
if (result.getContents() == null) {
Toast.makeText(this, "Result Not Found", Toast.LENGTH_LONG).show();
} else {
//if qr contains data
try {
//converting the data to json
JSONObject obj = new JSONObject(result.getContents());
//setting values to textviews
textViewName.setText(obj.getString("name"));
textViewAddress.setText(obj.getString("address"));
} catch (JSONException e) {
e.printStackTrace();
//if control comes here
//that means the encoded format not matches
//in this case you can display whatever data is available on the qrcode
//to a toast
Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onClick(View view) {
//initiating the qr code scan
qrScan.initiateScan();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name" />
<TextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Address" />
<TextView
android:id="#+id/textViewAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large" />
</LinearLayout>
<Button
android:id="#+id/buttonScan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Scan QR Code" />
</RelativeLayout>
I already inserted from AndroidManifest.xml in activity like this
android:screenOrientation="portrait" and android:screenOrientation="userPortrait".
The rest, I can't fix the problem.

Related

ML Kit Firebase textDetection does not detect clearly

The project that show in textView after taked photo from camera. Using Firebase ML kit for text detection. That's not detect text clearly. It detect some of words but not detect all clearly. Using bitmap for it I don't if this bitmap make this problem. Should I use SurfaceView for camera? Or whats solution to solve that?
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">
<ImageButton
android:id="#+id/cameraButton"
android:layout_width="108dp"
android:layout_height="72dp"
android:layout_marginStart="44dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="32dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_camera_alt_24"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.427" />
<ImageButton
android:id="#+id/detectButton"
android:layout_width="108dp"
android:layout_height="72dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="44dp"
android:layout_marginBottom="41dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_done_outline_24"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.445" />
<ImageView
android:id="#+id/mImageView"
android:layout_width="0dp"
android:layout_height="346dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:scaleType="fitXY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_image_24" />
<TextView
android:id="#+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:fontFamily="#font/segoeui"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/mImageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageView mImageView;
ImageButton cameraBtn;
ImageButton detectBtn;
Bitmap imageBitmap;
TextView textView;
String log = "error";
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.mImageView);
cameraBtn = findViewById(R.id.cameraButton);
detectBtn = findViewById(R.id.detectButton);
textView = findViewById(R.id.textView);
textView.setTypeface(ResourcesCompat.getFont(this, R.font.segoeui));
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent();
textView.setText("");
}
});
detectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
detectTextFromImage();
}
});
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager())!= null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
private void detectTextFromImage() {
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionCloudTextRecognizerOptions options = new FirebaseVisionCloudTextRecognizerOptions.Builder()
.setLanguageHints(Arrays.asList("eng","hi"))
.build();
FirebaseVisionTextRecognizer detector = FirebaseVision.getInstance()
.getCloudTextRecognizer(options);
Task<FirebaseVisionText> result =
detector.processImage(firebaseVisionImage)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
// Task completed successfully
// ...
displayTextFromImage(firebaseVisionText);
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
}
});
}
private void displayTextFromImage(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.TextBlock> blockList = firebaseVisionText.getTextBlocks();
if (blockList.size() == 0){
Toast.makeText(this,"No Text Found in image!",Toast.LENGTH_SHORT).show();
}
else{
for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) {
String text = block.getText();
textView.setText(text);
}
}
}
There's a sample app of text recognition on both iOS and Android platform at https://developers.google.com/ml-kit/samples (vision quickstart), and seems like both can detect the text within given image successfully?
private void displayTextFromImage(FirebaseVisionText firebaseVisionText) { List<FirebaseVisionText.TextBlock> blockList = firebaseVisionText.getTextBlocks(); if (blockList.size() == 0){ Toast.makeText(this,"No Text Found in image!",Toast.LENGTH_SHORT).show(); } else{ String text = ""; for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) { text = text + "\n" + block.getText(); textView.setText(text); } } }
By declaring and initializing String text inside for loop, will cause you lost the text of previous block. Actually, it takes each line as one block. Loop executes so fast, then you see only last line or last block of text set as your textview. Replace that code with this one, to resolve that issue.

how to add voice search in search view

I've Created search view in my app and now i want to add voice search on that how i do that
enter image description here
this is the image
in this search view is available i want to add voice search in it
This is code for Activity_main.xml in it search view is created now want to add voice search in which the result of voice search have to display on search box
activity_main.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="bottom"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:padding="10dp"
android:fontFamily="#font/custom_font"
android:text="#string/app_name"
android:textColor="#android:color/background_dark"
android:textSize="30dp" />
<android.support.v7.widget.SearchView
android:id="#+id/search_view"
android:layout_width="302dp"
android:layout_height="wrap_content"
android:layout_margin="12.1dp"
android:background="#drawable/search_view_design"
android:clickable="true"
android:contextClickable="true"
android:focusable="true"
android:inputType="text"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"
app:queryHint="Type Word..">
</android.support.v7.widget.SearchView>
</LinearLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/empty_history"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="150dp"
android:visibility="visible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search History Here.."
android:textAlignment="center"
android:textColor="#313131"
android:textSize="22sp"
android:layout_gravity="center_horizontal" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_history"
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
MainActicity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolBar = findViewById(R.id.toolBar);
setSupportActionBar(toolBar);
textView = findViewById(R.id.textView);
searchView = findViewById(R.id.search_view);
searchView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchView.onActionViewExpanded();
}
});
mdatabase = new Databasehelper(this);
if(mdatabase.checkDatabase())
{
openDatabase();
}
else
{
LoadDatabase ld = new LoadDatabase(this);
ld.execute();
}
final String[] from = new String[] {"en_word"};
final int[] to = new int[]{R.id.suggestion_text};
suggestionadapter = new SimpleCursorAdapter(MainActivity.this,
R.layout.suggestion_row,null,from,to,0)
{
#Override
public void changeCursor(Cursor cursor) {
super.swapCursor(cursor);
}
};
searchView.setSuggestionsAdapter(suggestionadapter);
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener(){
#Override
public boolean onSuggestionSelect(int i) {
return true;
}
#Override
public boolean onSuggestionClick(int i) {
CursorAdapter ca = searchView.getSuggestionsAdapter();
Cursor cursor = ca.getCursor();
cursor.moveToPosition(i);
String clicked_word = cursor.getString(cursor.getColumnIndex("en_word"));
searchView.setQuery(clicked_word,false);
searchView.clearFocus();
searchView.setFocusable(false);
Intent intent = new Intent(MainActivity.this,Word_meaningActivity.class);
Bundle bundle = new Bundle();
bundle.putString("en_word",clicked_word);
intent.putExtras(bundle);
startActivity(intent);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
String text = searchView.getQuery().toString().replaceAll("\\s+","");
Pattern P = Pattern.compile("[A-Za-z \\-.]{1,25}");
Matcher m = P.matcher(text);
if(m.matches()) {
Cursor c = mdatabase.getmeaning(text);
if (c.getCount() == 0) {
showDialog();
} else {
searchView.clearFocus();
searchView.setFocusable(false);
Intent intent = new Intent(MainActivity.this, Word_meaningActivity.class);
Bundle bundle = new Bundle();
bundle.putString("en_word", text);
intent.putExtras(bundle);
startActivity(intent);
}
}
else{
showDialog();
}
return false;
}
can Anyone help me in that
**Edit: Dont forget the permission: Manifest.permission.RECORD_AUDIO
You can create an Speech intent to capture the voice and then recall the speech back via onActivityResult
Create an intent
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to search");
try {
startActivityForResult(intent, 123456);
} catch (ActivityNotFoundException a) {
//show toast?
}
}
And then within the onActivityResult, capture the speech and pass it to your search.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 123456: {
if (resultCode == RESULT_OK && data != null) {
ArrayList result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
textView.setText(result.get(0));
}
break;
}
}
}
The android documentation can be found here: https://developer.android.com/reference/android/speech/SpeechRecognizer

Save google profile after google-signin in an activity

I successfully integrated the Google sign-in and successful in showing data in another Activity. But When I am going back to that activity where I passed the data it showing empty screen. I Want to Save user details in Profile Activity. Please help me. Thanks in Advance for a proper Solution. Below are my java files and XML files.
activity_main2.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=".Main2Activity">
<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_profile.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=".Profile">
<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" />
Profile.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
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();
}
Main2Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main3Activity.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(Main2Activity.this, Profile.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(Main2Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main2Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Instead of passing the data to the Profile activity use the GoogleSignIn.getLastSignedInAccount(getActivity()); method to get user profile data.
Replace your,
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");
with the following code,
GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(getActivity());
if (acct != null) {
String i_name = acct.getDisplayName();
String i_email = acct.getEmail();
Uri i_url = acct.getPhotoUrl();
}
For more information check this documentation

How to get value from Radiogroup and change in database

I am working on an application in android studio with firebase where the user can change user settings such as name, phone number and bio.
I also need the ability to change a selected radio group button value.
The Settings activity class is as follows
public class SettingsActivity extends AppCompatActivity {
private EditText mNameField, mPhoneField, mBio;
private Button mBack, mConfirm;
private RadioGroup mSport;
private ImageView mProfileImage;
private FirebaseAuth mAuth;
private DatabaseReference mUserDatabase;
private String userId, name, phone, bio, sport, profileImageUrl, userSex;
private Uri resultUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mNameField = (EditText) findViewById(R.id.name);
mPhoneField = (EditText) findViewById(R.id.phone);
mBio = (EditText) findViewById(R.id.bio);
mSport = (RadioGroup) findViewById(R.id.sport);
mProfileImage = (ImageView) findViewById(R.id.profileImage);
mBack = (Button) findViewById(R.id.back);
mConfirm = (Button) findViewById(R.id.confirm);
mAuth = FirebaseAuth.getInstance();
userId = mAuth.getCurrentUser().getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
getUserInfo();
mProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserInformation();
}
});
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
return;
}
});
}
private void getUserInfo() {
mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("name")!=null){
name = map.get("name").toString();
mNameField.setText(name);
}
if(map.get("phone")!=null){
phone = map.get("phone").toString();
mPhoneField.setText(phone);
}
if(map.get("bio")!=null){
bio = map.get("bio").toString();
mBio.setText(bio);
}
if(map.get("sport")!=null){
}
if(map.get("sex")!=null){
userSex = map.get("sex").toString();
}
if(map.get("sport") !=null){
}
Glide.clear(mProfileImage);
if(map.get("profileImageUrl")!=null){
profileImageUrl = map.get("profileImageUrl").toString();
switch(profileImageUrl){
case "default":
Glide.with(getApplication()).load(R.mipmap.default_app_image).into(mProfileImage);
break;
default:
Glide.with(getApplication()).load(profileImageUrl).into(mProfileImage);
break;
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void saveUserInformation() {
name = mNameField.getText().toString();
phone = mPhoneField.getText().toString();
bio = mBio.getText().toString();
int selectSport = mSport.getCheckedRadioButtonId();
final RadioButton sportButton = (RadioButton) findViewById(selectSport);
if(sportButton.getText() == null){
return;
}
Map userInfo = new HashMap();
userInfo.put("name", name);
userInfo.put("phone", phone);
userInfo.put("bio", bio);
userInfo.put("sport",sport);
mUserDatabase.updateChildren(userInfo);
if(resultUri != null){
StorageReference filepath = FirebaseStorage.getInstance().getReference().child("profileImages").child(userId);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getApplication().getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
finish();
}
});
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Map userInfo = new HashMap();
userInfo.put("profileImageUrl", downloadUrl.toString());
mUserDatabase.updateChildren(userInfo);
finish();
return;
}
});
}else{
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
final Uri imageUri = data.getData();
resultUri = imageUri;
mProfileImage.setImageURI(resultUri);
}
}
and the XML file
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.wk001764.finalproject.SettingsActivity"
android:orientation="vertical">
<ImageView
android:id="#+id/profileImage"
android:layout_width="200sp"
android:layout_height="200sp"
android:layout_gravity="center"
android:layout_marginBottom="20sp"
android:src="#mipmap/default_app_image" />
<EditText
android:id="#+id/name"
android:layout_width="398dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20sp"
android:background="#null"
android:hint="Name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/phone"
android:background="#null"
android:hint="Phone Number"
android:layout_marginBottom="20sp"
android:inputType="phone"/>
<EditText
android:id="#+id/bio"
android:layout_width="398dp"
android:layout_height="wrap_content"
android:layout_marginBottom="20sp"
android:background="#null"
android:hint="Bio" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Please Select the sport you want to change to:"/>
<RadioGroup
android:id="#+id/sport"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioButton
android:id="#+id/badminton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Badminton" />
<RadioButton
android:id="#+id/basketball"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Basketball" />
<RadioButton
android:id="#+id/boxing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Boxing" />
<RadioButton
android:id="#+id/cricket"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Cricket" />
<RadioButton
android:id="#+id/football"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Football" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioButton
android:id="#+id/golf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Golf" />
<RadioButton
android:id="#+id/hockey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hockey" />
<RadioButton
android:id="#+id/rugby"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rugby" />
<RadioButton
android:id="#+id/swimming"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Swimming" />
<RadioButton
android:id="#+id/tennis"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Tennis" />
</LinearLayout>
</LinearLayout>
</RadioGroup>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/confirm"
android:text="Save"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/back"
android:text="Back"/>
</LinearLayout>
How would I get the new selected value of the radio group and save it to the database?
You should be able to do something like this:
int radioButtonId = mSport.getCheckedRadioButtonId();
View radioButton = mSport.findViewById(radioButtonId);
int idx = mSport.indexOfChild(radioButton);
To get selected RadioButton Text in a RadioGroup, please use the following code:
RadioButton rb = (RadioButton) mSport.getChildAt(idx);
String selectedText = rb.getText().toString();
But note, this code will work only if the radio buttons are direct children of your RadioGroup. So you need to remove those "LinearLayouts". In fact, there is no need to use those layouts at all. You can set the orientation of your RadioGroup to "vertical", in your .XML file, using the following line of code:
android:orientation="vertical"

ImageView crashes my android application on Samsung Galaxy S5

I'm here to ask you a question as a newbie in android developing. Right now I'm trying to follow a tutorial which teaches the basics of android developing in Android Studio, but I encountered an issue with my Samsung Galaxy S5.
What I'm trying to do is to import an image from the gallery and put it into an ImageView but when I try to start the application I get a crash error. I know that many people had this issue and I downloaded the samsung SDK, but I don't know what and how to use for this problem. (Sorry, but I started all this yesterday and I can't find anything that can help me...)
The code is here:
activity_main.xml
<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"
tools:context="${packageName}.${activityClass}">
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/tabHost"
android:layout_alignParentTop="false">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/tabCreator"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Contatto"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imgContact"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:src="#drawable/no_user_logo"
android:clickable="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/txtName"
android:textAllCaps="false"
android:hint="Nome"
android:layout_marginTop="10dp" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="#+id/txtNumber"
android:hint="Numero di Telefono"
android:layout_marginTop="10dp"
android:layout_below="#id/txtName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="false" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/txtMail"
android:layout_marginTop="10dp"
android:hint="Email" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Aggiungi Contatto"
android:id="#+id/btnAdd"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:enabled="false"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:id="#+id/tabList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Contatti"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/banana"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
EditText txtName, txtPhone, txtEmail;
List<Contact> lstContacts = new ArrayList<Contact>();
ListView lstViewContact;
ImageView img = (ImageView)findViewById(R.id.imgContact);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (EditText) findViewById(R.id.txtName);
txtPhone = (EditText) findViewById(R.id.txtNumber);
txtEmail = (EditText) findViewById(R.id.txtMail);
lstViewContact = (ListView)findViewById(R.id.banana);
final Button btn = (Button) findViewById(R.id.btnAdd);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addContact(txtName.getText().toString().trim(), txtPhone.getText().toString(), txtEmail.getText().toString());
Toast.makeText(getApplicationContext(), "Banana", Toast.LENGTH_SHORT).show();
}
});
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
txtName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
boolean goName = false, goPhone = false;
if(txtName.length() > 0) goName = txtName.getText().toString().trim().length() > 0;
if(txtPhone.length() > 0) goPhone = txtPhone.getText().toString().trim().length() > 0;
btn.setEnabled(goName && goPhone);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
txtPhone.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
boolean goName = false, goPhone = false;
if(txtName.length() > 0) goName = txtName.getText().toString().trim().length() > 0;
if(txtPhone.length() > 0) goPhone = txtPhone.getText().toString().trim().length() > 0;
btn.setEnabled(goName && goPhone);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("list");
tabSpec.setContent(R.id.tabList);
tabSpec.setIndicator("List");
tabHost.addTab(tabSpec);
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1) img.setImageURI(data.getData());
}
}
private class lstContactsAdapter extends ArrayAdapter<Contact> {
public lstContactsAdapter() {
super(MainActivity.this, R.layout.listview_item, lstContacts);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
//Se la view non esiste io la metto come listview_item all'interno della lista alla fine (non al root)
if(view == null) view = getLayoutInflater().inflate(R.layout.listview_item, parent, false);
Contact currentContact = lstContacts.get(position);
TextView name = (TextView)view.findViewById(R.id.contactName);
TextView phone = (TextView)view.findViewById(R.id.contactPhone);
TextView mail = (TextView)view.findViewById(R.id.contactMail);
name.setText(currentContact.getName());
phone.setText(currentContact.getPhone());
mail.setText(currentContact.getEmail());
return view;
}
}
private void addContact(String name, String phone, String email) {
lstContacts.add(new Contact(name, phone, email));
ArrayAdapter<Contact> adapter = new lstContactsAdapter();
lstViewContact.setAdapter(adapter);
}
}
I'm so sorry for asking this without a proper knowledge, but I hope you'll understand and help me. Thank you for reading and sorry for any grammatical error I did.
In your class, in place of this
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1) img.setImageURI(data.getData());
}
}
put this,
#Override
public void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == RESULT_OK) {
if(reqCode == 1 && data.getData() != null)
img.setImageURI(data.getData());
}
super.onActivityResult(reqCode, resCode, data);
}
You should always call super class method to ensure default behaviour with your own. Also, #Override annotation makes sure that onActivityResult is called as a callback. Lastly, data.getData() != null ensures that you don't get a NPE.

Categories

Resources