Registration with two steps, next fragment by button - java

I want to handle user registration in my app. I red that using fragments is the best way to handle it.
I prefer using button to move to registration finish fragment, than swype.
I have to send few field to another and finally send all of data by Retrofit.
Any solution?

You can implement a Callback to save the values on your activity.
First create the interface:
public interface ActivityCallback {
void sendData(String data1,String data2);
}
Then make your activity implements this interface:
public class MyActivity extends AppCompatActivity implements ActivityCallback{
private ArrayList<String> arrayData = new ArrayList<>();
...
#Override
void sendData(String data1, String data2){
this.arrayData.add(data1);
this.arrayData.add(data2);
}
...
}
Then on your fragment, when you decide to go to the next step:
public class YourFragment extends Fragment{
private Button nextButton;
private EditText text1;
private EditText text2;
protected ActivityCallback callback;
...
#Override
public void onAttach(Context context) {
super.onAttach(context);
callback = (ActivityCallback) context;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
...
nextButton = (Button) findViewById(R.id.next_button);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callback.sendData(text1.getText().toString(),text2.getText().toString());
}
});
}
}

Related

how to change actionBar title of Activity1 from a button of Activity2

I am trying to make a button in activity2(settings page), when the button is clicked, then the title of activity1(MainActivity) will change to what I set to. I have been trying to use interface to carry out the function but it gives me a null pointer exception error.
MainActivity
#Override
public void changeActionBarTitle(String editText){
actionTitle = editText;
setTitle(actionTitle);
};
Interface
public interface ActionBarInterface {
void changeActionBarTitle(String editText);
}
Setting page (activity 2)
public class SettingsPage extends AppCompatActivity {
ActionBarInterface actionBarInterface;
Button editCompanyNameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
actionBarInterface.changeActionBarTitle("test");
}
});
}
}
Thanks.
You can try this code without using the interface
MainActivity:
#Override
protected void onResume() {
setTitle(Main2Activity.title);
super.onResume();
}
activity2:
public class SettingsPage extends AppCompatActivity {
Button editCompanyNameButton;
static String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
title = "test";
}
});
}
}
It gives a null pointer exception error because actionBarInterface was not initialised.
Check out topics on 'Getting a Result from an Activity', making use of classes and functions such as Intent, startActivityForResult, onActivityResult.
Android: how to make an activity return results to the activity which calls it?

change Main UI from custom Dialog Class

I have 2 class, Main and DialogOrder
Main
public class Main extends Fragment{
ImageView order;
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DialogOrder(getActivity()).show();
}
});
return view;
}
public void init(Bundle savedInstanceState) {
order = (ImageView) view.findViewById(R.id.order);
order.setImageResource(R.drawable.orderd);
RelativeLayout.LayoutParams orderparams = new RelativeLayout.LayoutParams(Main.screenHeight / 8, Main.screenHeight / 8);
orderparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
orderparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
orderparams.setMargins(Main.screenHeight / 80, Main.screenHeight / 80, Main.screenHeight / 80, Main.screenHeight / 30);
order.setLayoutParams(orderparams);
}
public void update_UI(){
order.setVisibility(View.INVISIBLE);
}
}
DialogOrder
public class DialogOrder extends Dialog {
Button button;
Main main;
Activity context;
public DialogOrder(Activity context) {
super(context);
this.context = context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.order_dialog);
main = new Main();
button = (Button)findviewbyid(R.id.bd);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
main.update_UI();
dismiss();
}
});
}}
what I want is to set order image INVISIBLE when the user press the button on dialog
right now the code give me
java.lang.NullPointerException
probably I try update the UI wrong
so please can someone tell me what the right way to update parent UI class from child class ?
You can update your main fragment by passing it to Dialog constructor or you can use Listener/Callback to communicate between your main fragment and dialog.
The best practice is is using Listener/Callback because a Dialog should not have access to the caller. This is also decouple Dialog from Main fragment.
First, create the listener via interface in the dialog:
public class DialogOrder extends Dialog {
...
Activity context;
private DialogListener listener;
public interface DialogListener {
void onButtonClicked();
}
public DialogOrder(Activity context, DialogListener listener) {
super(context);
this.context = context;
this.listener = listener;
}
...
}
Then, when button click call the listener:
public class DialogOrder extends Dialog {
Activity context;
private DialogListener listener;
public interface DialogListener {
void onButtonClicked();
}
public DialogOrder(Activity context, DialogListener listener) {
super(context);
this.context = context;
this.listener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
...
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onButtonClicked();
dismiss();
}
});
}
}
Now, you can create the dialog with the listener. Something like this:
DialogOrder.DialogListener listener = new DialogOrder.DialogListener() {
#Ovveride
public void onButtonClicked() {
update_UI();
}
};
DialogOrder dialogOrder = new DialogOrder(getActivity(), listener);
dialogOder.show();
The main fragment will be listening for button clicked in the dialog.

android calling a MainActivity function from a fragment

I'm new to android and I'm trying to get a hang of creating and using Fragments.
I have a fragment that shows a simple list of multiple dates to choose from and implements an onClickListener. The idea is once a user chooses a date, the fragments sends the date back to the MainActivity which then runs a query in database and sends the database response to another fragment.
I'm stuck on the point of sending the date back to MainActivity, elegantly. I can't find much info. I found this:
Activity activity = getActivity();
if(activity instanceof MyActivity){
MyActivity myactivity = (MyActivity) activity;
myactivity.myMethod();
}
I'm very new to this but this seems hacky to me. Is this the right way or is there another way?
Any input is appreciated
I prefer the interface based approach because is very clean. You can declare a nested interface in your Fragment or an external one:
interface OnMyStuffListener {
void myMethod();
}
Make the Activity to implement that interface:
public class MainActivity extends Activity implements OnMyStuffListener {
#Override
public void myMethod() {
// Do whatever you want.
}
}
The Fragment will be attached to the Activity so you can check the instance of the Context and cast it to the Activity:
public class MyFragment extends Fragment implements View.OnClickListener {
private OnMyStuffListener mListener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMyStuffListener) {
mListener = (OnMyStuffListener) context;
} else {
throw new IllegalArgumentException("The context " + context.getClass().getName() +
"must implement " + OnMyStuffListener.class.getName());
}
}
#Override
public void onDetach() {
super.onDetach();
// Release it avoiding memory leak.
mListener = null;
}
#Override
public void onClick(View v) {
mListener.myMethod();
}
}
YES this is absolutely right. You can use this, if you are not sure that your Fragment is attached to Activity
You can also achieve this by using Interface, using an EventBus like LocalBroadcastManager, or starting a new Activity with an Intent and some form of flag passed into its extras Bundle or something else.
Here is an example about using Interface:
1. Add function sendDataToActivity() into the interface (EventListener).
//EventListener.java
public interface EventListener {
public void sendDataToActivity(String data);
}
2. Implement this functions in your MainActivity.
// MainActivity.java
public class MainActivity extends AppCompatActivity implements EventListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void sendDataToActivity(String data) {
Log.i("MainActivity", "sendDataToActivity: " + data);
}
}
3. Create the listener in MyFragment and attach it to the Activity.
4. Finally, call function using listener.sendDataToActivity("Hello World!").
// MyFragment.java
public class MyFragment extends Fragment {
private EventListener listener;
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
if(activity instanceof EventListener) {
listener = (EventListener)activity;
} else {
// Throw an error!
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
// Send data
listener.sendDataToActivity("Hello World!");
return view;
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
}
Hope this will help~

Trying to insert to database with methods from MainActivity from Fragment

im newbie with fragment, and i want to insert some data into database from Fragment with methods from MainActivity
here is my code
LaporanFragment
public class LaporanFragment extends Fragment{
EditText judulL, isiL;
TextView nomor_ktp, ambilNama;
ImageView fotoL;
Button kirim;
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_laporan, container, false);
judulL = (EditText) v.findViewById(R.id.judulLaporan);
isiL = (EditText) v.findViewById(R.id.isiLaporan);
nomor_ktp = (TextView) getActivity().findViewById(R.id.nomor_ktp);
final String noktp = nomor_ktp.getText().toString();
//fotoL = (ImageView) v.findViewById(R.id.foto_laporan);
final String jdlLaporan = judulL.getText().toString();
final String isiLaporan = isiL.getText().toString();
kirim = (Button) v.findViewById(R.id.kirim_laporan);
kirim.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((MainActivity)getActivity()).kirim_lapor(jdlLaporan, isiLaporan, noktp);
}
});
return v;
}
and MainActivity with kirim_lapor method
public void kirim_lapor(final String judul, final String isi, final String username){
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_LAPOR,
new Response.Listener<String>(){
#Override
public void onResponse(String response){
//progressDialog.dismiss();
try{
JSONObject jsonObject = new JSONObject(response);
//Toast.makeText(LaporanFragment.this, jsonObject.getString("message"), Toast.LENGTH_LONG).show();
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
//progressDialog.hide();
//Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("judul_laporan", judul);
params.put("isi_laporan", isi);
params.put("no_ktp", username);
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
the problem is when i press button kirim in fragment, the app will crash
please help me guys, sorry for my bad english.
To localize and hinder further error, instead of calling the MainActivity method via casting the getActivity(), you should make a Listener for telling the Activity about the data.
Create the interface for Listener in Fragment:
public class LaporanFragment extends Fragment {
private LaporanListener mListener;
// Define a Listener to 'speak up' to the main activity
public interface LaporanListener {
public void onSendReportClicked(String title, String content, String idNumber);
}
...
}
When clicking the button sendReport, use the listener:
public class LaporanFragment extends Fragment {
...
...
kirim.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mListener.onSendReportClicked(jdlLaporan, isiLaporan, noktp);
}
});
...
...
}
Then you need to implement the interface Listener to the MainActivity:
public class MainActivity extends Activity implements LaporanFragment.LaporanListener {
...
#Override
public void onSendReportClicked(String title, String content, String idNumber) {
// MainActivity will receive the data here.
// You need to process here.
}
...
}
For further reading, read Creating Custom Listeners.

Can i declare and use the same button in an Activity and a class?

I want to use the button for different calls in the different classes. However, when I declare and try to call the Button click method in the Activity class, it throws a null exception. In my Class I want to do this:
public class CustomFeedListViewAdapter extends BaseAdapter {
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
private class ViewHolder {
Button feedUpVoteButton;
}
And in my main activity I want to do this:
public class Feed extends AppCompatActivity {
Button upVoteButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
upVoteButton = (Button) findViewById(R.id.feedUpVoteButton);
feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
}
}
You are getting NullPointerException because you are trying to access feedUpVoteButton which is present in the item layout used in CustomFeedListViewAdapter and not in the layout used by Feed activity.
Do you want to have access to the ClickListener whenever you create an adapter of type CustomFeedListViewAdapter? If yes then do this...
Your Activity class
public class Feed extends AppCompatActivity {
CustomFeedListViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
adapter = new CustomFeedListViewAdapter( new OnClickListener() {
#Override
public void onClick(View v) {
// Handle click here
}
});
}
}
And your custom adapter class
public class CustomFeedListViewAdapter extends BaseAdapter {
View.OnClickListener clickListener;
// Constructor
public CustomFeedListViewAdapter(View.OnClickListener listener) {
clickListener = listener;
}
#Override
void getView(){
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
}
}
This way you can set a different listener for each instance of the adapter you create.

Categories