Android Studio No view found for id Error - java

I am developing a project at Android Studios and I have encountered an error Like This no view ........................................................................................................................................................
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.mixerchat.dating, PID: 7525
java.lang.IllegalArgumentException: No view found for id 0x7f080014 (com.mixerchat.dating:id/Login_A) for fragment Enable_location_F{3a7c810 #1 id=0x7f080014}
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1454)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Error Returned Java Code
private void enable_location() {
Enable_location_F enable_location_f = new Enable_location_F();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left,R.anim.in_from_left,R.anim.out_to_right);
getSupportFragmentManager().popBackStackImmediate();
transaction.replace(R.id.Login_A, enable_location_f).addToBackStack(null).commit();
}
The Activity_Login.xml codes
<?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:id="#+id/Login_A"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/white"
tools:context="com.mixerchat.dating.Accounts.Login_A">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fillViewport="true">
<androidx.percentlayout.widget.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_heightPercent="62%"
android:id="#+id/upperlayout"
android:layout_weight="1">
<androidx.viewpager.widget.ViewPager
android:id="#+id/pager"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:overScrollMode="always"
android:layout_above="#+id/indicator"/>
<com.google.android.material.tabs.TabLayout
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="30dp"
app:tabBackground="#drawable/d_indicator_background"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_below="#+id/upperlayout"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:background="#drawable/ic_fb_btn_background">
<ImageView
android:layout_width="28dp"
android:layout_height="28dp"
app:srcCompat="#drawable/ic_facebook"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:textColor="#color/white"
android:textAllCaps="true"
android:textSize="14dp"
android:text="Facebook ile Giriş Yap"
style="?android:attr/borderlessButtonStyle"
android:onClick="Login"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:id="#+id/gmail_login_layout"
android:background="#drawable/ic_google_background">
<ImageView
android:layout_width="28dp"
android:layout_height="28dp"
app:srcCompat="#drawable/ic_gmail"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#color/black"
android:clickable="false"
android:textAllCaps="true"
android:textSize="14dp"
style="?android:attr/borderlessButtonStyle"
android:background="#color/transparent"
android:text="Google ile Giriş Yap"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginTop="10dp"
android:id="#+id/phone_login_layout">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#color/black"
android:clickable="false"
android:textSize="13dp"
android:background="#color/transparent"
style="?android:attr/borderlessButtonStyle"
android:text="Telefon Numaram ile Giriş Yap"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textColor="#color/dimgray"
android:text="Bize güvenebilirsiniz \n Bilgileriniz 3. Part Kişilerle Paylaşılmamaktadır."
android:layout_marginTop="10dp"
android:lineSpacingExtra="7dp"/>
</LinearLayout>
</androidx.percentlayout.widget.PercentRelativeLayout>
</ScrollView>
</RelativeLayout>
Enable_Location_F Code
public class Enable_location_F extends Fragment {
View view;
Context context;
Button enable_location_btn;
SharedPreferences sharedPreferences;
IOSDialog iosDialog;
String gpsText;
public Enable_location_F() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(Functions.isTurkish())
view= inflater.inflate(R.layout.fragment_enable_location, container, false);
else
view= inflater.inflate(R.layout.fragment_enable_location_eng, container, false);
context=getContext();
iosDialog = new IOSDialog.Builder(context)
.setCancelable(false)
.setSpinnerClockwise(false)
.setMessageContentGravity(Gravity.END)
.build();
sharedPreferences= context.getSharedPreferences(Variables.pref_name, MODE_PRIVATE);
enable_location_btn=view.findViewById(R.id.enable_location_btn);
enable_location_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getLocationPermission();
}
});
if(Functions.isTurkish())
gpsText = getString(R.string.gpstext_tr);
else
gpsText = getString(R.string.gpstext_eng);
return view;
}
#Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (enter) {
Animation anim= MoveAnimation.create(MoveAnimation.LEFT, enter, 300);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
// after all the animation done we will call this mothod for get the location of user
GPSStatus();
}
#Override
public void onAnimationRepeat(Animation animation) {}
});
return anim;
} else {
return MoveAnimation.create(MoveAnimation.RIGHT, enter, 300);
}
}
private void getLocationPermission() {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
123);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case 123:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
GetCurrentlocation();
} else {
TastyToast.makeText(context,gpsText,TastyToast.LENGTH_LONG,TastyToast.DEFAULT);
}
break;
}
}
private FusedLocationProviderClient mFusedLocationClient;
public void GPSStatus(){
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!GpsStatus) {
TastyToast.makeText(context,gpsText,TastyToast.LENGTH_LONG,TastyToast.DEFAULT);
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),2);
}
else {
GetCurrentlocation();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==2){
GPSStatus();
}
}
// main method used for get the location of user
private void GetCurrentlocation() {
iosDialog.show();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
// first check the location permission if not give then we will ask for permission
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
iosDialog.cancel();
getLocationPermission();
return;
}
// if the user gives the permission then this method will call and get the current location of user
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
iosDialog.cancel();
if (location != null) {
// save the location inlocal and move to main activity
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Variables.current_Lat,""+location.getLatitude());
editor.putString(Variables.current_Lon,""+location.getLongitude());
editor.commit();
GoToNext_Activty();
}else {
if(sharedPreferences.getString(Variables.current_Lat,"").equals("") || sharedPreferences.getString(Variables.current_Lon,"").equals("") ){
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(Variables.current_Lat,"33.738045");
editor.putString(Variables.current_Lon,"73.084488");
editor.commit();
}
GoToNext_Activty();
}
}
});
}
public void GoToNext_Activty(){
startActivity(new Intent(getActivity(), MainMenuActivity.class));
getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
getActivity().finishAffinity();
}
}
I Can Wait For Your Help...

Related

How to fetch image path file to one Activity to other Activity

I have an App that verifies the ID card by clicking photos from both sides, after clicking the picture front-side of the id card the user moves to another activity for clicking the picture back-side of the id card after completing those prosses the user redirect to another activity that the user sees both sides of the document into different ImageView but I don't know how to fetch or pass
those images on this Activity that user can see their ID card for confirmation.
Here is my front side-scan activity
public class Front_Scan extends AppCompatActivity {
ActivityResultLauncher<Intent> activityResultLauncher;
private static final int PERMISSION_CODE = 101;
public String currentPhotoPath;
Button frontImgCap;
Button frontImgCapAgain;
Button frontNext;
ImageView frontImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_scan);
frontImg = findViewById(R.id.Image_id_front);
frontImgCap = findViewById(R.id.imgCapture_front);
frontImgCap.setVisibility(VISIBLE);
frontImgCapAgain = findViewById(R.id.Front_imgCapture_again);
frontImgCapAgain.setVisibility(GONE);
frontNext = findViewById(R.id.front_next);
frontNext.setVisibility(INVISIBLE);
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
File f = new File(currentPhotoPath);
frontImgCapAgain.setVisibility(VISIBLE);
frontImgCap.setVisibility(INVISIBLE);
frontNext.setVisibility(VISIBLE);
frontImg.setImageURI(Uri.fromFile(f));
}
}
});
frontImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
dispatchTakePictureIntent();
}
} else {
//system os < marshmallow
dispatchTakePictureIntent();
}
}
});
}
public void next(View view) {
Intent myIntent = new Intent(Front_Scan.this, back_scan.class);
Front_Scan.this.startActivity(myIntent);
finish();
}
public void scanAgain(View view) {
clearMyFiles();
onCreateLayouts();
frontImg.setImageDrawable(getResources().getDrawable(R.drawable.id_front));
}
void clearMyFiles() {
File imgFile = new File(currentPhotoPath);
if (imgFile != null) {
imgFile.delete();
}
}
public void onCreateLayouts() {
frontImgCap.setVisibility(VISIBLE);
frontImgCapAgain.setVisibility(GONE);
frontNext.setVisibility(INVISIBLE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "FRONT_ID_JPEG" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.nyabaapplication.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityResultLauncher.launch(takePictureIntent);
}
}
}
}
Front Scan 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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
android:orientation="vertical"
android:padding="30dp"
tools:context=".Front_Scan">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scan Front Side"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="60dp"
app:cardBackgroundColor="#color/background"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Image_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<android.widget.Button
android:id="#+id/Front_imgCapture_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/flag_transparent"
android:text="Scan Again"
android:onClick="scanAgain"
android:layout_marginTop="8dp"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="17sp"
android:visibility="gone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Position your document inside the frame. Make sure that all the data is clearly visible."
android:textAlignment="center"
android:textColor="#color/gray"
android:textSize="16sp"/>
<android.widget.Button
android:id="#+id/imgCapture_front"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:background="#drawable/button_style_ylo"
android:text="Scan Now"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:visibility="visible"/>
<android.widget.Button
android:id="#+id/front_next"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="-50dp"
android:background="#drawable/button_style_ylo"
android:text="Next Step"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:onClick="next"
android:visibility="invisible"/>
</LinearLayout>
Here is Back side-scan activity
public class back_scan extends AppCompatActivity {
ActivityResultLauncher<Intent> activityResultLauncher1;
private static final int PERMISSION_CODE = 101;
public String currentPhotoPath1;
Button backImgCap;
Button backImgCapAgain;
Button backNext;
ImageView backImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_back_scan);
backImg = findViewById(R.id.Image_id_back);
backImgCap = findViewById(R.id.imgCapture_back);
backImgCap.setVisibility(VISIBLE);
backImgCapAgain = findViewById(R.id.Back_imgCapture_again);
backImgCapAgain.setVisibility(GONE);
backNext = findViewById(R.id.back_next);
backNext.setVisibility(INVISIBLE);
activityResultLauncher1 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
File f1 = new File(currentPhotoPath1);
backImgCapAgain.setVisibility(VISIBLE);
backImgCap.setVisibility(INVISIBLE);
backNext.setVisibility(VISIBLE);
backImg.setImageURI(Uri.fromFile(f1));
}
}
});
backImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
dispatchTakePictureIntent1();
}
} else {
//system os < marshmallow
dispatchTakePictureIntent1();
}
}
});
}
public void next1(View view) {
Intent myIntent = new Intent(back_scan.this, scanned_copy.class);
back_scan.this.startActivity(myIntent);
finish();
}
public void scanAgainBack(View view) {
clearMyFiles1();
onCreateLayouts1();
backImg.setImageDrawable(getResources().getDrawable(R.drawable.id_back));
}
void clearMyFiles1() {
File imgFile1 = new File(currentPhotoPath1);
if (imgFile1 != null) {
imgFile1.delete();
}
}
public void onCreateLayouts1() {
backImgCap.setVisibility(VISIBLE);
backImgCapAgain.setVisibility(GONE);
backNext.setVisibility(INVISIBLE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent1();
} else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
private File createImageFile1() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "BACK_ID_JPEG_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath1 = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent1() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile1();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.nyabaapplication.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityResultLauncher1.launch(takePictureIntent);
}
}
}
}
Back Scan XML file is almost same as front side XML
Here is the activity that shows both sides of the ID Card together
public class scanned_copy extends AppCompatActivity {
Button finishBtn;
ImageView scanIDBack;
ImageView scanIDFront;
String storeFrontScan;
String storeBackScan="BACK_ID_JPEG.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanned_copy);
readFrontImgFromFile();
readBackImgFromFile();
scanIDBack = findViewById(R.id.Scan_id_back);
scanIDFront = findViewById(R.id.Scan_id_front);
finishBtn = findViewById(R.id.ScanfinishBtn);
finishBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(scanned_copy.this, WellDone.class);
startActivity(intent);
finish();
}
});
}
public void readFrontImgFromFile()
{
File imgFileFront = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeFrontScan);
if(imgFileFront.exists())
{
scanIDFront.setImageURI(Uri.fromFile(imgFileFront));
}
}
public void readBackImgFromFile()
{
File imgFileBack = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeBackScan);
if(imgFileBack.exists())
{
scanIDBack.setImageURI(Uri.fromFile(imgFileBack));
}
}
}
The XML File of this Activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:background="#color/background"
android:scrollbars="none"
tools:context=".scanned_copy">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scanned ID Card"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<ProgressBar
android:id="#+id/progressBar4"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="174dp"
android:layout_height="26dp"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:progress="85"
android:progressTint="#color/yellow" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="20dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="10dp"
android:text="Have a final check if all data is clearly visible and that it matches the information you have entered in previous steps."
android:textAlignment="center"
android:textColor="#color/gray"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="Front Side"
android:textSize="26dp"
android:textStyle="bold"
android:textColor="#color/light_gray"
android:layout_marginTop="30dp"/>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginHorizontal="10dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Scan_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="Back Side"
android:textSize="26dp"
android:textStyle="bold"
android:textColor="#color/light_gray"
android:layout_marginTop="30dp"/>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginHorizontal="10dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Scan_id_back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_back" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<android.widget.Button
android:id="#+id/ScanfinishBtn"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="40dp"
android:background="#drawable/button_style_ylo"
android:text="Finish Verification"
android:textAllCaps="false"
android:textColor="#color/white"
android:layout_gravity="center_horizontal"
android:textSize="19sp"
android:textStyle="bold"/>
</LinearLayout>
</ScrollView>
You have the path to the files that were saved. Pass them through to the last activity as intent extras.
https://developer.android.com/training/basics/firstapp/starting-activity

Attempt to invoke virtual method 'void android.widget.Button.setVisibility(int)' on a null object

I have 3 buttons on my layout 1 visible and 2 invisible at the time when the app is open,
when I click the 1st visible button it's open the camera to click the picture after the picture was clicked the picture was displayed at an ImageView on that same layout. After the picture was displayed at that ImageView I want to make the 2 invisible buttons visible and the 1 visible button invisible but when I try to do this I gating this error.
here is my 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"
android:background="#color/background"
android:orientation="vertical"
android:padding="30dp"
tools:context=".Front_Scan">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scan Front Side"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_gravity="center"
android:layout_marginTop="30dp"
app:cardBackgroundColor="#color/background"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/Image_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<Button
android:id="#+id/Front_imgCapture_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/flag_transparent"
android:text="Scan Again"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:visibility="invisible"
android:textSize="17sp" />
<android.widget.Button
android:id="#+id/imgCapture_front"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:background="#drawable/button_style_ylo"
android:text="Scan Now"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:visibility="visible"/>
<android.widget.Button
android:id="#+id/front_next"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:background="#drawable/button_style_ylo"
android:text="Next Step"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:onClick="next"
android:visibility="invisible"/>
</LinearLayout>
enter image description here
here is my java class Code
public class Front_Scan extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button frontImgCap;
Button frontImgCapAgain;
Button frontNext;
ImageView frontImg;
Uri image_uri;
private int REQUEST_CODE_PERMISSIONS = 101;
private String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA",
"android.permission.WRITE_EXTERNAL_STORAGE"};
AutoFitTextureView textureView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_scan);
frontImg = findViewById(R.id.Image_id_front);
frontImgCap = findViewById(R.id.imgCapture_front);
frontImgCapAgain = findViewById(R.id.imgCapture_again);
frontNext = findViewById(R.id.front_next);
frontImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
openCamera();
}
} else {
//system os < marshmallow
openCamera();
}
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//Camera intent
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent,IMAGE_CAPTURE_CODE);
}
public void next(View view) {
Intent myIntent = new Intent(Front_Scan.this, back_scan.class);
Front_Scan.this.startActivity(myIntent);
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
openCamera();
}else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #NonNull Intent data) {
//called when image was captured from camera
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
frontImg.setImageURI(image_uri);
//geting error at this line//
frontImgCapAgain.setVisibility(VISIBLE);
frontImgCap.setVisibility(INVISIBLE);
frontNext.setVisibility(VISIBLE);
}
}
}
I think You should change something in Your AndroidManifest.xml file. Try adding the singleTop attribute to the Front_Scan <activity>. I've encountered a similar problem once and the attribute helped because, as the docs say:
If, when starting the activity, there is already an instance of the same activity class in the foreground that is interacting with the user, then re-use that instance.
So the code fragment in Your case should look like this:
<activity
android:name=".Front_Scan"
android:launchMode="singleTop"
...>
...
</activity>

java.lang.IllegalArgumentException: uri cannot be null

I am getting and error while uploading an image and storing data to Firebase. I am using Bitmap to display the images. After submitting the data the app crashes and returns to the previous Activity. Also, when I pick an image from the device it is not displaying in the ImageView.
My error:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bloodsavelife, PID: 6642
java.lang.IllegalArgumentException: uri cannot be null
at com.google.android.gms.common.internal.Preconditions.checkArgument(com.google.android.gms:play-services-basement##17.2.1:35)
at com.google.firebase.storage.StorageReference.putFile(StorageReference.java:238)
at com.example.bloodsavelife.Activities.MakeRequest.uploadToFirebase(MakeRequest.java:153)
at com.example.bloodsavelife.Activities.MakeRequest.access$000(MakeRequest.java:47)
at com.example.bloodsavelife.Activities.MakeRequest$2.onClick(MakeRequest.java:121)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) I/Process: Sending signal. PID: 6642 SIG: 9
XML file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".Activities.MakeRequest">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="18dp"
android:text="Write your message and add an image for the community, somebody will
defintely help you if possible"
android:textColor="#android:color/black"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/post_image"
android:layout_width="192dp"
android:layout_height="150dp"
android:padding="8dp"
android:src="#drawable/ic_launcher_background_image" />
<Button
android:id="#+id/browse"
android:layout_width="141dp"
android:layout_height="57dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="60dp"
android:background="#drawable/button_bg"
android:gravity="center"
android:text="Browse"
android:textAlignment="gravity"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#drawable/border_background">
<EditText
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:cursorVisible="true"
android:gravity="top"
android:hint="Message to donors and mention for what purpose blood needed Include your
contact and location here."
android:maxLines="15"
android:minLines="7"
android:padding="10dp"
android:textAlignment="gravity"
android:textColor="#android:color/black"
android:textColorHint="#color/DarkGreen"
android:textSize="15sp"
android:textStyle="bold" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/bloodgroup"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Required Blood Group"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="dropdown_menu">
<AutoCompleteTextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/quantity"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Quantity Needed(in ml)"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="clear_text">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<Button
android:id="#+id/btn_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:background="#drawable/button_bg"
android:text="Post Request"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
Java code:
public class MakeRequest extends AppCompatActivity {
EditText message;
TextInputLayout bloodgroup, quantity;
TextView title;
ImageView image;
Uri filepath;
Bitmap bitmap;
Button postReq, browse;
private AutoCompleteTextView dropDownText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_request);
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
browse = findViewById(R.id.browse);
title = findViewById(R.id.title);
image = findViewById(R.id.image);
postReq = findViewById(R.id.btn_post);
dropDownText = findViewById(R.id.dropdown_text);
String[] item = new String[]{
"A+Ve",
"A-Ve",
"B+Ve",
"B-Ve",
"AB+Ve",
"AB-Ve",
"O+Ve",
"O-Ve"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
MakeRequest.this,
R.layout.dropdown_item,
item
);
dropDownText.setAdapter(adapter);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MakeRequest.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "select image"), 1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission,
PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
postReq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadToFirebase();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadToFirebase() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("File Uploader");
dialog.show();
enter code here
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
FirebaseStorage storage = FirebaseStorage.getInstance();
//need improvement by using date and time instead of random method.
StorageReference uploader = storage.getReference("Image1" + new Random().nextInt(100));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
dialog.dismiss();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("RequestPost");
RequestHelper obj = new RequestHelper(message.getText().toString(),
bloodgroup.getEditText().getText().toString(), quantity.getEditText().getText().toString(),
uri.toString());
root.child(bloodgroup.getEditText().getText().toString()).setValue(obj);
message.setText("");
bloodgroup.getEditText().setText("");
quantity.getEditText().setText("");
image.setImageResource(R.drawable.ic_image_black_24dp);
Toast.makeText(getApplicationContext(), "Uploaded",
Toast.LENGTH_LONG).show();
}
});
}
})
.addOnProgressListener(snapshot -> {
float percent = (100 * snapshot.getBytesTransferred()) /
snapshot.getTotalByteCount();
dialog.setMessage("Uploaded:" + (int) percent + "%");
});
}
Try with this code
Pick an image from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(intent, 1001);
onActivityforresult get Uri
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
// You can catch the exception here
}
}
}

How to make messages appear on different sides?

I make a chat app using a video tutorial, but this tutorial does not show how to make messages from different people appear on different sides. The sender and receiver see all messages on the left. Could you please give some advices on this? Thanks in advance.
Now it looks like this
Main code
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE=1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SIGN_IN_CODE) {
if(requestCode == RESULT_OK) {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
} else {
Snackbar.make(activity_main, "You are not authorized", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText textField = findViewById(R.id.messageField);
if(textField.getText().toString().equals(""))
return;
FirebaseDatabase.getInstance().getReference().push().setValue(
new Message(
FirebaseAuth.getInstance().getCurrentUser().getEmail(),
textField.getText().toString()));
textField.setText("");
}
});
//Пользователь ещё не авторизован
if (FirebaseAuth.getInstance().getCurrentUser()==null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
//Пользователь авторизован
else {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
private void displayAllMessages() {
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Message> options =
new FirebaseListOptions.Builder<Message>()
.setQuery(FirebaseDatabase.getInstance().getReference(), Message.class)
.setLayout(R.layout.list_item)
.build();
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Message Class
public class Message {
private String UserName;
private String TextMessage;
private long MessageTime;
public Message() {}
public Message (String UserName, String TextMessage){
this.UserName = UserName;
this.TextMessage = TextMessage;
this.MessageTime = new Date().getTime();
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getTextMessage() {
return TextMessage;
}
public void setTextMessage(String textMessage) {
TextMessage = textMessage;
}
public long getMessageTime() {
return MessageTime;
}
public void setMessageTime(long messageTime) {
MessageTime = messageTime;
}
}
Main XML
<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"
tools:context=".MainActivity"
android:id="#+id/activity_main">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send_button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
app:fabSize="normal">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#id/btnSend"
>
<EditText
android:id="#+id/messageField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Message..."
/>
</com.google.android.material.textfield.TextInputLayout>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/text_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
XML for the message bubbles
<RelativeLayout
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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Try adding layout_gravity attribute in your BubbleTextView when you need this like this:
android:layout_gravity="right"
Every user will have a unique email - Let say here in the example - d#mail.ru is your email. You need to add user logic to dynamically check to decide whether you want a bubble test layout to be LEFT or RIGHT.
Update the message bubble layout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Adapter code:- you can update as you need either LEFT or RIGHT.
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
RelativeLayout Layout = v.findViewById(R.id.parentlayout);
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
if(!model.getUserName().equals("d#mail.ru")) {
mess_text.setGravity(Gravity.LEFT)
} else {
mess_text.setGravity(Gravity.RIGHT)
}
}
};
Check this link as a reference - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java

Radio button OnCheckedChangeListener error inside fragment

I am facing some problem when calling onCheckedCahngedListener inside fragment on radio group app crashes.
when clicking on any item inside radio group the app crashed.
fragment_sell.xml
<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"
tools:context="com.example.syedsaadali.myapplication.SellFragment"
android:orientation="vertical">
<HorizontalScrollView
android:id="#+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_gravity="center"
android:background="#FFFFFF"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/RadioButton1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:checkedButton="#+id/first"
>
<RadioButton
android:id="#+id/sApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/apartment"
android:padding="15dp"
android:onClick="apartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sBuilder"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/house"
android:padding="15dp"
android:onClick="house"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sPlot"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:button="#drawable/land"
android:padding="15dp"
android:onClick="land"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sHouse"
android:layout_width="100dp"
android:layout_height="match_parent"
android:button="#drawable/builder"
android:padding="15dp"
android:onClick="builder"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sStudioApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/farmhouse"
android:padding="15dp"
android:onClick="farmhouse"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sFarmHouse"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/serviceapartment"
android:padding="15dp"
android:onClick="servicedapartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sServicedApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/studioapartment"
android:padding="15dp"
android:onClick="studioapartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
</RadioGroup>
</LinearLayout>
</HorizontalScrollView>
SellFragment.java
public class SellFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RadioGroup mRadioGroup1;
private RadioButton mapartment;
private RadioButton mBuilder;
private RadioButton mplot;
private RadioButton mHouse;
private RadioButton mStudioApartment;
private RadioButton mFarmhouse;
private RadioButton mServicedApartment;
private Spinner city;
private View layout;
public static SellFragment newInstance(String param1, String param2) {
SellFragment fragment = new SellFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
layout = inflater.inflate(R.layout.fragment_sell, container, false);
mRadioGroup1=(RadioGroup) layout.findViewById(R.id.RadioButton1);
mapartment=(RadioButton)layout.findViewById(R.id.sApartment);
mBuilder=(RadioButton)layout.findViewById(R.id.sBuilder);
mplot=(RadioButton)layout.findViewById(R.id.sPlot);
mHouse=(RadioButton)layout.findViewById(R.id.sHouse);
mStudioApartment=(RadioButton)layout.findViewById(R.id.sStudioApartment);
mFarmhouse=(RadioButton)layout.findViewById(R.id.sFarmHouse);
mServicedApartment=(RadioButton)layout.findViewById(R.id.sServicedApartment);
mRadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.sApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
} else if (checkedId == R.id.sBuilder) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sPlot) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sHouse) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sStudioApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sFarmHouse) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.cServicedApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
}
});
return layout;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}}
Logcat:
03-23 02:50:57.703 4697-4697/com.example.syedsaadali.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.syedsaadali.myapplication, PID: 4697
java.lang.IllegalStateException: Could not find method apartment(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatRadioButton with id 'cApartment'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4780)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You have defined <RadioButton ... android:onClick="apartment"/> In the XML But any method apartment was not created in Activity.
To resolve this Either remove that onClick attribute (if note needed) OR create a method apartment in java as well like
public void apartment(View view){
}
You can directly click Alt + Enter in onClick attribute of XML to get the hint of resolving this error by creating method.

Categories