so i am making a password manager app for android and i have 1 activity and fragments im using room for sql and all of that works fine but when i rotate the screen the app crashes and im not sure why, it says that it cant find the constructor on the configuration change but if that was the case why would it work in the first place :(
the fragment code
package app.web.fragments.passwords;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.google.firebase.analytics.FirebaseAnalytics;
import app.web.R;
import app.web.room_password.Password;
import app.web.view_model.PasswordViewModel;
public class Password_Add_Fragment extends Fragment {
private EditText username, password;
// priority is number picker
private NumberPicker numberPicker;
private Button insert, yeetAll;
private PasswordViewModel passwordViewModel;
private FirebaseAnalytics firebaseAnalytics;
public Password_Add_Fragment(FirebaseAnalytics firebaseAnalytics){
this.firebaseAnalytics = firebaseAnalytics;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (container==null){
return null;
}
View view = inflater.inflate(R.layout.fragment_all_passwords_by_category, container, false);
setButtons(view);
return view;
}
private void setButtons(View view) {
passwordViewModel = new ViewModelProvider(getActivity()).get(PasswordViewModel.class);
username = view.findViewById(R.id.edit_text_add_username);
password = view.findViewById(R.id.edit_text_add_password);
numberPicker = view.findViewById(R.id.number_picker_priority_password);
numberPicker.setMinValue(1);
numberPicker.setMaxValue(100);
insert = view.findViewById(R.id.btn_password_save);
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getContext(), "Insert", Toast.LENGTH_SHORT).show();
String usernameP = username.getText().toString().trim();
String passwordP = password.getText().toString().trim();
int x = numberPicker.getValue();
if (!usernameP.isEmpty() && !passwordP.isEmpty() && x >= 1){
Password passwordX = new Password(usernameP,passwordP,x);
passwordViewModel.insert(passwordX);
Toast.makeText(getContext(), "Saved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), "Cant be empty", Toast.LENGTH_SHORT).show();
}
}
});
yeetAll = view.findViewById(R.id.btn_password_delete_all);
yeetAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passwordViewModel.deleteAllPasswords();
Toast.makeText(getContext(), "Deleted All", Toast.LENGTH_SHORT).show();
}
});
}
}
the crash log
Full crash log
nevermind the fix was to just have an empty constructor in the fragment class.
Related
this is my first android project.
I am making a login and register page for a game i am making, and i'm trying to figure the login/register stuff. my project so far consists of MainActivity.java, LoginFragment and a RegisterFragment.
my question is after declaring the username, password, loginbtn variables how should my Intent intent declaration look like?
note aside, my mainActivity consists of a viewPager which just lets me slide through the login and register pages. but i will supply the code below
mainActivity.java
package com.example.my_app_2;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.app.Dialog;
import android.content.Intent;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button btnSignIn, btnSignUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create instance of SQLite Database
ViewPager viewPager = findViewById(R.id.viewPager);
AuthenticationPagerAdapter pagerAdapter = new AuthenticationPagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragmet(new LoginFragment());
pagerAdapter.addFragmet(new RegisterFragment());
viewPager.setAdapter(pagerAdapter);
}
static class AuthenticationPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<>();
public AuthenticationPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return fragmentList.get(i);
}
#Override
public int getCount() {
return fragmentList.size();
}
void addFragmet(Fragment fragment) {
fragmentList.add(fragment);
}
}
}
LoginFragment:
package com.example.my_app_2;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class LoginFragment extends Fragment {
EditText username, password;
Button loginbtn;
public LoginFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_login, container,false);
username = v.findViewById(R.id.username);
password = v.findViewById(R.id.password);
loginbtn = v.findViewById(R.id.loginbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String usernameValue = username.getText().toString();
String passwordValue = password.getText().toString();
// i assume the Intent intent goes here, but i have no idea what arugments/parameters pass in the new Intent() part of it
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_login, container, false);
}
}
and same goes with the registerFragment
package com.example.my_app_2;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class RegisterFragment extends Fragment {
EditText username, password, email;
Button signupbtn;
public RegisterFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_register, container,false);
username = v.findViewById(R.id.username);
password = v.findViewById(R.id.password);
email = v.findViewById(R.id.email);
signupbtn = v.findViewById(R.id.signupbtn);
signupbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String usernameValue = username.getText().toString();
String passwordValue = password.getText().toString();
String emailValue = email.getText().toString();
Intent intent = new Intent();
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_register, container, false);
}
}
what i have tried to do...
what i am trying to do is just take the username and password and store them in sharedPreferences.
thanks in advance, i apoligize for the silliness of the question but any help would be appreciated!
i have tried Intent intent = new Intent(this, RegisterFragment); // ??????
honestly im kinda clueless lol xd
(RegisterFragment.this); // ???????
I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
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.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
I am trying to implement On Click Listener in Fragment but it is giving me an error 'Attempt to invoke Virtual Method' I am using try/ catch to it is throwing an error in exception. Is anyone can guide me on how to implement onClick in Fragment I have different methods but all in vain. Tried onClick in XML, Tried Fragment Implement OnClickListener and btn.setOnClickListner but nor working at all.
package com.example.finalapp;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.hbb20.CountryCodePicker;
/**
* A simple {#link Fragment} subclass.
* Use the factory method to
* create an instance of this fragment.
*/
public class buyer_fragment extends Fragment {
public EditText mFirstname, mLastname, mUsername, mEmail, mPhone;
public TextInputEditText mPassword;
public CountryCodePicker ccp;
public FirebaseAuth mAuth;
public Button mSignUp;
public View view;
public buyer_fragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_buyer_fragment, container, false);
initViews();
return view;
}
public void login_back(View view) {
Intent intent = new Intent(getActivity(), login.class);
startActivity(intent);
}
public void initViews() {
try {
mFirstname = view.findViewById(R.id.first_name);
mLastname = view.findViewById(R.id.last_name);
mUsername = view.findViewById(R.id.user_name);
mEmail = view.findViewById(R.id.email);
mPhone = view.findViewById(R.id.phone_number);
mPassword = view.findViewById(R.id.signup_password);
ccp = view.findViewById(R.id.ccp);
mSignUp = (Button) view.findViewById(R.id.signup_btn1);
mSignUp.setOnClickListener(this::createUser);
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
public void createUser(View view) {
try {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
mAuth = FirebaseAuth.getInstance();
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(getContext(), "User Created", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Erro I got while performing this functionality in exception:
Attempt to invoke Virtual Method 'void.android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Why do you not using ViewBinding it will remove the pressure of findViewById()
for more info, you can check view binding setup
And you can also check this How to use ViewBinding in Fragment
According to #VishalBeep, you can do this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_buyer_fragment, container, false);
mFirstname = view.findViewById(R.id.first_name);
mLastname = view.findViewById(R.id.last_name);
mUsername = view.findViewById(R.id.user_name);
mEmail = view.findViewById(R.id.email);
mPhone = view.findViewById(R.id.phone_number);
mPassword = view.findViewById(R.id.signup_password);
ccp = view.findViewById(R.id.ccp);
mSignUp = (Button) view.findViewById(R.id.signup_btn1);
mSignUp.setOnClickListener(this::createUser);
}
I was doing a very little mistake I was using Tab Layout so I have 2 Fragments open in parallel and I was using the button ID of 2nd Fragment while I working on 1st Fragment. I know that was a stupid mistake but I am new to android development so I think that this can be expected from a beginner. The same code worked for me I have not used any Binding View just change that ID and know code is working fine for me.
I am making a practice app for my self creating friends profile my self in my app and having their avatar as imageview and name,nickname as text view it accepts object but it never shows anything on recyclerview
Please Help!
My main activity.java
package rex.MyFriends;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
FloatingActionButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView view = findViewById(R.id.elementsview);
btn = (FloatingActionButton) findViewById(R.id.newfbtn);
view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
view.setAdapter(new Friendsadapter(this));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),FriendsAdder.class));
}
});
}
}
my FriendAdder activity
package rex.MyFriends;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FriendsAdder extends AppCompatActivity {
TextView name,nickname;
Button add ,selectimage;
ImageView image;
String imgpath;
private static final int SELECT_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friendsadder);
name = findViewById(R.id.name);
nickname = findViewById(R.id.nickname);
add = findViewById(R.id.add);
selectimage = findViewById(R.id.selimg);
image = findViewById(R.id.disimg);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name.toString().isEmpty() || nickname.toString().isEmpty() || image.getDrawable()==null){
Toast.makeText(getBaseContext(),"please fill every thing!",Toast.LENGTH_SHORT).show();
}
else{
FriendList.addFriend(name.toString(),nickname.toString(),imgpath);
finish();
Toast.makeText(getBaseContext(),"Friend Added!",Toast.LENGTH_SHORT).show();
}
}
});
selectimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Your Friends Avatar!"), SELECT_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==SELECT_IMAGE && resultCode== Activity.RESULT_OK){
imgpath= data.getData().getPath();
Toast.makeText(getBaseContext(),imgpath,Toast.LENGTH_LONG).show();
image.setImageURI(data.getData());
}
}
}
my adapter class
package rex.MyFriends;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
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.recyclerview.widget.RecyclerView;
import java.io.File;
public class Friendsadapter extends RecyclerView.Adapter<Friendsadapter.FriendsHolder> {
Context context;
public Friendsadapter(Context context) {
this.context = context;
}
#NonNull
#Override
public FriendsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.friendrow,null,false);
return new FriendsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FriendsHolder holder, int position) {
FriendList.Friend friend = (FriendList.Friend) FriendList.friendlist.get(position);
holder.nickname.setText(friend.nickname);
holder.name.setText(friend.name);
File imgFile = new File(friend.imgpath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
holder.image.setImageBitmap(myBitmap);
}
}
#Override
public int getItemCount() {
return FriendList.friendlist.size();
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView name,nickname;
ImageView image;
public FriendsHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
nickname = itemView.findViewById(R.id.nickname);
image = itemView.findViewById(R.id.imageView2);
}
}
}
A helper Class I made with static Array list of Friend object acting as A runtime temporary database to add and remove Friend used in adapter class to display
package rex.MyFriends;
import java.util.ArrayList;
public class FriendList {
public static ArrayList<Friend> friendlist = new ArrayList<>();
public static class Friend {
String name;
String nickname;
String imgpath ;
public Friend(String name, String nickname, String imgpath) {
this.name = name;
this.nickname = nickname;
this.imgpath = imgpath;
}
}
public static void addFriend(String name, String nickname, String imgpath){
Friend friend = new Friend(name,nickname,imgpath);
friendlist.add(friend);
}
public int getSize(){
return friendlist.size();
}
public Friend getFriend(int position){
return friendlist.get(position);
}
}
Where the RecyclerView is handled adapterName.notifyDataSetChanged (); you need to run.
In your case, the data is collected statically. The place where the data is processed is a different Activity.
After switching to the new screen and adding data, you will need to update your adapter in onResume if you want the relevant data to appear when you come back. Recyclerview will appear blank since there is no data in its initial state.
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
The title says it all. I am attempting to send an ArrayList that has data inside from one fragment to another and then switch and show the second fragment (the one that just received the ArrayList).
here is my MainActivity.java:
package;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_display)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
}
}
here is my HomeFragment.java (the sending fragment):
package;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import com.mvsolutions.snap.R;
import com.mvsolutions.snap.ui.display.DisplayFragment;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import static android.app.Activity.RESULT_OK;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private ImageView imageView;
private Button captureImageButton, detectButton, pickButton;
private Bitmap imageBitmap;
private TextView capturedTextView;
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int RESULT_LOAD_IMAGE = 101;
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
//View view = inflater.inflate(R.layout.fragment_home, container, false);
View root = inflater.inflate(R.layout.fragment_home, container, false);
detectButton = root.findViewById(R.id.action_homeFragment_to_displayFragment2);
//detectButton.setOnClickListener((View.OnClickListener) this);
//return view;
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
//View v = inflater.inflate(R.layout.fragment_display, container, false);
imageView = root.findViewById(R.id.home_image_view_img);
capturedTextView = root.findViewById(R.id.home_text_view_txt);
captureImageButton = root.findViewById(R.id.capture_image_btn);
detectButton = root.findViewById(R.id.detect_text_btn);
//pickButton = root.findViewById(R.id.pick_image_btn);
captureImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
// pickButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// pickImage();
// }
// });
detectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_homeFragment_to_displayFragment2);
// DisplayFragment displayFragment = new DisplayFragment();
// FragmentManager fragmentManager = getFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.DisplayFragment, displayFragment, displayFragment.getTag())
// .commit();
//detectTextFromImage();
}
});
return root;
}
private void detectTextFromImage() {
capturedTextView.setText("");
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionTextDetector visionTextDetector = FirebaseVision.getInstance().getVisionTextDetector();
visionTextDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.Block> textBlocks = firebaseVisionText.getBlocks();
if (textBlocks.size() == 0) {
Toast.makeText(getContext(), "No Text Found", Toast.LENGTH_SHORT).show();
} else {
for (FirebaseVisionText.Block block : textBlocks) {
String text = block.getText();
ArrayList textBlobs = new ArrayList();
textBlobs.add(text);
for(int i = 0; i < textBlobs.size(); i++) {
capturedTextView.setText(capturedTextView.getText() + ", " + textBlobs.get(i));
}
// capturedTextView.setText(capturedTextView.getText() + " " + text);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
Log.d("Error", e.getMessage());
}
});
}
private void pickImage() {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
private void captureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
// else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
// Uri imageUri = data.getData();
// imageBitmap = MediaStore.Images.Media.decodeBitmap(this.);
// imageView.setImageBitmap(imageBitmap);
// }
}
}
here is my DisplayFragment.java (the receiving fragment):
package com.mvsolutions.snap.ui.display;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.mvsolutions.snap.R;
public class DisplayFragment extends Fragment {
private DisplayViewModel DisplayViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DisplayViewModel =
ViewModelProviders.of(this).get(DisplayViewModel.class);
View root = inflater.inflate(R.layout.fragment_display, container, false);
// final TextView textView = root.findViewById(R.id.text_gallery);
DisplayViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
return root;
}
}
I am currently using a navigation fragment xml file to make the button switch from the first fragment to the second, but I want it to send the data to the second fragment as well.
My two questions are:
Is it possible to both send the data to the second fragment and switch to the second fragment with one button press? or do I have to split it into two?
How do I send the data from the first fragment to the second?
You are using ViewModel so I think the easiest way is to use the same ViewModel for both fragments. In android docs, You can find an example Share data between fragments
It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of split-view (master-detail) fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item.
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
}
}
Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.