I've already searched and tried many ways on doing Intent like getActivity() / v.this / and my app still stop working when clicking this TextView to get to reserveReply class which only do simple ImageView.
---- MapFragment.class ------
#Override
public void onClick(View v) {
// I put the intent on the front of the codes just to test btw
Intent intent = new Intent(MapFragment.this, reserveReply.class);
startActivity(intent);
final String parkname = (String) v.getTag();
final String name = "Testing Test";
final String age = "21";
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("firstname",parkname);
parameters.put("lastname",name);
parameters.put("age",age);
return parameters;
}
};
requestQueue.add(request);
}
}
---- reserveReply.class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reservation_reply);
imgReply = (ImageView)findViewById(R.id.imgReply);
imgReply.setImageResource(R.drawable.waiting);
}
}
I also tried to implement View.onClickListener in fragment but it is not working. instead use setOnClickListener method directly and do your stuff... upvote if you like it...
public class FragmentView extends Fragment implements View.OnClickListener {
TextView newsTitle;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_layout, container, false);
newsTitle = (TextView) rootView.findViewById(R.id.news_title);
newsTitle.setOnClickListener(this);
return rootView;
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.news_title:
// code
break;
}
}
}
Related
I am making an app where I send data from one fragment to a dialog fragment
through a Bundle and pass that string with hash map and save that data to a database. When I send data from the fragment to the dialog fragment, it does not get there and I get the following error and my app crashes:
Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
Fragment code:
private void mobileNumber()
{
Bundle args = new Bundle();
args.putString("mobile", edtMobileNumber.getText().toString());
DialogFragment newFragment = new Save_contact_fragment();
newFragment.setArguments(args);
// newFragment.show(getFragmentManager(),"TAG");
}
In this code I am sending a mobile number to the dialog fragment. Dialog fragment code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TokenModel mTokenModel = ((BaseActivity)getActivity()).getTokenDetails();
if (mTokenModel != null) {
mAuthorizationHeader = mTokenModel.getTokenType() + " " + mTokenModel.getAccessToken();
}
Bundle args = this.getArguments();
data = args.getString("mobile");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_save_contact, container, false);
initUI(view);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
/*Bundle bundle = this.getArguments();
if (bundle == null) {
data = bundle.getString("mobile");
}*/
}
#Override
public void onDetach() {
super.onDetach();
}
private void initUI(View view) {
btnsave = (Button) view.findViewById(R.id.save);
btnCancelDialog = (Button) view.findViewById(R.id.btn_cancel);
etPromoCode = (EditText) view.findViewById(R.id.et_promo_code);
etPromoCode.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) {
if (charSequence.toString().length() > 0) {
btnsave.setEnabled(true);
} else {
btnsave.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
// Should always be at the end
bindClicks();
}
private void bindClicks() {
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callAddToContactAPI();
//Toast.makeText(getContext(), "save", Toast.LENGTH_SHORT).show();
//dismiss();
}
});
btnCancelDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
}
private void callAddToContactAPI() {
if (selectedPlan == null) {
selectedPlan = new SaveContactModel();
//selectedPlan.setRemark(Constants.CATEGORY_MOBILE_RECHARGE);
//Toast.makeText(getContext(), "1", Toast.LENGTH_SHORT).show();
}
//selectedPlan.setPlanMrp(Integer.parseInt(Utils.getTextFromEditText(etPromoCode)));
addToContactAPI(selectedPlan);
}
private void addToContactAPI(SaveContactModel saveContactModel) {
if (!Utils.isNetworkConnected(getActivity())) {
return;
}
CartClient cartClient = ServiceGenerator.createService(CartClient.class);
HashMap<String, Object> parameterMap = new HashMap<>();
parameterMap.put(Constants.ADD_ContactName,Utils.getTextFromEditText(etPromoCode));
parameterMap.put(Constants.ADD_ContactNumber,data);
parameterMap.put(Constants.ADD_ServiceID_TO_SAVE, 1);
parameterMap.put(Constants.ADD_UserBasicID,"1593");
Call<String> cart = cartClient.addToContact(mAuthorizationHeader, parameterMap);
//Toast.makeText(getContext(), "2", Toast.LENGTH_SHORT).show();
String abc = cart.request().url().toString();
cart.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.code() == 200) {
Intent intent = new Intent(getContext(), MyContactActivity.class);
startActivity(intent);
Utils.showAlertDialogWithMessage(Constants.CONTACT_ADDED, getActivity());
// Utils.showAlertDialogWithMessage(Constants.SUCCESS_MESSAGE_ITEM_ADDED_TO_CART, getActivity());
} else {
// Utils.showAlertDialogWithMessage(Constants.ERROR_UNABLE_TO_PROCESS_REQUEST, getActivity());
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Utils.showShortToastMessage(getActivity(), Constants.ERROR_OOPS_SOMETHING_WENT_WRONG);
}
});
}
Here is where I receive data in the dialog fragment:
Bundle args = this.getArguments();
data = args.getString("mobile");
But I get null and get an error when I pass that data string to a hash map. I do that in the following code:
HashMap<String, Object> parameterMap = new HashMap<>();
parameterMap.put(Constants.ADD_ContactName,Utils.getTextFromEditText(etPromoCode));
parameterMap.put(Constants.ADD_ContactNumber,data);
parameterMap.put(Constants.ADD_ServiceID_TO_SAVE, 1);
parameterMap.put(Constants.ADD_UserBasicID,"1593");
The mobile number is not there in the bundle.
put this part:
Bundle args = getArguments();
data = args.getString("mobile");
in onCreateView instead of onCreate and without this.
You can get your passed argument in onViewCreated or into onCreateView method. If you don't receive bundle, a default string will be used if arguments are different than null.
String mobile = getArguments() != null ? getArguments().getString("mobile", "defaultString") : "defaultString";
In Activity, i called web service and getting json response. Now i need to send this json response in one of the fragment of Activity. Please anyone help me how to send the json response to fragment without null value.
Thank you in advance.
public class Gifts_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refereal_activtiy);
onSucceeded();
}
private void onSucceeded() {
ServiceClient serviceClient = ServiceUtil.getServiceClient();
JsonObject json = new JsonObject();
json.addProperty("user_id", "353");
json.addProperty("device_id", "433");
serviceClient.movie_quiz(json, callback);
}
Callback<JsonObject> callback = new Callback<JsonObject>() {
#Override
public void success(final JsonObject jsonObject, Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
///here i am getting response. i need this response in fragment .
}
});
}
#Override
public void failure(RetrofitError error) {
}
};
}
fragement:
public class Electronics_fragment extends Fragment {
Refeeral_Fragemnt.ShareAdapter adapter;
LinearLayout lay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
lay = (LinearLayout) inflater.inflate(R.layout.referralhistory, container, false);
return lay;
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//here i am getting response. i need this response in fragment .-->
//then here you can store(set) your json response value in SharedPreferences, please define SharedPreferences method globally
//and after when you call fragment retrieve(get) SharedPreferences Method in your Fragment.
}
});
I have an activity(RecoveryActivity) which has a fragment(RecoveryFragment). A button click calls this activity in which RecoveryFragment is shown. I just want to directly call RecoveryFragment as an activity. How to convert this fragment into an activity. Noob here ! Any help would be deeply appreciated.
RecoveryActivity
public class RecoveryActivity extends ActivityBase {
private static final String TAG = "password_recovery_activity";
Toolbar mToolbar;
Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recovery);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (savedInstanceState != null) {
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "currentFragment");
} else {
fragment = new RecoveryFragment();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container_body, fragment).commit();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "currentFragment", fragment);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fragment.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed(){
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home: {
finish();
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}}}
RecoveryFragment
public class RecoveryFragment extends Fragment implements Constants {
private ProgressDialog pDialog;
Button mContinueBtn;
EditText mEmail;
String email;
private Boolean loading = false;
public RecoveryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
initpDialog();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recovery, container, false);
if (loading) {
showpDialog();
}
mEmail = (EditText) rootView.findViewById(R.id.PasswordRecoveryEmail);
mContinueBtn = (Button) rootView.findViewById(R.id.PasswordRecoveryBtn);
mContinueBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = mEmail.getText().toString();
if (!App.getInstance().isConnected()) {
Toast.makeText(getActivity(), R.string.msg_network_error, Toast.LENGTH_SHORT).show();
} else {
Helper helper = new Helper();
if (helper.isValidEmail(email)) {
recovery();
} else {
Toast.makeText(getActivity(), getText(R.string.error_email), Toast.LENGTH_SHORT).show();
}
}
}
});
// Inflate the layout for this fragment
return rootView;
}
public void onDestroyView() {
super.onDestroyView();
hidepDialog();
}
protected void initpDialog() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(getString(R.string.msg_loading));
pDialog.setCancelable(false);
}
protected void showpDialog() {
if (!pDialog.isShowing()) pDialog.show();
}
protected void hidepDialog() {
if (pDialog.isShowing()) pDialog.dismiss();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
public void recovery() {
loading = true;
showpDialog();
CustomRequest jsonReq = new CustomRequest(Request.Method.POST, METHOD_ACCOUNT_RECOVERY, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (!response.getBoolean("error")) {
Toast.makeText(getActivity(), getText(R.string.msg_password_reset_link_sent), Toast.LENGTH_SHORT).show();
getActivity().finish();
} else {
Toast.makeText(getActivity(), getText(R.string.msg_no_such_user_in_bd), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} finally {
loading = false;
hidepDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading = false;
hidepDialog();
Toast.makeText(getActivity(), getText(R.string.error_data_loading), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("clientId", CLIENT_ID);
params.put("email", email);
return params;
}
};
App.getInstance().addToRequestQueue(jsonReq);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}}
You start by extending AppCompatActivity instead of Fragment
public class RecoveryActivity extends AppCompatActivity (this is your fragment but I renamed it RecoveryActivity. You shouldn't cause you'd have 2 activities with the same name.Let's say it's called RecoveryActivityNew. The instructions below are not for what you named as RecoveryActivity but for the RecoveryFragment piece of code.
Then you remove the methods such as onAttach() and onDetach() which are only relevant to a fragment. Get rid of onDestroyView. Remove onCreateView() and all the code that is in there, put it in onCreate()
Now because you don't have a fragment, you reference a view like this:
mContinueBtn = (Button) findViewById(R.id.PasswordRecoveryBtn);
Just like you referenced the toolbar in the activity (you lose the rootView).
Also, in displaying the Toast for example, you don't use the getActivity() method but use this or RecoveryActivity.this:
Toast.makeText(RecoveryActivity.this, R.string.msg_network_error, Toast.LENGTH_SHORT).show();
Get rid of the constructor public RecoveryFragment()
And don't forget to declare your new activity in the app's Manifest file.
<activity
android:name=".RecoveryActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="com.your.packagename.RecoveryActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I'm Using viewpager with 2 swiping tab layouts. In the first tablayout I post data to the server and when I switch the tab the Listview in not update. Only when I click on Listview Item and close it the Listview gets refreshed and the posted data is visible...
Question Is : How to automatically refresh Listview when data is posted to server can some one help please.
public class PagerAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PagerAdapter(FragmentManager fm,int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
RaiseComplaintFragment RFragment=new RaiseComplaintFragment();
return RFragment;
case 1:
ComplaintListFragment CFragment=new ComplaintListFragment();
return CFragment;
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
This is the method which posts data to the server
public void postDataToServer(String complaintdata) throws JSONException {
String url = URLMap.getPostComplaintUrl();
String roleId = LoggedInUserStore.getLoggedInRoleId(getContext());
String branchId = LoggedInUserStore.getLoggedInBranchId(getContext());
String compid = LoggedInUserStore.getLoggedInCompanyId(getContext());
HashMap<String, String> params = new HashMap<>();
params.put("CallRecordID", "0"); //pass 0 if we are inserting a new record always
params.put("CompanyID", compid);
params.put("BranchID", branchId);
params.put("ServiceID", sId);
params.put("CallLocationID", lId);
params.put("RaisedByID", roleId);
params.put("ComplaintDetails", complaintdata);
params.put("CallStatusID", "1");
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait..");
pDialog.setProgressStyle(pDialog.STYLE_SPINNER);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Complaint has been registered successfully");
builder.setMessage("").setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
_complaintText.setText("");
serviceSpinner.setSelection(0);
locationSpinner.setSelection(0);
pDialog.dismiss();
/*((HomeActivity)getActivity()).getViewPager().setCurrentItem(1); //onCLick of Submit it just switches the tab
String tagName="android:switcher:"+R.id.pager+":"+1;
ComplaintListFragment f2=(ComplaintListFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
f2.fetchComplaintData();*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Unable to register your request.\nPlease try later.");
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
pDialog.dismiss();
}
});
req.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue requestQueue = ((VolleyRequestQueue) getActivity().getApplication()).getRequestQueue();
requestQueue.add(req);
}
My HomeActivity class which handles two tab layouts
viewPager = (ViewPager) findViewById(R.id.view_Pager);
tabLayout = (TabLayout) findViewById(R.id.tab_Layout);
String roleID = LoggedInUserStore.getLoggedInRoleId(getApplicationContext());
if (roleID.equals("4")) {
//RAISE COMPLAINT UI. IF ROLE ID == 4 MANAGER DASHBOARD
tabLayout.addTab(tabLayout.newTab().setText("Raise Complaint"));
tabLayout.addTab(tabLayout.newTab().setText("Complaint List"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final PagerAdapter adapter =
new com.six30labs.cms.adapters.PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Second fragment which contains my listview
public class ComplaintListFragment extends Fragment {
private ListView complaintListView;
EditText _inputSearch;
ComplaintAdapter compadapter;
private static Parcelable mListViewScrollPos = null;
private RequestQueue mQueue;
ProgressBar progressBar;
String URL;
private View v;
String TAG="Second Fragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_complaint_list, container, false);
complaintListView = (ListView) v.findViewById(R.id.complaintListView);
_inputSearch = (EditText) v.findViewById(R.id.inputSearchforComplaintListFragment);
progressBar = (ProgressBar) v.findViewById(R.id.complaintListProgressBar);
fetchComplaintData();
_inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
compadapter.getFilter().filter(s.toString());
compadapter.notifyDataSetChanged();
}catch (NullPointerException e){
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (mListViewScrollPos != null) {
complaintListView.onRestoreInstanceState(mListViewScrollPos);
}
return v;
}
public void fetchComplaintData() {
progressBar.setVisibility(View.VISIBLE);
URL = URLMap.getComplaintUrl("complaint_url");
URL = URL.replace("{id}", LoggedInUserStore.getLoggedInCompanyId(getContext()));
StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
getCompliantList(response);
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue queue=((VolleyRequestQueue)getActivity().getApplication()).getRequestQueue();
queue.add(request);
/* RequestQueue requestQueue
= Volley.newRequestQueue(getContext());
requestQueue.add(request);*/
}
public void getCompliantList(String response) {
try {
List complaint = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
// complaint.add(Complaint.fromJson(jArray.getJSONObject(i)));
complaint.add(0,Complaint.fromJson(jArray.getJSONObject(i))); //To push the data to the top of the listview.
}
compadapter = new ComplaintAdapter(getContext(), complaint);
complaintListView.setAdapter(compadapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Method that will save the position the user when they scroll
//return it when the user comes back to the listView instead of it refreshing the data.
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mListViewScrollPos = complaintListView.onSaveInstanceState();
}
public void onPause() {
super.onPause();
}
public void onResume() {
super.onResume();
fetchComplaintData();
}
BroadcastReceiver For class Where your Listview is
private BroadcastReceiver updateProfileBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fire your event
}
};
Register Broadcast in onResume()
registerReceiver(updateProfileBroadcast, new IntentFilter("KEY"));
Now fire Broadcast From Fragment
Intent intent = new Intent("KEY");
getActivity().sendBroadcast(intent);
As an alternative to SID's answer you may use EventBus. It works by event-driven architecture and able to transfer information between components really easy and fast.
That's how you use it:
1) add to project in app gradle: compile 'org.greenrobot:eventbus:3.0.0'
2) Register EventBus in fragment's onCreate() where you need to update ListView: eventBus.register(this);. And don't forget to unregister it on onDestryView(): eventBus.unregister(this);
3) Add the method to your ListView fragment which will handle event with list update:
#SupressWarning("unused")
#Subscribe
public void onEvent(List<YourListViewData> event) {/* update `ListView` */};
4) Fire that event from activity\fragment when you need to update ListView:
EventBus bus = EventBus.getInstance();
eventBus.post(List<YourListViewData> yourData);
I created a voteUp method as follows,
public class Voting {
public void onUpVote(View view) {
CharSequence VoteUpId = ((TextView) ((RelativeLayout) view.getParent()).getChildAt(1)).getText();
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "URL + VoteUpId + URL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
}
This method takes a view object, and I also have another method as shown below in another class where I set an onClickListner
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
VoteClass(What Do I pass In here??);
}
});
And I want to pass in a child of the view that is different from the button view from the same layout, and no I do not want to use the direct onClick from the xml layout to the class. So how do i do this?
implement the View.OnClickListener class and pass the view as argument like this
class CustomClickListener implements View.OnClickListener{
View view;
public CustomClickListener(View view){
this.view = view;
}
#Override
public void onClick(View v) {
VoteClass(view);
}
}
and then
mButton.setOnClickListener(new CustomClickListener(the view you want to pass));