Fragment Call Issue With Multiple Clicks - android-fragments

I have created this design to display in Stories Fragments. The design XML coding.
stories_fragment_sample_layout.XML code.
When I click on the stories fragment it works fine with just one click as I click for second or multiple times it calls fragment on the fragment. This means that its overwrite
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_margin="10dp"
app:cardBackgroundColor="#color/about_end_color"
app:cardCornerRadius="10dp"
app:cardElevation="10dp"
android:layout_height="100dp">
<ImageView
android:id="#+id/ImageFeather"
android:src="#drawable/stories"
android:contentDescription="#string/feather_image"
android:layout_width="100dp"
android:layout_height="100dp"/>
<TextView
android:id="#+id/storiesHandler"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:fontFamily="#font/tangerine_bold"
android:text="#string/stories"
android:textColor="#color/black"
android:textSize="30sp"
android:textStyle="bold" />
</androidx.cardview.widget.CardView>
fragment_stories
<?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"
tools:context=".Fragments.FragmentStories">
<!-- TODO: Update blank fragment layout -->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewStories"
android:layout_width="match_parent"
tools:listitem="#layout/stories_fragment_sample_layout"
android:layout_height="match_parent"/>
</LinearLayout>
this is stories_fragment XML coding that begins from the LinearLayout
Here, I have StoriesFragment.java
package com. quotescollector.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android. view.LayoutInflater;
import android. view.View;
import android. view.ViewGroup;
import com.quotescollector.Adapters.StroiesAdapter;
import com.quotescollector.Models.StoriesModel;
import com. quote collector. R;
import java.util.ArrayList;
public class FragmentStories extends Fragment {
StroiesAdapter adapter;
RecyclerView recyclerView;
ArrayList<StoriesModel> storiesList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stories, container, false);
storiesList = new ArrayList<>();
recyclerView = view.findViewById(R.id.recyclerviewStories);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new StroiesAdapter(storiesList, getContext());
displayStories();
return view;
}
private void displayStories() {
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
storiesList.add(new StoriesModel(R.drawable.stories, "Stories"));
recyclerView.setAdapter(adapter);
}
}
I think I don't have any errors in java. So you can check here.
enter image description here
This is the one-time click of the image
enter image description here
This is the second or multiple-time click of the image

Related

Android Android registration and login with firebase

I have a view (activity_SingIn) and its Presenter now in the onCreate method gives me the following error related to "singInPresenter.singInUser(v);"
2022-09-18 17:30:51.785 3811-3811/com.example.Natour21 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.Natour21, PID: 3811
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.NaTour21.Presenter.Activity.SingInPresenter.singInUser(android.view.View)' on a null object reference
at com.example.NaTour21.View.Activity.activity_singIn$2.onClick(activity_singIn.java:61)
package com.example.NaTour21.Presenter.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.NaTour21.View.Activity.activity_Home;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import android.widget.ProgressBar;
public class SingInPresenter extends AppCompatActivity {
private EditText EmailLgn,PasswordLgn;
String[] messaggio = {"Campi vuoti inserili"};
private ProgressBar progressBar;
public void singInUser(View view) {
String email = EmailLgn.getText().toString();
String password = PasswordLgn.getText().toString();
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
home();
}
}, 3000);
} else {
String error;
try{
throw task.getException();
}catch(Exception e){
error ="Errore di accesso utente";
}
Snackbar snackbar = Snackbar.make(view,error,Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}
}
});
}
public void home() {
Intent intent = new Intent(this, activity_Home.class);
startActivity(intent);
finish();
}
#Override
public void onStart() {
super.onStart();
FirebaseUser UtenteCorrente = FirebaseAuth.getInstance().getCurrentUser();
if(UtenteCorrente != null){
home();
}
}
}
package com.example.NaTour21.View.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.example.NaTour21.Presenter.Activity.SingInPresenter;
import com.example.NaTour21.R;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.widget.ProgressBar;
public class activity_singIn extends AppCompatActivity{
private EditText EmailLgn,PasswordLgn;
private Button loginLgn;
private Button registratiLgn;
private SingInPresenter singInPresenter;
private ProgressBar progressbar;
String[] messaggio = {"Campi vuoti inserirli",
"Accesso effettuato con successo",
"Formato email non valido",
"La password deve avere minimo 6 caratteri"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singin);
getSupportActionBar().hide();
initializeComponent();
registratiLgn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity_singIn.this, activity_singUp.class);
startActivity(intent);
}
});
loginLgn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = EmailLgn.getText().toString();
String password = PasswordLgn.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Snackbar snackbar = Snackbar.make(v, messaggio[0], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
} else if (!isValidEmail(email)) {
Snackbar snackbar = Snackbar.make(v, messaggio[2], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}else if (!(password.length() < 6)) {
Snackbar snackbar = Snackbar.make(v, messaggio[3], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
}else{
Snackbar snackbar = Snackbar.make(v, messaggio[1], Snackbar.LENGTH_SHORT);
snackbar.setBackgroundTint(Color.WHITE);
snackbar.setTextColor(Color.BLACK);
snackbar.show();
singInPresenter.singInUser(v); //??????
}
}
});
}
private boolean isValidEmail(String email) {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void initializeComponent() {
registratiLgn = findViewById(R.id.btRegistratiLgn);
EmailLgn = findViewById(R.id.tilEmailLgn);
PasswordLgn = findViewById(R.id.tilPasswordLgn);
loginLgn = findViewById(R.id.btLoginLgn);
progressbar = findViewById(R.id.progressbarLgn);
}
}
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/sfondo"
android:id="#+id/activity_singin"
android:clickable="true"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="336dp"
android:layout_height="196dp"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/txtNomeApp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:clickable="true"
android:fontFamily="sans-serif-medium"
android:gravity="center"
android:text="NaTour21"
android:textColor="#color/white"
android:textSize="60sp" />
</LinearLayout>
<LinearLayout
android:layout_width="361dp"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<EditText
android:id="#+id/tilEmailLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="25dp"
android:drawableLeft="#drawable/ic_email"
android:ems="10"
android:hint="Email"
android:textColor="#color/white"
android:inputType="textEmailAddress"
app:backgroundTint="#color/white"/>
<EditText
android:id="#+id/tilPasswordLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:drawableLeft="#drawable/ic_password"
android:drawableRight="#drawable/ic_occhio"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#color/white"
app:backgroundTint="#color/white"/>
<ProgressBar
android:id="#+id/progressbarLgn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
app:layout_constraintTop_toBottomOf="#id/containerComponents" />
<Button
android:id="#+id/btLoginLgn"
android:layout_width="232dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="30dp"
android:background="#drawable/button_login"
android:text="Login"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold"/>
<Button
android:id="#+id/btRegistratiLgn"
android:layout_width="232dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:background="#drawable/button_registrati"
android:text="Registrati"
android:textColor="#color/white"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Dear #Fabiola Salomone if you are trying to use MVP because you said you have a presenter then i am afraid you are not doing it correctly at least according to what i know about MVP please study about it that will be better instead of me or anyone else telling you the code directly because you will not know how it works that way , for a head start you need to make an interface and presenter and inside that presenter you will make three more interfaces View Model and Presenter again and then you will initialize that presenter inside you main activity , here you are extending you presenter with appcompactActivty that itself is wrong a lot about your code is wrong its not MVP by any means so i don't how can i help you exactly with this apart from what i just said, Once you know how MVP work then me or other users can surely help you with this, Still if you need any clearance you can ask :)

Null exeption encountered even though I have coded the button in both xml and java files with same ID

Found the solution I had forgot to include setContentView in my code
This my first app and I am building a login app.This is my Login page and it is connected to my frontpage and main activity through buttons.
I have coded the java and xml page to best of my Knowldge.My reset button'btn_link_to_register' and
'btn_action_back_to_homepage' are throwing null exception. They are both present in my java and xml codes. Usins Intent intent and calling it separately isn't changing anything.Please help!!
'LoginActivity.java'
'''package com.bharath.smartdata;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnSignOut, btnReset ,btn_link_to_register, btn_action_back_to_homepage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnSignOut =(Button) findViewById(R.id.btnsignout);
btn_action_back_to_homepage = (Button) findViewById(R.id.btn_action_back_to_homepage);
btnReset = (Button) findViewById(R.id.btn_reset_password);
btn_link_to_register =(Button) findViewById(R.id.btn_link_to_register);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
//Redirect to Homepage
btn_action_back_to_homepage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, Frontpage.class));
finish();
}
});
//Redirect To Signup Page
btn_link_to_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
//Login
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPassowordActivity.class));
}
});
//SignOut
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOut();
}
});
}
//sign out method
public void signOut() {
auth.signOut();
}
});
}
public void clickFuncTion(View view) {
}
}'''
'activity_login.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"
android:fitsSystemWindows="true"
android:background="#42CDDF"
tools:context="com.bharath.smartdata.LoginActivity">
<!-- Link to Login Screen -->
<TextView
android:id="#+id/textView"
android:layout_width="298dp"
android:layout_height="47dp"
android:text="Welcome Back!!!"
android:textSize="36sp"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.355" />
<ImageView
android:id="#+id/imageView"
android:layout_width="342dp"
android:layout_height="193dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.362"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.171"
app:srcCompat="#drawable/background" />
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/email"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/white"
app:layout_constraintBottom_toTopOf="#+id/password"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.284" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="76dp"
android:focusableInTouchMode="true"
android:hint="#string/hint_password"
android:imeActionLabel="#+id/login"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/email"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="#+id/email"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.052" />
<Button
android:id="#+id/btn_signup"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:text="#string/btn_login"
android:textColor="#android:color/black"
android:textStyle="bold"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/password"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/password"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.635" />
<Button
android:id="#+id/btn_reset_password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#null"
android:text="#string/btn_forgot_password"
android:textAllCaps="false"
android:textColor="#color/colorAccent"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.806" />
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="center|bottom"
android:visibility="gone"
app:layout_constraintBottom_toTopOf="#+id/textView"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="#+id/btn_link_to_register"
android:layout_width="411dp"
android:layout_height="56dp"
android:text="#string/btn_link_to_register"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
android:onClick="clickFuncTion"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.887" />
<Button
android:id="#+id/btn_action_back_to_homepage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/action_back_to_homepage"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
<Button
android:id="#+id/btnsignout"
android:layout_width="414dp"
android:layout_height="58dp"
android:text="#string/btn_sign_out"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.465"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.72" />
</androidx.constraintlayout.widget.ConstraintLayout>
'''
'Error Message'
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.bharath.smartdata.LoginActivity.onCreate(LoginActivity.java:53)
EDITED VERSION:
You added this line of code for every button:
android:onClick="clickFuncTion"
but in your java file (at the bottom of the file), you didn't add intent to move to another activity (clickFuncTion function was emtpy):
public void clickFuncTion(View view) {
}
If you want to use an onClickListener (like this one):
btn_action_back_to_homepage.setOnClickListener(new View.OnClickListener(){
}
you have to remove these:
android:onClick="clickFuncTion"
public void clickFuncTion(View view) {
}
EXAMPLE:
OPTION 1 (without using onClick property and clickFuntion for the button):
activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test this button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java file:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test button", "test button");
}
});
}
}
OPTION 2 (using onClick property and clickFuntion for the button):
activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/testButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test this button"
android:onClick="clickFuncTion"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java file:
package com.example.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button testButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testButton = (Button) findViewById(R.id.testButton);
}
public void clickFuncTion(View view) {
Log.d("test button", "test button");
}
}
Both produce the same result:
2021-04-19 14:42:50.727 27886-27886/com.example.myapplication D/testĀ button: test button

I want an implit loading spinner to be displayed in a fragment which has some views and the user clicks any one of them

I have a fragment which basically has a recyclerView. So when the user clicks on any item of the view, the background needs to change (the item clicked needs to be highlighted) and a loading spinner needs to appear and then fragment needs to replaced based on the item clicked. How to achieve this? In the below code, I have implemented the highlight facility, but once an item is clicked redirection should happen....
My Internal Layout, (layout_research)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="#dimen/loginCardRadius"
android:elevation="5dp"
android:layout_gravity="center"
android:layout_marginTop="#dimen/loginViewsMargin"
android:layout_marginBottom="#dimen/loginViewsMargin"
android:background="#ffffff">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:padding="#dimen/loginViewsMargin">
<ImageView
android:contentDescription="#string/abc"
android:src="#drawable/logo"
android:layout_gravity="center"
android:layout_height="100dp"
android:layout_width="wrap_content"
android:layout_marginTop="#dimen/loginViewsMargin"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/grid_view"
android:layout_marginTop="20dp"
tools:listitem="#layout/row_item"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
My External Layout,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ScrollView
android:fillViewport="true"
android:layout_height="match_parent"
android:layout_width="match_parent">
<RelativeLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:baselineAligned="true"
android:weightSum="12"
android:background="#drawable/login_shape_bk"
android:orientation="vertical"
android:layout_weight="3">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_login_bk" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical"
android:layout_marginTop="40dp"
android:layout_marginRight="30dp"
android:layout_marginLeft="30dp">
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textColor="#ffffff"
android:textSize="22sp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_gravity="center"
android:text="#string/abcd"/>
<include
layout="#layout/internal_research"/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
My Java File,
package com.example.a123;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class research extends Fragment {
int selectedPosition=-1;
private String[] names = {"Blogs & Books","Patents","Projects","Publications"};
private int[] image ={R.drawable.books,R.drawable.patents,R.drawable.project,R.drawable.publications};
private ArrayList<adapter_for_research> mProfiles;
private RecyclerView mProfileRecyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
mProfiles = new ArrayList<>();
for(int i =0;i<names.length;i++){
adapter_for_research s = new adapter_for_research();
s.setname(names[i]);
s.setImageId(image[i]);
mProfiles.add(s);
}
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_research, container, false);
mProfileRecyclerView = view.findViewById(R.id.grid_view);
updateUI();
return view;
}
private void updateUI(){
ProfileAdapter mAdapter = new ProfileAdapter(mProfiles);
mProfileRecyclerView.setAdapter(mAdapter);
}
private class ProfileHolder extends RecyclerView.ViewHolder {
private adapter_for_research mProfilecsg;
private ImageView mImageView;
private TextView mnameTextView;
private ProfileHolder(final View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.image_view);
mnameTextView = itemView.findViewById(R.id.text_view);
}
private void bindData(adapter_for_research s){
mProfilecsg = s;
mImageView.setImageResource(s.getImageId());
mnameTextView.setText(s.getname());
}
}
private class ProfileAdapter extends RecyclerView.Adapter<ProfileHolder>{
private ArrayList<adapter_for_research> mProfiles;
private ProfileAdapter(ArrayList<adapter_for_research> profile){
mProfiles = profile;
}
#NonNull
public ProfileHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.row_item,parent,false);
return new ProfileHolder(view);
}
#Override
public void onBindViewHolder(ProfileHolder holder, final int position) {
adapter_for_research s = mProfiles.get(position);
holder.bindData(s);
if(selectedPosition==position)
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_select));
else
holder.itemView.setBackground(ContextCompat.getDrawable(getContext(),R.drawable.item_nselect));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition=position;
notifyItemChanged(selectedPosition);
}
});
}
#Override
public int getItemCount() {
return mProfiles.size();
}
}
}
Adapter Class,
package com.example.a123;
class adapter_for_research {
private String mName;
private int mImageId;
String getname() {
return mName;
}
void setname(String mName) {
this.mName = mName;
}
int getImageId() {
return mImageId;
}
void setImageId(int mImageId) {
this.mImageId = mImageId;
}
}

insert admob in android fragment?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:gravity="bottom" >
<WebView
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:textAlignment="gravity" />
<LinearLayout
android:id="#+id/ll_ad"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-5456867664363319/8478541984" >
</com.google.android.gms.ads.AdView>
</LinearLayout>
</RelativeLayout>
package htm.greensoftware.com;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class HomeFragment<ChildFragment> extends Fragment {
WebView wv;
private AdView adView;
private AdRequest adRequest;
public HomeFragment() {
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
wv = (WebView) rootView.findViewById(R.id.webView1);
wv.loadUrl("file:///android_asset/index.html");
adView = new AdView(getActivity());
adView.setAdUnitId("ca-app-pub-5456867664363319/8478541984");
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.ll_ad);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
return rootView;
}
}
I googled but no proper not able to got answer.
i tried following links.
AdMob in a fragment
Using AdMob from within a Fragment?
Android Admob ad not shown in Activity with fragment. Why?
It is not clear what your question is, BUT
Yes, you can show AdView in a Fragment
yes, your config looks approximately correct.
You have marked your WebView as android:layout_height="fill_parent" so it will grab all the screen height giving none to your AdView. If you want I to expand to fill unused space then your will need to use a containing LinearLayout and use layout_weight="1" in order to indicate it should expand.

Android Fragment Duplication: Can't replace the fragment added statically

Hi i am very new in Android. I try to replace a fragment added statically in the layout file. But, if I instantiated my Fragment within my xml layout then the contents would remain visible after replacing it with another Fragment at runtime.
Here is my Activity Code:
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
public class RetailerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retailer);
}
public void selectFrag(View view) {
Fragment fr;
if (view == findViewById(R.id.button2)) {
fr = new FragmentTwo();
} else if (view == findViewById(R.id.button3)) {
fr = new FragmentThree();
} else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fr);
fragmentTransaction.commit();
}
}
Here is my Activity XML file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.1" />
<Button
android:id="#+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.2" />
<Button
android:id="#+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="selectFrag"
android:text="Fragment No.3" />
<LinearLayout
android:orientation="vertical"
android:id="#+id/fragment_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<fragment
android:id="#+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="fill_parent" />
</LinearLayout>
FragmentOne XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ffff">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="This is fragment No.1"
android:textStyle="bold" />
</LinearLayout>
FragmentOne java file:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
FragmentTwo xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#00ffff">
<TextView
android:id="#+id/textfrag2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is fragment No.2"
android:textStyle="bold" />
</LinearLayout>
FragmentTwo java code:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false);
}
}
Thanks in advance.
I've looked into this problem too and I can't seem to find a solution for placing a fragment statically in the XML file. In your Activity XML file, you'll have to replace the Fragment portion with a FrameLayout (The id can stay the same, just replace 'Fragment' with 'FrameLayout'); only way to make your selectFrag method with FragmentTransaction replace the fragments without overlap.
(If you want to have a default fragment shown when the activity starts, duplicate the FragmentTransaction code in the onCreate method of the Activity and swap the blank FrameLayout view with either fragment)

Resources