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);
}
Related
I am having some trouble. I followed every guide online showing how to override a parent method in a child class. I have done everything I was told to do, yet my child function does nothing.
My MainActivity(Parent) class:
package com.example.flashcards;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
DatabseHelper DB = new DatabseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeText();
changeText2();
};
public void changeText(){}
public void changeText2(){}
String [] columns = new String[] {
DatabseHelper.FLASHCARD_QUESTION,
DatabseHelper.FLASHCARD_ANSWER
};
#Override
public void onClick(View v) {
}
}
My child class (TextC)
package com.example.flashcards;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TextC extends MainActivity {
#Override
public void changeText() {
super.changeText();
final String[] revertText = {"H2O", "What elements does water consist of?"};
final TextView textChange = findViewById(R.id.flashcard1);
Button change = findViewById(R.id.answer1);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
public void changeText2() {
super.changeText2();
final String[] revertText = {"2,200° F", "How hot does lava get?"};
final TextView textChange = findViewById(R.id.flashcard2);
Button change = findViewById(R.id.answer2);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
}
My changeText() function does nothing. I am not getting any errors, so I can not tell what I am doing wrong. Do I need to create an onCreate method for the child class? But I am extending MainActivity which has it.
Any ideas on why my method overriding is not working?
With inheritance and overriding concepts, you need to override onCreate function in your child class. And from that overridden method, you can make a call to super.onCreate or you can do this.chnageText and this.changeText2 from child class.
Otherwise when you call onCreate function, it will call changeText and changeText2 from super class only.
In your child class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.changeText();
this.changeText2();
};
Modify parent class
package com.example.flashcards;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
DatabseHelper DB = new DatabseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//changeText(); freeze or remove these callings
//changeText2();
};
public void changeText(){}
public void changeText2(){}
}
And add some code to your child class
package com.example.flashcards;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TextC extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
changeText();
changeText2();
};
#Override
public void changeText() {
super.changeText();
final String[] revertText = {"H2O", "What elements does water consist of?"};
final TextView textChange = findViewById(R.id.flashcard1);
Button change = findViewById(R.id.answer1);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
public void changeText2() {
super.changeText2();
final String[] revertText = {"2,200° F", "How hot does lava get?"};
final TextView textChange = findViewById(R.id.flashcard2);
Button change = findViewById(R.id.answer2);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
}
In the above method there is no point declare changeText(); and changeText2(); in parent activity. For the sake of reusability, we can use abstract classes and methods.
Do some changes to your parent activity as you see below.
public abstract class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeText(); // they dont have default implimentation in parent so it will be invoked from child class where these methods implimented
changeText2();
};
public abstract void changeText(); //there is no default implimentation
public abstract void changeText2();
}
And in child activity, you have to implement those methods.
public class TextC extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//changeText(); no need to call these methods bcz its already called in parent onCreate()
//changeText2();
};
#Override
public void changeText() {
super.changeText();
final String[] revertText = {"H2O", "What elements does water consist of?"};
final TextView textChange = findViewById(R.id.flashcard1);
Button change = findViewById(R.id.answer1);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
public void changeText2() {
super.changeText2();
final String[] revertText = {"2,200° F", "How hot does lava get?"};
final TextView textChange = findViewById(R.id.flashcard2);
Button change = findViewById(R.id.answer2);
change.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int) (Math.random() * revertText.length);
textChange.setText(revertText[random]);
}
});
}
}
I'm trying to start a new Fragment that shows the details of the item that was clicked on in the RecyclerView. I've tried this in Activities and it worked perfectly but I'm trying to convert it to use on Fragments. Every time I get an 'null object reference'.
Adapter
package com.umbrella.fragmenttest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class BorrowedAdapter extends RecyclerView.Adapter<BorrowedAdapter.BorrowedViewHolder> {
private Context mCtx;
private List<Borrowed> borrowedList;
public BorrowedAdapter(Context mCtx, List<Borrowed> borrowedList) {
this.mCtx = mCtx;
this.borrowedList = borrowedList;
}
#Override
public BorrowedViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.list_borrowed, parent, false);
return new BorrowedViewHolder(view);
}
#Override
public void onBindViewHolder(BorrowedViewHolder holder, int position) {
Borrowed b = borrowedList.get(position);
holder.textViewOwner.setText(b.getOwner());
holder.textViewDesc.setText(b.getDesc());
holder.textViewAmount.setText(String.valueOf(b.getAmount()));
}
#Override
public int getItemCount() {
return borrowedList.size();
}
class BorrowedViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewOwner, textViewDesc, textViewAmount;
public BorrowedViewHolder(View itemView) {
super(itemView);
textViewOwner = itemView.findViewById(R.id.b_owner);
textViewDesc = itemView.findViewById(R.id.b_description);
textViewAmount = itemView.findViewById(R.id.b_amount);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Borrowed borrowed = borrowedList.get(getAdapterPosition());
AppCompatActivity activity = (AppCompatActivity) view.getContext();
NavController navController = Navigation.findNavController(activity, R.id.hostfrag);
navController.navigate(R.id.action_displayBorrowed2_to_updateBorrowedClass);
}
}
}
Fragment class with the details
package com.umbrella.fragmenttest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class UpdateBorrowedClass extends Fragment {
private EditText editTextOwner, editTextDesc, editTextAmount;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.new_borrowed, container, false);
editTextOwner = view.findViewById(R.id.u_owner);
editTextDesc = view.findViewById(R.id.u_description);
editTextAmount = view.findViewById(R.id.u_amount);
Bundle bundle = getArguments();
final Borrowed borrowed = (Borrowed) bundle.getSerializable("borrowed");
loadBorrowed(borrowed);
view.findViewById(R.id.button_update).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateBorrowed(borrowed);
}
});
view.findViewById(R.id.button_delete).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteBorrowed(borrowed);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog ad = builder.create();
ad.show();
}
});
return view;
}
private void loadBorrowed(Borrowed borrowed) {
editTextOwner.setText(borrowed.getOwner());
editTextDesc.setText(borrowed.getDesc());
editTextAmount.setText(String.valueOf(borrowed.getAmount()));
}
private void updateBorrowed(final Borrowed borrowed) {
final String sOwner = editTextOwner.getText().toString().trim();
final String sDesc = editTextDesc.getText().toString().trim();
final Double dAmount = Double.parseDouble(editTextAmount.getText().toString().trim());
if (sOwner.isEmpty()) {
editTextOwner.setError("Owner required");
editTextOwner.requestFocus();
return;
}
if (sDesc.isEmpty()) {
editTextDesc.setError("Description required");
editTextDesc.requestFocus();
return;
}
if (dAmount.toString().isEmpty()) {
editTextAmount.setError("Amount required");
editTextAmount.requestFocus();
return;
}
class UpdateBorrowed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
//Creating an item
borrowed.setOwner(sOwner);
borrowed.setDesc(sDesc);
borrowed.setAmount(dAmount);
//Adding to database
DatabaseClient.getInstance(getContext())
.borrowedDao()
.update(borrowed);
return null;
}
//Returns to the {RecyclerViewFragment} because the item is created
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
DisplayBorrowed displayBorrowed = new DisplayBorrowed();
getChildFragmentManager().beginTransaction().replace(R.id.mainer, displayBorrowed).addToBackStack(null).commit();
Toast.makeText(getContext(), "Updated", Toast.LENGTH_LONG).show();
}
}
UpdateBorrowed ut = new UpdateBorrowed();
ut.execute();
}
private void deleteBorrowed(final Borrowed borrowed) {
class DeleteBorrowed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
DatabaseClient.getInstance(getContext())
.borrowedDao()
.delete(borrowed);
return null;
}
//Returns to the {RecyclerViewFragment} because the item is created
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
DisplayBorrowed displayBorrowed = new DisplayBorrowed();
getChildFragmentManager().beginTransaction().replace(R.id.mainer, displayBorrowed).addToBackStack(null).commit();
Toast.makeText(getContext(), "Deleted", Toast.LENGTH_LONG).show();
}
}
DeleteBorrowed dt = new DeleteBorrowed();
dt.execute();
}
}
Run log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.umbrella.fragmenttest, PID: 31428
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference
at com.umbrella.fragmenttest.UpdateBorrowedClass.onCreateView(UpdateBorrowedClass.java:31)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2646)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2416)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2372)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Application terminated.
Have a look at this link: https://developer.android.com/guide/navigation/navigation-pass-data#bundle
In your onClick()
#Override
public void onClick(View view) {
Borrowed borrowed = borrowedList.get(getAdapterPosition());
AppCompatActivity activity = (AppCompatActivity) view.getContext();
NavController navController = Navigation.findNavController(activity, R.id.hostfrag);
navController.navigate(R.id.action_displayBorrowed2_to_updateBorrowedClass);
}
You should add a bundle with your borrowed object as argument like below:
#Override
public void onClick(View view) {
Borrowed borrowed = borrowedList.get(getAdapterPosition());
Bundle bundle = new Bundle();
bundle.putSerializable("borrowed", borrowed);
AppCompatActivity activity = (AppCompatActivity) view.getContext();
NavController navController = Navigation.findNavController(activity, R.id.hostfrag);
navController.navigate(R.id.action_displayBorrowed2_to_updateBorrowedClass, bundle);
}
what i'm trying to do:
in FirstFragment the user can type in his weight.
in SecondFragment the weight should be shown in a TextView
the Value should be passed on swipe of the user.
i tried arround 3 how-to's and read a lot about fragments but i still couldn't find a suitable solution. As i'm kind of new to fragments it could also be that i made a uncommon way to generate fragments and it therefore doesn't work but i couldn't figure it out yet.
As you can se unerneath actually there is an error in the code because i tried to get access to the method of FirstFragment through the MainActivity
To simplyfy, i don't poste the whole code of the two fragment xlm's.
first_frag.xml have a EditText (id: getWeight) Box where you only can enter numbers up to 3 digits
second_frag.xml has a TextView (id: txtAlcLvl)
activity_main.xml:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
MainActivity.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
Calculator calc = new Calculator();
ViewPager pager;
private MyPagerAdapter myPagerAdapter;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
public Calculator getCalc(){
return this.calc;
}
public void getWeight(){
FragmentManager fm = getSupportFragmentManager();
FirstFragment fragment = (FirstFragment)fm.findFragmentById(R.id.i_dont_know_the_id);
//failure because trying to get access to Method of FirstFragment
fragment.getWeight();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int i, final float v, final int i2) {
}
#Override
public void onPageSelected(final int i) {
YourFragmentInterface fragment = (YourFragmentInterface) pagerAdapter.instantiateItem(pager, i);
if (fragment != null) {
fragment.fragmentBecameVisible();
}
}
#Override
public void onPageScrollStateChanged(final int i) {
}
});
}
public interface YourFragmentInterface {
void fragmentBecameVisible();
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 1: return new SecondFragment(); //SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return new FirstFragment();
default: return new FirstFragment(); //FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
FirstFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FirstFragment extends Fragment implements MainActivity.YourFragmentInterface {
Button btnBeer;
Button btnBeerSmall;
Button btnWine;
Button btnLiq;
Button btnSch;
Button btnWater;
Button btnMale;
Button btnFemale;
Calculator calc;
EditText getWeight;
public String getWeight(){
return getWeight.getText().toString();
}
#Override
public void fragmentBecameVisible() {
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
btnBeer = (Button) v.findViewById(R.id.btnBeer);
btnBeerSmall = (Button) v.findViewById(R.id.btnBeerSmall);
btnWine = (Button) v.findViewById(R.id.btnWine);
btnLiq = (Button) v.findViewById(R.id.btnLiq);
btnSch = (Button) v.findViewById(R.id.btnSch);
btnWater = (Button) v.findViewById((R.id.btnWater));
btnMale = (Button) v.findViewById(R.id.btnMale);
btnFemale = (Button) v.findViewById(R.id.btnFemale);
getWeight = (EditText) v.findViewById(R.id.getWeight);
btnBeer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(0);
}
});
btnBeerSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(1);
}
});
btnWine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(2);
}
});
btnLiq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(3);
}
});
btnSch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(4);
}
});
btnWater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(5);
}
});
btnMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnMale.setBackgroundResource(R.drawable.male_false);
btnFemale.setBackgroundResource(R.drawable.female);
}
});
btnFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnFemale.setBackgroundResource(R.drawable.female_false);
btnMale.setBackgroundResource(R.drawable.male);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
SecondFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class SecondFragment extends Fragment implements MainActivity.YourFragmentInterface {
TextView txtAlcLvl;
TextView txtTimeToZero;
TextView txtPeak;
ImageButton btnReset;
Calculator calc;
String weight;
#Override
public void fragmentBecameVisible() {
calc.person.setSex(false);
calc.person.setWeight(80);
txtAlcLvl.setText(((MainActivity) getActivity()).getWeight());
//txtAlcLvl.setText(String.format("%.2f", calc.getCurrentLevel()) + "‰");
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
public void setSex(){
}
public void setWeight(){
try{
} catch(NumberFormatException e){
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
txtAlcLvl = (TextView) v.findViewById(R.id.txtAlcLvl);
txtTimeToZero = (TextView) v.findViewById(R.id.txtTimeToZero);
txtPeak = (TextView) v.findViewById(R.id.txtPeak);
btnReset = (ImageButton) v.findViewById((R.id.btnReset));
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.resetConsumption();
}
});
return v;
}
public void updateText(String t){
txtAlcLvl.setText(t);
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
You could do it the over way round.
Instead of trying to get the weight in activity from your fragment, try to set the weight on the activity from the fragment.
public class MainActivity extends FragmentActivity {
...
private float weight;
public void setWeight(float weight) {
this.weight = weight;
}
public float getWeight() {
return this.weight();
}
Then in your FirstFragment:
((MainActivity)getActivity()).setWeight(...);
And finally in your SecondFragment:
float weight = ((MainActivity)getActivity()).getWeight();
Don't try to "pass" the value like you would normally expect when an activity is invoking a new fragment.
Instead, consider using some persistent storage to store the value, such as SharedPreferences or a Sqlite database. Each fragment can read and write values out of there as needed.
package test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
public class DisplayAlert extends Activity implements OnClickListener
{
int t;
public int dis( String destinationAddress)
{
new AlertDialog.Builder(this).setTitle("SEND MESSAGE")
.setMessage("Are you sure you want to send this msg to no ? "+ destinationAddress)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
t=0;
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
t=1;
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return t;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
package com.meproject2;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import test.SmsManager;
import test.DisplayAlert;
public class MainActivity extends Activity implements OnClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(this);
}
#Override
public void onClick(View v) {
int j;
try {
final String phoneNumber = ((EditText)
findViewById(R.id.editview1)).getText().toString();
EditText editText = (EditText)findViewById(R.id.editview1);
DisplayAlert ob =new DisplayAlert();
j=ob.dis(phoneNumber);
if(j==0)
SmsManager.getDefault().sendTextMessage1(phoneNumber, null, "Hello SMS!", null, null);
editText.setText("hello ");
}
catch (Exception e) {
}
}
}
I created a class to display dialog box and call the function in Activity main but its not working.if I write the function in ActivityMain then its working but if I write the function in separate class then the dislog box is not displayed
You need a Context to display Dialog. and remove extends Activity from DisplayAlert.
try this way pass context to single argument constructor
DisplayAlert ob =new DisplayAlert(MainActivity.this);
and create constructor like
Context context;
public DisplayAlert(Context context) {
this.context = context;
}
and used this context to create AlertDialog
new AlertDialog.Builder(context).setTitle("SEND MESSAGE")....
DisplayAlert extends Activity but it isn't an activity. You cannot instantiate activities with new. Remove the extends Activity.
Pass a valid context as a parameter to methods that need it. For example,
public int dis(Context activityContext, String destinationAddress)
{
new AlertDialog.Builder(activityContext).setTitle("SEND MESSAGE")
call as
ob.dis(MainActivity.this, phoneNumber);
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