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.
Related
The code I've done was followed closely by a few YouTube tutorials. I'm designing an Age of Empires app that takes in the data from a public API. When the user progresses through the pages then different parts of the API data are shown. What I wanted it to do was get the data from the main activity (where the API is retrieved) and put some of its many data into the UniqueUnit page. It's using something called serializable which I can't quite understand how it works yet.
For the record, it works in getting the data from page 'DetailedCivilization' but just completely breaks on 'UniqueUnit'page.
MainActivity.java
package com.example.ageofempires2;
import ...
public class MainActivity extends AppCompatActivity {
public static final String TAG = "tag";
RecyclerView itemList;
Adapter adapter;
List<Civilizations> all_civilizations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setTitle("Civilizations menu");
all_civilizations = new ArrayList<>();
itemList = findViewById(R.id.itemList);
itemList.setLayoutManager(new LinearLayoutManager(this));
adapter = new Adapter(this, all_civilizations);
itemList.setAdapter(adapter);
getJsonData();
}
private void getJsonData() {
String URL = "https://age-of-empires-2-api.herokuapp.com/api/v1/civilizations";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray civilizations = response.getJSONArray("civilizations");
JSONObject civilizationsData = civilizations.getJSONObject(0);
Log.d(TAG, "onResponse "+ civilizationsData);
for (int i=0; i< civilizationsData.length();i++){
JSONObject civilization = civilizations.getJSONObject(i);
Civilizations v = new Civilizations();
v.setName(civilization.getString("name"));
v.setArmy_type(civilization.getString("army_type"));
v.setExpansion(civilization.getString("expansion"));
v.setCivilization_bonus(civilization.getString("civilization_bonus"));
v.setUnique_unit(civilization.getString("unique_unit"));
all_civilizations.add(v);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse" + error.getMessage());
}
});
requestQueue.add(objectRequest);
}
}
Adapter.java
package com.example.ageofempires2;
import ...
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
private List<Civilizations> allCivilizations;
private Context context;
public Adapter(Context ctx, List<Civilizations> civilizationsData){
this.allCivilizations = civilizationsData;
this.context = ctx;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.civilization_view,parent,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.titleName.setText(allCivilizations.get(position).getName());
holder.vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putSerializable("civilizationsData", allCivilizations.get(position));
Intent i = new Intent(context, DetailedCivilization.class);
i.putExtras(b);
v.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return allCivilizations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleName;
TextView expansionName;
View vv;
public ViewHolder(#NonNull View itemView) {
super(itemView);
titleName = itemView.findViewById(R.id.civilizationUniqueUnits);
expansionName = itemView.findViewById(R.id.civilizationUnitDescription);
vv = itemView;
}
}
}
Civilizations.java
package com.example.ageofempires2;
import java.io.Serializable;
public class Civilizations implements Serializable {
private String name;
private String expansion;
private String army_type;
private String civilization_bonus;
private String unique_unit;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getExpansion() {
return expansion;
}
public void setExpansion(String expansion) {
this.expansion = expansion;
}
public String getArmy_type() {
return army_type;
}
public void setArmy_type(String army_type) {
this.army_type = army_type;
}
public String getCivilization_bonus() {
return civilization_bonus;
}
public void setCivilization_bonus(String civilization_bonus) {this.civilization_bonus = civilization_bonus; }
public String getUnique_unit() {
return unique_unit;
}
public void setUnique_unit(String unique_unit) {this.unique_unit = unique_unit; }
}
UniqueUnits.java
package com.example.ageofempires2;
import ...
public class UniqueUnit extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unique_unit);
getSupportActionBar().setTitle("Unique Unit");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent incomingIntent = getIntent();
Bundle incomingName = incomingIntent.getExtras();
Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData");
Log.d(TAG, "onCreate: IDK MAN IT SHOULD WORK??" +incomingName);
TextView unit = findViewById(R.id.civilizationUnitDescription);
unit.setText(v.getUnique_unit());
}
}
DetailedCivilization.java
package com.example.ageofempires2;
import ...
public class DetailedCivilization extends AppCompatActivity {
public static final String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations v = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit();
}
});
}
private void activityTech(){
Intent intent = new Intent(this, UniqueTech.class);
startActivity(intent);
}
private void activityUnit(){
Intent intent = new Intent(this, UniqueUnit.class);
startActivity(intent);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
Solutions is
private void activityUnit(Civilizations civ){
Bundle b = new Bundle();
b.putSerializable("civilizationsData", civ)
Intent intent = new Intent(this, UniqueUnit.class);
intent.putExtras(b);
startActivity(intent);
}
In DetailedCivilization.java
Rename v from line Civilizations v = (Civilizations) incomingName.getSerializable("civilizationsData"); to civ or something more descriptive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_civilization);
getSupportActionBar().setTitle("Detailed view");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
Bundle data = i.getExtras();
Civilizations civ = (Civilizations) data.getSerializable("civilizationsData");
TextView type = findViewById(R.id.civilizationType);
type.setText(v.getArmy_type());
TextView title = findViewById(R.id.civilizationUniqueUnits);
title.setText(v.getName());
TextView expansions = findViewById(R.id.civilizationUnitDescription);
expansions.setText(v.getExpansion());
TextView bonus = findViewById(R.id.civilizationBonus);
bonus.setText(v.getCivilization_bonus());
Button changeActivityTech = findViewById(R.id.tech_button);
Button changeActivityUnit = findViewById(R.id.unit_button);
changeActivityTech.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityTech();
}
});
changeActivityUnit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activityUnit(civ);
}
});
}
And pass Civilizations when you call activityUnit function
Basically you forgot to pass Civilizations when you go from DetailedCivilization.java to UniqueUnits.java
Updated Problem: My text of the SecondAcitivity is displayed in the recycling view of my MainActivity. However, the text in the Recyclerview will be overwritten.
How do I get it that the text in my recycling view is not overwritten, but is displayed in a further field one below the other?
I would like to have a button in my main activity that opens Activity 2. A text should then be entered there, which should then be displayed by clicking a button in the Recyclerview of the main activity.
I have already inserted a recylerview adapter, but the text is not output. Where is the problem?
On my XML i got 2 Buttons (one in the MainActivity (floatingActionButton) and one in the Second (sendNewTask))
My MainActivity:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton floatingActionButton;
TaskManager taskManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskManager = new TaskManager(this);
initViews();
initClickListener();
receiveIntent();
setRecyclerView();
}
protected void initViews(){
floatingActionButton = findViewById(R.id.floating_button);
recyclerView = findViewById(R.id.recyclerview);
}
protected void initClickListener(){
floatingActionButton.setOnClickListener(view -> onOpenButtonClicked());
}
protected void setRecyclerView(){
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new TaskListAdapter(taskManager));
recyclerView.getAdapter().notifyItemInserted(taskManager.getTaskListCount() - 1);
}
protected void onOpenButtonClicked(){
Intent i = new Intent(this, TaskActivity.class);
startActivity(i);
}
protected void receiveIntent(){
String inputTask = getIntent().getStringExtra("EXTRA_SESSION_TASK");
Task task = new Task();
task.setName(inputTask);
taskManager.addTask(task);
}
}
My SecondActivity:
public class TaskActivity extends AppCompatActivity {
EditText etAddTask;
ImageView sendNewTask;
TaskManager taskManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_task);
taskManager = new TaskManager(this);
initViews();
initClickListener();
}
protected void initViews(){
etAddTask = findViewById(R.id.et_new_task);
sendNewTask = findViewById(R.id.send_new_task);
}
protected void initClickListener(){
sendNewTask.setOnClickListener(view -> onSendButtonClicked());
}
protected void onSendButtonClicked(){
String newTaskName = etAddTask.getText().toString();
Task task = new Task();
task.setName(newTaskName);
taskManager.addTask(task);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
And my RecyclerAdapter & TaskViewHolder:
public class TaskListAdapter extends RecyclerView.Adapter<TaskViewHolder> {
TaskManager taskManager;
public TaskListAdapter(TaskManager taskManager){
this.taskManager = taskManager;
}
#NonNull
#Override
public TaskViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new TaskViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.task_row, parent, false));
}
#Override
public void onBindViewHolder(#NonNull TaskViewHolder holder, int position) {
Task task = taskManager.getTaskList().get(position);
holder.newTask.setText(task.getName());
}
#Override
public int getItemCount() {
return taskManager.getTaskListCount();
}
}
public class TaskViewHolder extends RecyclerView.ViewHolder {
TextView newTask;
public TaskViewHolder(#NonNull View itemView) {
super(itemView);
newTask = itemView.findViewById(R.id.tv_new_task);
}
}
TaskManager:
public class TaskManager {
ArrayList<Task> taskList = new ArrayList<>();
public TaskManager(Context context){
Hawk.init(context).build();
loadTaskList();
}
public void addTask(Task task){
taskList.add(task);
saveTaskList();
}
public void removeTask(Task task){
taskList.remove(task);
saveTaskList();
}
public ArrayList<Task> getTaskList(){
return taskList;
}
public int getTaskListCount(){
return taskList.size();
}
protected void saveTaskList(){
Hawk.put("taskList", taskList);
}
protected void loadTaskList(){
Hawk.get("taskList", new ArrayList<>());
}
}
Adding a task using a AlertDialog
If you don't need a whole new activity to just add a new task, you can use an AlertDialog.
public class MainActivity extends AppCompatActivity {
// ...
protected void onOpenButtonClicked(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Here you can set the View you want, even a LinearLayout. In this
// case, I'm adding a text field so user can type the task name
final EditText edittext = new EditText(this);
builder.setTitle("Enter the task name");
builder.setView(edittext);
alert.setPositiveButton("ADD", (dialog, which) -> {
// When the user clicks the add button of the dialog, here will
// be the task name the user has typed, so just add it to the
// task manager of this activity
final String newTaskName = edittext.getText().toString();
});
alert.setNegativeButton("CANCEL", (dialog, which) -> {
// When the user clicks the cancel button of the dialog, just
// dismiss it without doing any action
dialog.dismiss();
});
alert.create().show();
}
// ...
}
Keeping the previous tasks passing a StringArrayList
If you do need a new activity, you can keep the previous tasks by using a ArrayList and passing this around.
Requesting a new task:
public class MainActivity extends AppCompatActivity {
// ...
protected void onOpenButtonClicked(){
final Intent i = new Intent(this, TaskActivity.class);
// Transform the task list to a string list
final List<String> taskNames = taskManager.getTaskList().stream()
.map(task -> task.name).collect(Collesctions.toList());
// Put it into the intent and start a new activity
i.putStringArrayListExtra("TASK_NAME_LIST", new ArrayList<>(taskNames));
startActivity(i);
}
// ...
}
Fetching a new task name:
public class TaskActivity extends AppCompatActivity {
// ...
ArrayList<String> taskNames;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// ...
final Intent i = getIntent();
// Receive the current task names
taskNames = getIntent().getStringArrayListExtra("TASK_NAME_LIST");
}
protected void onOpenButtonClicked() {
final String newTaskName = etAddTask.getText().toString();
// Add the new task name to the task names
taskNames.add(newTaskName);
// Send it back to the MainActivity
final Intent i = new Intent(this, MainActivity.class);
i.putStringArrayListExtra("TASK_NAME_LIST", taskNames);
startActivity(i);
finish();
}
// ...
}
Creating a new task:
public class MainActivity extends AppCompatActivity {
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
taskManager = new TaskManager(this);
final Intent i = getIntent();
if (i != null) {
// Receive the new task names
final List<String> taskNames = getIntent().getStringArrayListExtra("TASK_NAME_LIST");
for (String taskName : taskNames) {
final Task task = new Task();
task.setName(taskName);
taskManager.addTask(task);
}
}
}
// ...
}
NOTE: Even though in the previous example there are two separate MainActivity methods, you should include both.
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());
}
});
}
}
I would like to use interface to implement the communicate of passing data from fragments to activity's button which contains onClick event. I can see Map can write the data which is valid on editText field, but those values cannot be sent to activity. it shows error and stopped once I trigger the onClick event on activity.
The procedures are:
Users filled in the editText field
Once the editText field is out-focused, the TextWatcher with validation will check (If invalid, editText will not put into HashMap and hint user to edit, if user click submit button, it will reheat user change the correct answer at first)
When user filled all fields and click button, values on fragments will return as Hashmap, and checking it has null fields or not, and explode the values and putExtra() to next activity.
I was confused on the usage of the interface although I have read many sources and cases during troubleshooting this issue. Or May I use another solution to implement this function?
Thanks for any assistance.
Main activity:
......
Fragment_step_1 getHashMapStep1 = new Fragment_step_1();
Fragment_step_2 getHashMapStep2 = new Fragment_step_2();
public interface onPassValue{
public Map<Object, String> onPassValueStep1(Map<Object, String> insureApplicant);
}
public interface onPassValue2{
Map<Object, String> onPassValueStep2(Map<Object, String> insureApplicant2);
}
protected void onCreate(Bundle savedInstanceState) {
......
btn_sendInsureInfo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Fragment_step_1.onPassValueStep1();
Fragment_step_2.onPassValueStep2();
//NullPointerException on those two calling interface method
......
}
}
......
Fragment_step_1: (xxx is activity's name)
public class Fragment_step_1 extends Fragment implements xxx.onPassValue {
......
Map<Object, String> insureApplicant = new HashMap<>(4);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context xxx){
super.onAttach(xxx);
try {
passValue = (onPassValue) xxx;
} catch (ClassCastException e) {
throw new ClassCastException(pingan_insure_info.toString()
+ " didn't implement onPassValue");
}
//THROW EXCEPTION ALWAYS
}
#Override
public Map<Object, String> onPassValueStep1(Map<Object, String> insureResult) {
for (Object key : insureResult.entrySet()) {
//System.out.println(key + " fragment_1 : " + insureResult.get(key));
System.out.println(" fragment_1 : " + key);
Log.e("map", String.valueOf(insureResult));
}
return insureResult;
}
......
Fragment_step_2: (xxx is activity's name)
public class Fragment_step_2 extends Fragment implements xxx.onPassValue2{
......
RelativeLayout correspondence;
HashMap insureApplicant2 = new HashMap<>(3);
#Override
public void onAttach(Context xxx){
super.onAttach(xxx);
try {
passValueStep2 = (onPassValueStep2) xxx;
} catch (ClassCastException e) {
throw new ClassCastException(xxx.toString()
+ " didn't implement onPassValue");
}
//THROW EXCEPTION ALWAYS
}
#Override
public Map<Object, String> onPassValueStep2(Map<Object, String> insureApplicantStep2){
for (Object key : insureApplicantStep2.entrySet()) {
System.out.println("fragment_2 : " + key);
Log.e("Hashmap2", String.valueOf(insureApplicantStep2));
}
return insureApplicant2;
}
All fragments' editText will be filled after the editText is valid and typing by user and send to the function and stored in HashMap.
For example: (AddTextChangedListener with TextWatcher)
residentAddress.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
#Override
public void afterTextChanged(Editable editable) {
residentAddress.setOnFocusChangeListener(new View.OnFocusChangeListener(){
#Override
public void onFocusChange(View view, boolean isFocus){
if(!isFocus){
if("".trim().equals(residentAddress.getText().toString())){
rAddress.setError("Resident Address is required.");
strAddress = "";
insureApplicant2.put(2, strAddress);
} else {
rAddress.setErrorEnabled(false);
rAddress.setError(null);
strAddress = residentAddress.getText().toString().trim();
insureApplicant2.put(2, strAddress);
onPassValueStep2(insureApplicant2);
//CAN PUT THE VALUE TO HASHMAP BUT CANNOT be RETURNED TO ACTIVITY :(
}
}
}
});
}
});
To pass values from fragment to activity create interface in fragment.not in activity.
Fragment A
public class FragmentA extends Fragment {
public interface InterfaceTest{
void passValue(String passval);
}
InterfaceTest interfaceTest;
#Override
public void onAttach(Context context) {
super.onAttach(context);
interfaceTest= (InterfaceTest) context;
}
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_, container, false);
return rootView;
}
//
public void passToActivity(){
interfaceTest.passValue("yourvalues");
}
}
ACTIVITY
public class MainActivity extends AppCompatActivity implements FragmentA.InterfaceTest {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create code for add fragment in activity
}
#Override
public void passValue(String passval) {
Log.e("print",passval);
}
}
I'm using Android Studio to develop my app. I have two activities that does the same thing (except a parameter value) and I have an inner class inside which does the same thing too in the other activity. My inner class extends AsyncTask for background downloading. But, if I extend my second activity from my 1st activity, I can't do task.execute(), I will need to extend AyncTask too,and extending from two classes impossible in Java.. Here's my code :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private TextView title;
private List<User> myList;
String query_url;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recycler = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(llm);
//create and execute new task
AsyncDL task = new AsyncDL();
task.execute();
}
//background download
private class AsyncDL extends AsyncTask<Object, String, Integer> {
#Override
protected Integer doInBackground(Object... params) {
tryDownloadXmlData();
return null;
}
private void tryDownloadXmlData() {
try {
URL xmlUrl = new URL(query_url);
myXMLPullParser myCustomParser = new myXMLPullParser();
//fetch & parse data
myList = myCustomParser.parse(xmlUrl.openStream());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(Integer integer) {
myAdapter = new MyAdapter(getApplicationContext(), myList);
recycler.setAdapter(myAdapter);
RecyclerItemClickSupport.addTo(recycler).setOnItemClickListener(new RecyclerItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
User user = myList.get(position);
Intent myIntent = new Intent(getApplicationContext(), Details.class);
myIntent.putExtra("user", user);
startActivity(myIntent);
}
});
super.onPostExecute(integer);
}
}
}
I don't really know if it is possible to reuse an activity's code like that, thanks !
EDIT: new piece of code
ProductAsyncTask task = new ProductAsyncTask(getApplicationContext(), listview, QUERY_URL, productList, myCustomAdapter);
task.execute();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
User currentUser = myList.get(position); //error here
Intent myIntent = new Intent(getApplicationContext(), Detail_User.class);
myIntent.putExtra("currentUser", currentUser);
Log.i("INFO", "Loading extra data for transfer...");
startActivity(myIntent);
}
});