I'm new to java and I'm currently testing it in android studio.
I'm trying to access function showMessage() in TEST class from TEST2 class.
There is no problem if showMessage() function is called within the same class but the code stopped if I tried to access it from another class.
Maybe there is something wrong with my logic or syntax, but I'm not entirely sure which one is it. I already tried to search for some solution but there is no answer that I can find to help with my situation.
Here is my TEST.java code
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class TEST extends AppCompatActivity {
public TEST2 ab;
Button button;
private final String text ="Testing test test test testing test";
public void showMessage(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setCancelable(false) // cancel with button only
.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
button = (Button) findViewById(R.id.buttontest);
ab = new TEST2(this);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showMessage(text);
}
});
}
}
class TEST2 extends View{
public TEST t = new TEST();
public TEST2(Context context) {
super(context);
//there is error if I tried this 2 line code
//onTest();
//t.showMessage("TESTING FROM TEST2 CLASS");
}
public void onTest(){
t.showMessage("TESTING FROM TEST2 CLASS");
}
}
and this is my activity_test.xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/buttontest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
You can do this by passing parameter context
public void showMessage(String message, Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setCancelable(false) // cancel with button only
.show();
}
Alert Dialog is a UI element it will not run from another class if activity is changed. if activity is not change try this...
public void showMessage(final String message,final Context mContext) {
runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setCancelable(false) // cancel with button only
.show();
}
});
}
public void onTest(){
if (getContext() instanceof Test)
((Test)getContext()).showMessage("TESTING FROM TEST2 CLASS");
}
Just pass the Context of your TEST2 class.
public void showMessage(Context context, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
.............
......................
}
TEST2:
public TEST2(Context context) {
super(context);
t.showMessage(context, "TESTING FROM TEST2 CLASS");
}
Related
So belove is my code, in the design i have one textview with the ID t. I am using android 5.0 to build and i have the required SDK(android 5 and 5.1).
package com.example.alertdialogbox;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AlertDialog;
import android.os.Bundle;
import android.content.DialogInterface;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView t1=findViewById(R.id.t);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder b1=new AlertDialog.Builder(this);
b1.setTitle("Alert Dialog");
b1.setMessage("Do you want to continue?");
b1.setCancelable(false);
b1.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
t1.setText("Clicked YES");
}
});
b1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
t1.setText("Clicked NO");
}
});
b1.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
t1.setText("Clicked CANCEL");
}
});
AlertDialog d=b1.create();
d.show();
}
}
Sorry if my question looks silly :)
Thank you
call TextView t1=findViewById(R.id.t); after setContentView(R.layout.activity_main);
I searched but the questions I could see dealt with just copy, or copying to clipboard, or just pasting. Specifically what I want (in 1 button click, the PositiveButton in AlertDialog) is to copy the text entered by user in the EditText of my alertdialog to the EditText of my Activity.
Can you tell me how to do this please? Here is the code I am using and trying to fix:
//when user touches on "commentname" edittext we want the alertdialog to open
commentname.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
AlertDialog.Builder builder = new AlertDialog.Builder(NewContact.this);
builder.setTitle("Ur Comment:");
//start the following xml file/ layout
View viewInflated = LayoutInflater.from(NewContact.this).inflate(R.layout.comment_text_pop_up, null, false);
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//we want to copy the text entered in "input", in the alertdialog,
//and paste it in commentname
commentname.setText(alertdialog_edittext.getText().toString());
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
alertdialog_edittext = (EditText) dialog.findViewById(R.id.input);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
return true;
}
return false;
}
});
i wrote this simple code example for you to do it.
just add method to setText on Your edittext in your Activity:
private void setTextFromDialog(final String textFromDialog){
myEditText.setText(textFromDialog);
}
when user click in dialog get text from edittext dialog and pass using this method:
setTextFromDialog(YouEditTextValueX);
here code example:
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText myEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ShowDialog = findViewById(R.id.showdialog_id);
myEditText = findViewById(R.id.editText_id);
ShowDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
final EditText edittext = new EditText(MainActivity.this);
alert.setTitle("Title");
alert.setMessage("Message");
alert.setView(edittext);
alert.setPositiveButton("Set text", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String YouEditTextValueX = edittext.getText().toString();
if(YouEditTextValueX.length() > 0){
//this line for call method and pass the text
setTextFromDialog(YouEditTextValueX);
}
}
});
alert.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
alert.show();
}
});
}
private void setTextFromDialog(final String textFromDialog){
myEditText.setText(textFromDialog);
}
}
hope this help you
I create a application using DialogFragment.I want to get the Data from DialogFragment and setText in the MainActivity. In my Code I successfully Created the AlertDialog.But I con't able to get the EditText value to MainActivity.Application is crashed.Please help me to solve the problem.Any Help would be I really Appreciate.
MainActivity.java :
public class MainActivity extends ActionBarActivity {
Button showDialog;
TextView showText;
String myNameStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog = (Button)findViewById(R.id.myBtn);
showText = (TextView)findViewById(R.id.showText);
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMyAlert(v);
}
});
}
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert();
myAlert.show(getFragmentManager(), "My New Alert");
}
public void setMyNameStr(String myNameStr) {
showText.setText(myNameStr);
}
}
MyAlert.java:
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
MainActivity mainActivity = new MainActivity();
mainActivity.setMyNameStr(value);
dialog.dismiss();
}
}
Using this Procedure Application is Crashed.
replace from
MainActivity mainActivity = new MainActivity();
to:
Activity mainActivity = (MainActivity)getActivity();
Create an interface like-
CustomDialogInterface.java
public interface CustomDialogInterface {
// This is just a regular method so it can return something or
// take arguments if you like.
public void okButtonClicked(String value);
}
and modify your MyAlert.java by-
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
CustomDialogInterface customDI;
public MyAlert(CustomDialogInterface customDI)
{
this.customDI = customDI;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
dialog.dismiss();
customDI.okButtonClicked(value);
}
void setCustomDialogInterface(CustomDialogInterface customDialogInterface){
this. customDI = customDialogInterface;
c}
}
And implement CustomDialogInterface in your MainActivity and overide method okButtonClicked()
When onClick will be called then your MainActivity's onButtonClicked will be called .
and change showAlert to -
class MainActivity..... implements CustomDialogInterface {
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert(this);
myAlert.show(getFragmentManager(), "My New Alert");
}
#Overide
public void okButtonClicked(String value){
// handle
}
}
or use following code :
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert(this);
myAlert.setCustomDialogInterface(new CustomDialogInterface() {
#Override
public void okButtonClicked(String value) {
//handle click
}
});
myAlert.show(getFragmentManager(), "My New Alert");
}
you can achieve this using a interface,by sending your data from a fragment to main activity,below i have edited your complete code and its working fine....
Here is the code with example
Your Main Activity
package com.example.dialogfragment;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends Activity implements SetName{
Button showDialog;
TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog = (Button)findViewById(R.id.button1);
showText = (TextView)findViewById(R.id.textView2);
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showMyAlert(v);
}
});
}
public void showMyAlert(View view) {
MyAlert myAlert = new MyAlert();
myAlert.show(getFragmentManager(), "My New Alert");
}
public void setMyNameStr(String myNameStr) {
}
#Override
public void setMyName(String string) {
// TODO Auto-generated method stub
showText.setText(string);
}
}
Your Alert
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyAlert extends DialogFragment implements OnClickListener {
private EditText getEditText;
MainActivity callBackActivity;
SetName setname;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
callBackActivity = new MainActivity();
getEditText = new EditText(getActivity());
getEditText.setInputType(InputType.TYPE_CLASS_TEXT);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Get UserName :");
builder.setMessage("Enter Your Name :");
builder.setPositiveButton("Ok", this);
builder.setNegativeButton("Cancel", null);
builder.setView(getEditText);
return builder.create();
}
#Override
public void onAttach(Activity a) {
super.onAttach(a);
setname = (SetName) a;
}
#Override
public void onClick(DialogInterface dialog, int which) {
String value = getEditText.getText().toString();
Log.d("Name : ", value);
// MainActivity mainActivity = new MainActivity();
setname .setMyName(value);
//setname = (SetName)
// setname = (SetName)getActivity();
dialog.dismiss();
}
}
Create a Interface
public interface SetName {
void setMyName(String string);
}
Now what you should do is create onAttach in your alertFragment and call your interface..
public void renameFile(){
RenameFileDialog dialog = new RenameFileDialog();
dialog.show(getSupportFragmentManager(), DIALOG_RENAME_FILE);
}
public void syncFolders(String value) {
//some code
new UpdateFolderAsyncTask().execute();
}
update listview with new updated value after performining operation in main activity class syncFolders() in DialogFragment class
CustomDialogFragment extends DialogFragment{
//some logic for performining operation
String updatedValue=edittext.getText();
MainActivity activity=(MainActivity)getActivity();
activity.syncFolders(updatedValue);
}
I created a DialogFragment that looks like this:
package com.name.test;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.name.test.MainActivity.DialogType;
public class AlertDialogFragment extends DialogFragment {
public static DialogType type;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View v = getActivity().getLayoutInflater().inflate(R.layout.search_fragment, null);
final EditText searchField = (EditText)v.findViewById(R.id.searchEditTxt);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
switch(type) {
case SEARCH:
builder.setView(inflater.inflate(R.layout.search_fragment, null))
.setTitle("Search Dialog")
.setPositiveButton("Search", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// logic for the search button
// Toast.makeText(getActivity().getBaseContext(), "Search Dialog", Toast.LENGTH_SHORT).show();
String tempString = searchField.getText().toString();
System.out.println(tempString);
}
})
//.setView(searchField)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// logic for the cancel button
AlertDialogFragment.this.getDialog().cancel();
}
});
break;
case PREFERENCES:
builder.setView(inflater.inflate(R.layout.preferences_fragment, null))
.setTitle("Preferences")
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// logic for the search button
Toast.makeText(getActivity().getBaseContext(), "Preferences", Toast.LENGTH_SHORT).show();
}
})
//.setView(searchField)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// logic for the cancel button
AlertDialogFragment.this.getDialog().cancel();
}
});
break;
default:
break;
}
return builder.create();
}
public static AlertDialogFragment newInstance(DialogType dialogType) {
type = dialogType;
return new AlertDialogFragment();
}
}
In the XML file for this fragment I have this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="search_fragment"
android:orientation="vertical" >
<EditText
android:id="#+id/searchEditTxt"
android:hint="#string/search_menu_hint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
I'm trying to target that EditText in the DialogFragment so when the user types something and clicks on Save or OK I can store its value. I can't seem to be able to target the EditText properly. My System.out.println(tempString); is empty. What am I doing wrong? Thanks much.
try to change
builder.setView(inflater.inflate(R.layout.search_fragment, null));
to
builder.setView(v);
You just need to set your inflated view to your builder.
I have Code Image with Pich zoom
package com.androidtutorialpoint;
import com.androidtutorialpoint.imageview.PhotoView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends Activity {
private ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new HackyViewPager(this);
setContentView(mViewPager);
mViewPager.setAdapter(new SamplePagerAdapter());
}
static class SamplePagerAdapter extends PagerAdapter {
private static int[] sDrawables = {
R.drawable.ic_launcher,R.drawable.ic_launcher,
};
#Override
public int getCount() {
return sDrawables.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
PhotoView photoView = new PhotoView(container.getContext());
photoView.setImageResource(sDrawables[position]);
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
I have add imageButton listner ale marker with function switching to a new activity
My Image button lister have Code
public class MainActivity extends Activity {
private ImageView mainBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainBtn = (ImageView) findViewById(R.id.button);
mainBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openAlert(v);
}
});
}
private void openAlert(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle(this.getTitle()+ " ");
// set positive button: Yes message
alertDialogBuilder.setPositiveButton("więcej",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// go to a new activity of the app
Intent positveActivity = new Intent(getApplicationContext(), PositiveActivity.class);
startActivity(positveActivity);
}
});
// set negative button: No message
alertDialogBuilder.setNegativeButton("wyjście",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// cancel the alert box and put a Toast to the user
dialog.cancel();
Toast.makeText(getApplicationContext(), "Mapa Budnik",
Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show alert
alertDialog.show();
}
}
My Ask how to add a tag to the image Button and when you click the trigger Activity?
When my Image Button is in layaut.xml there is invisible.please help me