Android Pich zoom Image how add ImageButton listner - java

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

Related

How to set RecyclerView OnClickListener in Fragments?

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);
}

Android - String value from AlertDialog keeps resetting on access

I'm having an issue where I enter data into where my string keeps resetting to null even after I have entered data for it in my AlertDialog Fragment. What's supposed is that I enter data into a EditText object, store it in a string variable, set it as the string value in my Getter/Setter class then retrieve from that class in my fragment.
Image of AlertDialog
AlertDialog Fragment
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import org.ramferno.scoutapplication.ramfernoscout.R;
import org.ramferno.scoutapplication.ramfernoscout.providers.AddressProvider;
public class AddressDialogFragment extends DialogFragment {
AddressProvider addressProvider = new AddressProvider();
EditText enterIP;
String urlAddress;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Declare and initialize objects
LayoutInflater i = getActivity().getLayoutInflater();
View v = i.inflate(R.layout.fragment_dialog, null);
enterIP = (EditText) v.findViewById(R.id.enterIP);
//Create AlertDialog
AlertDialog.Builder b = new AlertDialog.Builder(getActivity())
.setTitle("Enter IP Address")
.setPositiveButton("ADD",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
urlAddress = enterIP.getText().toString();
addressProvider.setAddress(urlAddress);
} //End of onClick
}) //End of DialogInterface
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
} //End of onClick
} //End of DialogInterface
); //End of AlertDialog
b.setView(v);
return b.create();
} //End of onCreateDialog
} //End of class
Getter/Setter class
public class AddressProvider {
private String urlAddress;
public String getAddress() {
return urlAddress;
} //End of getAddress
public void setAddress(String urlAddress) {
this.urlAddress = urlAddress;
} //End of setAddress
} //End of class
ScoutFragment (Fragment that receives string from Getter/Setter)
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.ramferno.scoutapplication.ramfernoscout.downloaders.Downloader;
import org.ramferno.scoutapplication.ramfernoscout.R;
import org.ramferno.scoutapplication.ramfernoscout.providers.AddressProvider;
//Start of ScoutFragment
public class ScoutFragment extends Fragment {
//Declares Android UI objects
AddressProvider addressProvider = new AddressProvider();
FloatingActionButton addDataScout;
ListView eListScoutInfo;
String IP = addressProvider.getAddress();
//Declare and initialize variable
String urlAddress = "http://" + IP + "/ramfernoscout/matchdb/matchretrieve.php";
public ScoutFragment() {
// Required empty public constructor
} //End of ScoutFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflates layout for this fragment
View view = inflater.inflate(R.layout.fragment_scout, null, false);
//Instantiate ListView object with the xml ListView object
eListScoutInfo = (ListView) view.findViewById(R.id.listScoutInfo);
//Add instructions to the Refresh FAB that will download the data from the database server
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Downloader d = new Downloader(getActivity(),urlAddress,eListScoutInfo);
d.execute();
} //End of onClick
}); //End of setOnClickListener
//Change fragment to AddScoutDataFragment with animations
addDataScout = (FloatingActionButton) view.findViewById(R.id.fab);
addDataScout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AddScoutDataFragment fragment = new AddScoutDataFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right,
R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} //End of onClick
}); //End of setOnClickListener
//Returns view
return view;
} //End of onCreateView
} //End of class
You are using AddressProvider addressProvider = new AddressProvider(); in both ScoutFragment and AddressDialogFragment.
The new operator will create a new instance of AddressProvider class. If you want to persist the data, you should create only a single instance of AddressProvider. So you should make AddressProvider a SingleTon class.
public class AddressProvider {
private static AddressProvider ourInstance = new AddressProvider();
private String urlAddress;
private AddressProvider() {
}
public static AddressProvider getInstance() {
return ourInstance;
}
public String getAddress() {
return urlAddress;
}
public void setAddress(String urlAddress) {
this.urlAddress = urlAddress;
}
}
Usage,
To store the IP,
AddressProvider.getInstance().setAddress("xxx.xxx.xx.xx");
to retrieve,
AddressProvider.getInstance().getAddress()

Handling orientation change in android studio

I have been struggling with an issue in a note application i have been building with the help of a tutorial series. I just created a dialog allowing the user to change the category of a note but the new category is lost whenever the orientation is changed. as instructed by tutorial i override onSavedInstance to save information first but for some reason is not solved code below:
package com.workingprogess.notebook;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
public class NoteEditFragment extends Fragment {
private ImageButton noteCatButton;
private EditText title;
private EditText message;
private Button saveButton;
private Note.Category savedButtonCategory;
private AlertDialog categoryDialogObject;
private AlertDialog confirmDialogObject;
private static final String MODIFIED_CATEGORY="Modified Category";
public NoteEditFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(savedInstanceState!=null){
savedButtonCategory = (Note.Category) savedInstanceState.get(MODIFIED_CATEGORY);
}
//grab layout and assign to view so that we may access widgets
View fragmentLayout = inflater.inflate(R.layout.fragment_note_edit, container, false);
//grab widget references
title = (EditText) fragmentLayout.findViewById(R.id.editNoteTitle);
message = (EditText) fragmentLayout.findViewById(R.id.editMessage);
noteCatButton = (ImageButton) fragmentLayout.findViewById(R.id.editNoteButton);
saveButton = (Button) fragmentLayout.findViewById(R.id.saveNoteButton);
//populate with note data
Intent intent = getActivity().getIntent();
title.setText(intent.getExtras().getString(MainActivity.NOTE_TITLE_EXTRA));
message.setText(intent.getExtras().getString(MainActivity.NOTE_MESSAGE_EXTRA));
if(savedButtonCategory !=null){
Log.d("not null","the new image should be carried over");
noteCatButton.setImageResource(Note.categoryToDrawable(savedButtonCategory));
} else {
Note.Category noteCat = (Note.Category) intent.getSerializableExtra(MainActivity.NOTE_CATEGORY_EXTRA);
savedButtonCategory = noteCat;
noteCatButton.setImageResource(Note.categoryToDrawable(noteCat));
Log.e("null","pull from intent" );
}
//set onclick listeners
buildCategoryDialog();
noteCatButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
categoryDialogObject.show();
}
});
buildConfirmDialog();
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialogObject.show();
}
});
// Inflate the layout for this fragment
return fragmentLayout;
}
//save info before orientation change.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d("save","info is saved");
savedInstanceState.putSerializable(MODIFIED_CATEGORY, savedButtonCategory);
}
//build pop uo dialog to change note info
private void buildCategoryDialog(){
final String[] categories = new String[]{"Personal","Technical","Quote","Finance"};
final AlertDialog.Builder categoryBuilder = new AlertDialog.Builder(getActivity());
categoryBuilder.setTitle("Choose Note Type");
categoryBuilder.setSingleChoiceItems(categories, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int item) {
switch (item){
case 0:
savedButtonCategory= Note.Category.PERSONAL;
noteCatButton.setImageResource(R.drawable.p_icon);
break;
case 1:
savedButtonCategory=Note.Category.TECHNICAL;
noteCatButton.setImageResource(R.drawable.t_icon);
break;
case 2:
savedButtonCategory=Note.Category.QUOTE;
noteCatButton.setImageResource(R.drawable.q_icon);
break;
case 3:
savedButtonCategory=Note.Category.FINANCE;
noteCatButton.setImageResource(R.drawable.f_icon );
break;
}
categoryDialogObject.cancel();
}
});
categoryDialogObject=categoryBuilder.create();
}
private void buildConfirmDialog(){
final AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(getActivity());
confirmBuilder.setTitle("are you sure?");
confirmBuilder.setMessage("are you sure you want to save this note");
confirmBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("Save Note","Note title " + title.getText()+ "Note message "
+ message.getText()+" note category" + savedButtonCategory);
Intent intent = new Intent(getActivity(),MainActivity.class);
startActivity(intent);
}
});
confirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
savedButtonCategory=Note.Category.TECHNICAL;
}
});
confirmDialogObject = confirmBuilder.create();
}
}
Open your application Manifest file and for particular activity, add this code:
<activity
android:name=".MainActivity" //Activity where the problem is occuring
android:configChanges="screenLayout|orientation|screenSize">
Its better to add this "android:configChanges" to every activity to maintain data state even if orientation changes.
Have you checked if onSaveInstanceState is actually getting called? This callback will only be called if the Activity holding the fragment is getting destroyed. So, first check if your Activity is getting destroyed or not.

Pass the EditText.getText from FirstFragment to SecondFragment when the User swipes

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.

How to get the Data from DialogFragment to MainActivity in Android?

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);
}

Categories

Resources