Why does alertDialog cause my app to crash? - java

public class SignUpActivity extends AppCompatActivity
{
private CircleImageView profilePic,galleryPick,cameraPick;
private ActivityResultLauncher<Intent> activityResultLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
profilePic = findViewById(R.id.circular_image);
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result)
{
if(result.getResultCode() == RESULT_OK && result.getData() != null)
{
Bundle bundle = result.getData().getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
profilePic.setImageBitmap(bitmap);
}
}
});
profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
chooseProfilePic();
}
});
}
private void chooseProfilePic()
{
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_dialog,null);
builder.setCancelable(false);
builder.setView(dialogView);
galleryPick = findViewById(R.id.gallery_pick);
cameraPick = findViewById(R.id.camera_pick);
AlertDialog alertDialog = builder.create();
alertDialog.show();
cameraPick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager()) != null)
{
activityResultLauncher.launch(cameraIntent);
}
}
});
}
}
So I am a beginner in Android Studio and since startForActivityResult is deprecated I am
looking for something to replace it. The new method works but there occurs a problem when
used with private method including the alert dialog.

You are finding the resourceId of the button in the dialog from wrong view.
Buttons are present in dialog while you are finding it from activity/fragment view.
Update your code to find it from dialogView.
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_dialog,null);
builder.setCancelable(false);
builder.setView(dialogView);
galleryPick = dialogView.findViewById(R.id.gallery_pick); // find id from dialog view
cameraPick = dialogView.findViewById(R.id.camera_pick); // find id from dialog view
AlertDialog alertDialog = builder.create();
alertDialog.show();

Related

why can't I put item_form.class on intent?

I want to transfer Uri from a dialog activity to a normal activity
public class popup extends AppCompatDialogFragment {
ActivityItemFormBinding binding;
ActivityResultLauncher<String> selectpic;
public Uri newUri;
public Button camera, gallery, send;
public popuplistener listener;
public ImageView Display;
#Override
public Dialog onCreateDialog( Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.popup, null);
builder.setView(view);
binding = ActivityItemFormBinding.inflate(getLayoutInflater());
Display = view.findViewById(R.id.display);
selectpic = registerForActivityResult(
new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
if(!(result == null)) {
Display.setVisibility(View.VISIBLE);
send.setVisibility(View.VISIBLE);
newUri = result;
Display.setImageURI(newUri);
}
}
}
);
Ive made a method to take Uri from selectpic result but I cannot start intent because it wont take the parameters item_form.class
private void sendpic() {
Intent intent = new Intent(popup.this, item_form.class);
intent.putExtra("imageUri", newUri);
startActivity(intent);
I do not understand how to resolve this part where Intent won't take item_form as parameter. How do I proceed to fix this problem?

getting error when i try to use switch button is differen class

So I defined a switch button in ProfileSettingsfragment but i am using that button in Explanation.class. What I am really trying to do is when switch button is checked i want start service else i don't want to star service from Explanation.class
SO I tried Some code and it showing me this error " java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.appcompat.widget.SwitchCompat.isChecked()' on a null object reference
at com.harsh.preacher.ui.Home.Explaination$1.onClick(Explaination.java:43)"
P.S I have designed switch button in ProfileSettingsfragment.xml
Here is ProfileSettingsfragment class code
public class ProfileSettingsFragment extends Fragment {
private GoogleSignInClient mGoogleSignInClient;
public SwitchCompat notePopUp;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_profilesettings, container, false);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(requireContext(), gso);
final ProfileSettingsFragment profileSettingsFragment =new ProfileSettingsFragment();
Button signOut1 = root.findViewById(R.id.signOut);
signOut1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO Custom Alert Dialog Bar
// signOut();
Intent intent = new Intent(getContext(), AndarAwoo.class);
startActivity(intent);
// Animation(signOut1);
}
});
notePopUp = (SwitchCompat) root.findViewById(R.id.notePopUp);
RelativeLayout EditName = root.findViewById(R.id.EditName);
RelativeLayout ProfileSettingsLayout= root.findViewById(R.id.profileSettingsCardView);
TextView EditNameText = root.findViewById(R.id.EditNameText);
EditNameText.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
if(EditName.getVisibility() == View.GONE){
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.VISIBLE);
}else {
TransitionManager.beginDelayedTransition(ProfileSettingsLayout,new AutoTransition());
EditName.setVisibility(View.GONE);
}
}
});
return root;
}
Here is my explanation class code
public class Explaination extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explaination);
Intent intent = getIntent();
String about = intent.getStringExtra("about");
TextView about1 = findViewById(R.id.about);
about1.setText(about);
Button resource = findViewById(R.id.Resource);
resource.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = getIntent();
String url = intent.getStringExtra("button");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
ProfileSettingsFragment checkNotePopUp = new ProfileSettingsFragment();
checkNotePopUp.notePopUp = findViewById(R.id.notePopUp);
if(checkNotePopUp.notePopUp.isChecked()){
startService(new Intent(Explaination.this, NotePopUpHead.class));
}
else{
stopService(new Intent(Explaination.this,NotePopUpHead.class));
}
finish();
startActivity(i);
}
});
}
}

How to add AdMob Banner AD in RecyclarView after 5 or 10 CardView using FirebaseRecyclerAdapter

I am working on an android app where I am showing some text coming through the firebase database, now I want to show AdMob Banner AD after 5 CardView in the RecyclarView but I am not understand how to do that because I am beginner in Java and Android Programming language. Can anyone help me to do this implementation.
MY JAVA CODE
POJO CLASS
private String shaData;
public Model(){
}
public Model(String sha) {
this.shaData = sha;
}
public String getShaData() {
return shaData;
}
public void setShaData(String shaData) {
this.shaData = shaData;
}
}
MY VIEW HOLDER CLASS
public class Holder extends RecyclerView.ViewHolder{
public TextView txtShayari;
public Button copyButton, shareButton, whatsappButton;
public Holder(#NonNull View itemView) {
super(itemView);
txtShayari = (TextView)itemView.findViewById(R.id.textView);
copyButton = (Button) itemView.findViewById(R.id.copyBtn);
shareButton = (Button) itemView.findViewById(R.id.shBtn);
whatsappButton = (Button) itemView.findViewById(R.id.waBtn);
}
}
MY MAIN ACTIVITY
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ProgressBar progressBar;
ImageView imageView;
FirebaseRecyclerAdapter<Model, Holder> recyclerAdapter;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
database = FirebaseDatabase.getInstance();
databaseReference = database.getReference("MyQuotes");
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
progressBar = findViewById(R.id.progress);
loadData();
}
private void loadData()
{
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Model>()
.setQuery(databaseReference,Model.class)
.build();
recyclerAdapter = new FirebaseRecyclerAdapter<Model, Holder>(options) {
int AD_TYPE = 0;
int CONTENT_TYPE = 1;
#Override
protected void onBindViewHolder(#NonNull final Holder holder, int position, #NonNull final Model model) {
holder.txtShayari.setText(model.getShaData());
progressBar.setVisibility(View.GONE);
holder.copyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager)holder.itemView.getContext().getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(Intent.EXTRA_TEXT, model.getShaData());
clipboard.setPrimaryClip(clip);
Toast.makeText(holder.itemView.getContext(), "Shayari Copied", Toast.LENGTH_SHORT).show();
}
});
holder.whatsappButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
try {
holder.itemView.getContext().startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(holder.itemView.getContext(), "Whatsapp have not been installed", Toast.LENGTH_SHORT).show();
}
}
});
holder.shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent .setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, model.getShaData());
intent.setType("text/plain");
intent = Intent.createChooser(intent, "Share With");
holder.itemView.getContext().startActivity(intent);
}
});
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_view,viewGroup,false);
return new Holder(view);
}
};
recyclerAdapter.notifyDataSetChanged();
recyclerAdapter.startListening();
recyclerView.setAdapter(recyclerAdapter);
}
}
This is my whole code too fetch text data from the Firebase server and it is working very well, Simply now I am want too show AdMob banner ads after 5 cardviews on the recyclarview, So please anyone guide me.

How to add editText and buttons dynamically using LayoutInflater and set a unique id for them?

I am doing adding specifications on the product and I want to that when users click on add_field_btn it will show the XML file contains of two editText with a delete button on the side using the LayoutInflater. But I don't know how to implement the adding of a unique id for every editText that are generated.
Below is my code:
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_products);
backBTN = findViewById(R.id.imageButton);
backBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddProductsActivity.this, StoreHomeActivity.class);
intent.putExtra("userid", userID);
startActivity(intent);
overridePendingTransition(R.anim.mid_to_left, R.anim.right_to_mid);
}
});
}
public void onAddField(View v) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.product_specification_item_layout, null);
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
You are on right way; just check this below function that i modified.
int myTagCount=0;
public void onAddField(View v) {
myTagCount++;
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.product_specification_item_layout, null);
TextView tv_delete = (TextView) view.findViewById(R.id.tv_delete);
tv_delete.setText("Delete");
tv_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
parentLinearLayout.removeView(view);
}
});
view.setTag(myTagCount);
parentLinearLayout.addView(view);
}
I use inflater this way. This will also helps you.
For getting value with Tag, check this:
for (int i = 0; i < parentLinearLayout.getChildCount(); i++) {
View view = parentLinearLayout.getChildAt(i);
if (view.getTag().equals(myTagCount)) {
EditText editText = (EditText) view.findViewById(R.id.edt1);
String myText = editText.getText().toString();
break;
}
}

Android Alert Dialog crashes my application

Whenever I debug the application it crashes when I click the button that pops up the dialog.
What should I do to make that dialog work?
public class Actionbar_BtnHandler extends Activity {
Context context;
public Actionbar_BtnHandler (Context context)
{
this.context=context;
}
public void btn_handler (Button btn_mic,Button btn_post)
{
btn_mic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context,"MICROPHONE",Toast.LENGTH_LONG).show();
}
});
btn_post.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create();
}
});
}
}
Thanks in advance...
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
is inaccurate... The cast seems to fail
Try :
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = Actionbar_BtnHandler.this.getLayoutInflater();
Try this write your AlertDialog code using Handler..
btn_post.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Handler handler = new Handler();
handler.post(MessagealertDisplay);
}
});
}
Runnable MessagealertDisplay = new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Get the layout inflater
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
// Add action buttons
.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create();
}
};
i used
Actionbar_BtnHandler btns = new Actionbar_BtnHandle(Class.this);
btns.btn_handler(btn_post, btn_mic);
instead of
Actionbar_BtnHandler btns = new Actionbar_BtnHandler(getApplicationContext);
btns.btn_handler(btn_post, btn_mic);
and it worked

Categories

Resources