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);
Related
I always use the approach to show the data in recyclerview using Volley is to create Adapter in Oncreate method and then notify after receiving response from volley using notifyDataSetChanged.
I tried to use the same approach in Retrofit but data is not showing in Recyclerview,but if instead of setting adapter in Oncreate method if I set Adapter in retrofit after receiving response from Retrofit then it works perfectly
My question is that
(1) why the data is not showing in Retrofit if i create adapter in Oncreate am i doing something wrong?
(2)Is it a good approach to create adapter in Oncreate and then notifying it after receiving response or shoud I set adapter after getting response?
If I set adapter after getting response like this
#Override
public void onResponse(Call<SubCatModelList> call, Response<SubCatModelList> response) {
Log.d("subcategoryJsonResponse", String.valueOf(response));
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Log.d("aaaaaa", String.valueOf(successResponse));
if (response.isSuccessful()) {
subCatModel =response.body().getSubCategories();
Log.d("asaaaaaaa", String.valueOf(subCatModel));
subCategoryAdapter = new SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
FixedGridLayoutManager manager = new FixedGridLayoutManager();
manager.setTotalColumnCount(1);
rvBinaryCommission.setLayoutManager(manager);
rvBinaryCommission.setAdapter(subCategoryAdapter);
rvBinaryCommission.addItemDecoration(new DividerItemDecoration(BinaryCommissionActivity.this, DividerItemDecoration.VERTICAL));
}
then every time this line initializes adapter and creates object whenver api hits and i think its a bad approach
subCategoryAdapter = new
SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
public class BinaryCommissionActivity extends AppCompatActivity {
int scrollX = 0;
List<SubCatModel> subCatModel = new ArrayList<>();
SubCategoryAdapter subCategoryAdapter;
VolleyCustomClass volleyCustomClass;
#BindView(R.id.toolbarcustom) Toolbar toolbarcustom;
#BindView(R.id.spinner_binary_commission) Spinner spinnerBinaryCommission;
#BindView(R.id.searchViewBinary) SearchView searchViewBinary;
#BindView(R.id.headerScroll) HorizontalScrollView headerScroll;
#BindView(R.id.rvBinaryCommission) RecyclerView rvBinaryCommission;
#BindView(R.id.swipeRefreshBinaryList) SwipeRefreshLayout swipeRefreshBinaryList;
private AlertDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_commission);
ButterKnife.bind(this);
toolbarcustom = findViewById(R.id.toolbarcustom);
setSupportActionBar(toolbarcustom);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Binary Commission");
volleyCustomClass = new VolleyCustomClass(getApplicationContext());
dialog = new SpotsDialog.Builder().setContext(this)
.setMessage("Loading...")
.setCancelable(false).build();
spinnerData();
setUpRecyclerView();
prepareClubData();
recyclerviewScrollListener();
searchFilter();
swipeRefreshBinaryList.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (!InternetUtils.checkForInternet(getApplicationContext())) {
swipeRefreshBinaryList.setRefreshing(false);
FancyToast.makeText(getApplicationContext(), "No Internet Connection", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
} else {
prepareClubData();
}
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
/**
* Recyclerview ScrollListener
*/
private void recyclerviewScrollListener() {
rvBinaryCommission.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
scrollX += dx;
headerScroll.scrollTo(scrollX, 0);
}
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
});
}
/**
* Search Filter
*/
private void searchFilter() {
searchViewBinary.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
subCategoryAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
subCategoryAdapter.getFilter().filter(newText);
return false;
}
});
}
/**
* Adding data to spinner
*/
private void spinnerData() {
List<String> show_entries = new ArrayList<String>();
show_entries.add("5");
show_entries.add("10");
show_entries.add("15");
show_entries.add("20");
show_entries.add("All");
ArrayAdapter<String> dataAdapterShowEntries = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, show_entries);
dataAdapterShowEntries.setDropDownViewResource(R.layout.layout_spinner_item);
spinnerBinaryCommission.setAdapter(dataAdapterShowEntries);
spinnerBinaryCommission.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Object item = adapterView.getItemAtPosition(position);
if (item != null) {
// Toast.makeText(getContext(), item.toString(), Toast.LENGTH_SHORT).show();
}
// Toast.makeText(getContext(), "Selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// TODO Auto-generated method stub
}
});
}
private void prepareClubData() {
if (!InternetUtils.checkForInternet(getApplicationContext())) {
FancyToast.makeText(getApplicationContext(), "No Internet Connection", FancyToast.LENGTH_LONG, FancyToast.ERROR, false).show();
return;
} else {
dialog.show();
if (subCatModel != null) {
subCatModel.clear();
}
/**
* Volley
*/
/* volleyCustomClass.callGetServer(URLs.subcategoryURL, new VolleyCallback() {
#Override
public void onSuccess(String response) {
Log.d("subcategoryJsonResponse", response);
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCatModel subCatModelClass = new SubCatModel();
subCatModelClass.setSubcategoriesId(productObject.getString("Subcategories-Id"));
subCatModelClass.setCategoriesId(productObject.getString("categories-Id"));
subCatModelClass.setSubcategoriesName(productObject.getString("Subcategories-Name"));
subCatModel.add(subCatModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCatModel));
}
dialog.dismiss();
subCategoryAdapter.notifyDataSetChanged();
swipeRefreshBinaryList.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
dialog.dismiss();
}
}
#Override
public void onError(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
swipeRefreshBinaryList.setRefreshing(false);
}
});*/
/**
* Retrofit
*/
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<SubCatModelList> call = apiService.getList();
call.enqueue(new Callback<SubCatModelList>() {
#Override
public void onResponse(Call<SubCatModelList> call, Response<SubCatModelList> response) {
Log.d("subcategoryJsonResponse", String.valueOf(response));
Gson gson = new Gson();
String successResponse = gson.toJson(response.body());
Log.d("aaaaaa", String.valueOf(successResponse));
if (response.isSuccessful()) {
subCatModel =response.body().getSubCategories();
Log.d("asaaaaaaa", String.valueOf(subCatModel));
}
dialog.dismiss();
subCategoryAdapter.notifyDataSetChanged();
swipeRefreshBinaryList.setRefreshing(false);
}
#Override
public void onFailure(Call<SubCatModelList> call, Throwable t) {
swipeRefreshBinaryList.setRefreshing(false);
}
});
}
}
/**
* Handles RecyclerView for the action
*/
private void setUpRecyclerView() {
subCategoryAdapter = new SubCategoryAdapter(BinaryCommissionActivity.this, subCatModel);
FixedGridLayoutManager manager = new FixedGridLayoutManager();
manager.setTotalColumnCount(1);
rvBinaryCommission.setLayoutManager(manager);
rvBinaryCommission.setAdapter(subCategoryAdapter);
rvBinaryCommission.addItemDecoration(new DividerItemDecoration(BinaryCommissionActivity.this, DividerItemDecoration.VERTICAL));
}
}
Instead of initializing adapter everytime, you can use: (inside adapter class)
public void setItems(List<String> myList) { // Let's say it's List of Strings
this.myList = myList;
notifyDataSetChanged();
}
And everytime you change List with your data to display (in your case inside of onResponse()) you just call 'setItems()' on your adapter.
I am trying to update viewpager fregment when viewpager swipe in MainActivity.
MenuActivity:-
package jbit.kanha;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.romainpiel.shimmer.Shimmer;
import com.romainpiel.shimmer.ShimmerTextView;
import org.json.JSONArray;
import org.json.JSONObject;
import jbit.kanha.AllAdepters.SideMenuAdapter;
import jbit.kanha.InternetConection.CheckInternetConection;
import jbit.kanha.InternetConection.ConnectionDetector;
import jbit.kanha.InternetConection.InternetDialoge;
import jbit.kanha.ProgressDialog.MyProgressDialog;
import jbit.kanha.SideMenuClasses.MyProfile;
import jbit.kanha.db.Database;
public class MenuActivity extends FragmentActivity implements View.OnClickListener{
public static ResideMenu resideMenu;
private MenuActivity mContext;
private ResideMenuItem itemHome;
private ResideMenuItem itemProfile;
private ResideMenuItem itemCalendar;
private ResideMenuItem itemSettings;
SharedPreferences loginPreferences;
private SharedPreferences pref;
ImageView profile_image;
public static TextView title_bar_right_menu,txt_total_rate;
Database database;
JSONArray categoryItem;
// private PagerSlidingTabStrip tabLayout;
private TabLayout tabLayout;
ViewPager pager;
private ConnectionDetector connectionDetector;
private MyProgressDialog dialog;
ViewPagerAdapter adapter;
OneFregment fregment;
// private int currentColor = Color.parseColor("#1D569B");
// PagerSlidingTabStrip tabStrip;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
database = new Database(MenuActivity.this);
tabLayout= (TabLayout)findViewById(R.id.tabs);
pager = (ViewPager)findViewById(R.id.pager);
loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
connectionDetector = new ConnectionDetector(mContext);
dialog = new MyProgressDialog(mContext);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
if (connectionDetector.isConnectingToInternet()){
getCategoryName();
}else{
Toast.makeText(mContext, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
title_bar_right_menu = (TextView) findViewById(R.id.title_bar_right_menu);
txt_total_rate = (TextView) findViewById(R.id.txt_total_rate);
pref = getApplicationContext().getSharedPreferences("loginPrefs", MODE_PRIVATE);
Cursor cursor1 = database.getData("SELECT * FROM cart");
int count = cursor1.getCount();
cursor1.close();
title_bar_right_menu.setText(count+"");
setUpMenu();
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
getCategoryDataRefresh(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void getCategoryData(final int postion){
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php")
.setTimeout(30*1000)
.setBodyParameter("outlet_id",loginPreferences.getString("outlet_id",""))
.setBodyParameter("catid",String.valueOf(postion+1))
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
JSONArray jsonArray = mainJson.getJSONArray("data");
setUpViewPager(pager,categoryItem,jsonArray);
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());
}
} else {
Log.d("exaption", e.toString());
}
}
});
}
private void getCategoryDataRefresh(final int postion){
dialog.show();
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryoriginal.php")
.setTimeout(30*1000)
.setBodyParameter("outlet_id",loginPreferences.getString("outlet_id",""))
.setBodyParameter("catid",String.valueOf(postion+1))
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwoData(mContext, "Connection Timed Out!", "Message...",postion).show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
Fragment frg = null;
frg = new OneFregment(mainJson.getJSONArray("data"));
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());
}
} else {
Log.d("exaption", e.toString());
}
}
});
}
private void getCategoryName(){
dialog.show();
Ion.with(mContext)
.load(getResources().getString(R.string.api_main_url) + "categoryname.php")
.setTimeout(30*1000)
.asString().setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
// dialog.hide();
if (e != null) {
e.printStackTrace();
DialogsClassTwo(mContext, "Connection Timed Out!", "Message...").show();
}
if (result != null) {
try {
Log.d("name",result);
JSONObject mainJson = new JSONObject(result);
String status = mainJson.getString("status");
if(status.equals("Success")){
JSONObject jsonObject = mainJson.getJSONObject("data");
categoryItem = jsonObject.getJSONArray("items");
// setUpViewPager(pager,jsonObject.getJSONArray("items"));
Log.d("json",jsonObject+"");
getCategoryData(0);
//data = jsonObject.getJSONArray("items");
/* for(int i=0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
bigImage.add(jsonObject1.getString("bigimage"));
}
pager.setAdapter(new CustomPagerAdapter(getActivity(),data));
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
changeColor(currentColor);*/
}
}catch (Exception ex) {
ex.printStackTrace();
Log.d("exaption", ex.toString());
}
} else {
Log.d("exaption", e.toString());
}
}
});
}
private void setUpViewPager(ViewPager pager, JSONArray jsonArray,JSONArray products){
try {
// ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
adapter.addFrag(new OneFregment(products),jsonObject.getString("categoryname"));
}
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
// tabLayout.tabSelectedTextColor
// getCategoryData();
}
catch (Exception e) {
Log.e("error", e.getMessage());
}
}
public AlertDialog.Builder DialogsClassTwo(Context cxt, final String message, String title){
return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogs, int which) {
// here you can add functions
if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){
getCategoryName();
// getCategoryData();
}else{
InternetDialoge.showDialogFinishActivity(
"Internet Connection Failed!", "connection error", mContext);
}
}
});
}
public AlertDialog.Builder DialogsClassTwoData(Context cxt, final String message, String title, final int postion){
return new AlertDialog.Builder(cxt).setTitle(title).setMessage(message).setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogs, int which) {
// here you can add functions
if (CheckInternetConection.isInternetConnection(mContext.getApplicationContext())){
//getCategoryName();
getCategoryData(postion);
}else{
InternetDialoge.showDialogFinishActivity(
"Internet Connection Failed!", "connection error", mContext);
}
}
});
}
private void setUpMenu() {
resideMenu = new ResideMenu(MenuActivity.this, R.layout.side_menu, R.layout.home);
//resideMenu.setBackground(Color.parseColor("#FAA514"));//FAA514
resideMenu.setBackground(R.drawable.slider_background);
resideMenu.attachToActivity(MenuActivity.this);
resideMenu.setScaleValue(0.5f);
View leftMenu = resideMenu.getLeftMenuView();
Shimmer shimmer = new Shimmer();//#faebd7
shimmer.setDuration(3000)
.setStartDelay(500)
.setDirection(Shimmer.ANIMATION_DIRECTION_LTR);
ShimmerTextView powered = (ShimmerTextView)leftMenu.findViewById(R.id.powered);
ListView list = (ListView) leftMenu.findViewById(R.id.list1);
list.setAdapter(new SideMenuAdapter(MenuActivity.this));
profile_image = (ImageView) leftMenu.findViewById(R.id.profile_image);
TextView title1 = (TextView) leftMenu.findViewById(R.id.title1);
TextView loction1 = (TextView) leftMenu.findViewById(R.id.loction1);
ImageView location_icon =(ImageView) leftMenu.findViewById(R.id.location_icon);
RelativeLayout ll_checkout = (RelativeLayout) findViewById(R.id.ll_checkout);
//loginPreferences = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
title1.setText(loginPreferences.getString("fullname",""));
loction1.setText(loginPreferences.getString("address",""));
// if(!loginPreferences.getString("profileimage","").equals("")){
/* Picasso.with(MenuActivity.this)
.load(loginPreferences.getString("profileimage",""))
.error(R.drawable.images)
.placeholder(R.drawable.progress_animation)
.into(profile_image);*/
// File file = new File("/main_json/main_json/com.example.w.lazymojo/app_imageDir/profile.jpg");
shimmer.start(powered);
if(pref.getString("User_id", "").equals("")){
profile_image.setImageResource(R.drawable.images);
location_icon.setVisibility(View.INVISIBLE);
}
else {
Bitmap bitmap1 = BitmapFactory.decodeFile("/data/data/jbit.kanha/app_imageDir/profile.jpg");
if(bitmap1!=null){
Log.d("MenuActivity:-","image not null");
profile_image.setImageBitmap(bitmap1);
// Picasso.with(MenuActivity.this).load(file).resize(dpToPx(96),dpToPx(96)).centerCrop().into(profile_image);
}
else {
Log.d("MenuActivity:-","image is null");
profile_image.setImageResource(R.drawable.images);
}
}
profile_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(pref.getString("User_id", "").equals("")){
profile_image.setImageResource(R.drawable.images);
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You have to login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(in);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
else {
Intent i = new Intent(MenuActivity.this, MyProfile.class);
startActivity(i);
}
}
});
// }
ll_checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!pref.getString("User_id", "").equals("")){
Intent i = new Intent(MenuActivity.this,MyCart.class);
startActivity(i);
finish();
}
else
{
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(intent);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
});
resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);
resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_LEFT);
findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
}
});
findViewById(R.id.cart_img).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!pref.getString("User_id", "").equals("")){
Intent i = new Intent(MenuActivity.this,MyCart.class);
startActivity(i);
finish();
}
else
{
new AlertDialog.Builder(MenuActivity.this).setTitle("Login").setMessage("You must login first").setPositiveButton("Login", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MenuActivity.this,LoginActivity.class);
startActivity(intent);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
// resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
}
});
}
#Override
public void onClick(View view) {
resideMenu.closeMenu();
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
#Override
public void openMenu() {
// Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}
#Override
public void closeMenu() {
//Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};
// What good method is to access resideMenu?
public ResideMenu getResideMenu(){
return resideMenu;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
moveTaskToBack(true);
}
}
ViewPagerAdapter.java:
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
OneFregement:-
public class OneFregment extends Fragment {
JSONArray jsonArray;
ListView listView;
HomeLiatAdapter adapter;
public OneFregment() {
// Required empty public constructor
}
#SuppressLint("ValidFragment")
public OneFregment(JSONArray jsonArray){
this.jsonArray = jsonArray;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_child_layout, container, false);
listView = (ListView) v.findViewById(R.id.list);
try {
JSONObject obj = jsonArray.getJSONObject(0);
adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage"));
listView.setAdapter(adapter);
}catch (Exception e){
e.printStackTrace();
}
return v;
}
/* public void update(){
try {
JSONObject obj = jsonArray.getJSONObject(0);
adapter = new HomeLiatAdapter(getContext(),obj.getJSONArray("items"),obj.getString("bigimage"));
listView.setAdapter(adapter);
}catch (Exception e){
e.printStackTrace();
}
}*/
}
I am do this but fregment is show previous data.I also try create update method in fregment class but all is wain.
I am new in Android Developing please help me. Thanks in advance.
you will have to write custom interface and implement in each fragment. And on onpagechangelistener you will have to call those method.
check this for more explanation. even i had to implement same for my project to get the fragments updated as normal fragment life-cycle wont work as you want. due to view pager adding and retaining of fragment as you swipe through.
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'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;
}
}
}
I did a quick search in here and didn't find any answers for my qustion, if its already answered please point me to that question ..
I have an ActionBar Tabs with swipe views implemented according to this android training. My activity have 3 tabs
Weather Comment Dashboard
and these fragments
WeatherFragment CommentsFragment LoginFragment DasboardFragment RegisterFragment
As the activity is started,
Weather Tab displays WeatherFragment ,
Comments Tab displays CommentsFragment and
Dashboard Tab displays LoginFragment
If Login is successful in LoginFragment, DasboardFragment should replace the LoginFragment inside the Dashboard Tab. So if user swipes to other tabs and come back to Dashboard Tab DasboardFragment should be visible.
I'm new to android development, so any code snippets or tutorial would be greatly appreciated
Code i've so far MainActivity class
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_network_weather);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
//actionBar.setDisplayShowTitleEnabled(false);
//actionBar.setDisplayShowHomeEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new WeatherInfoFragment();
case 1:
return new PostsFragment();
default: //TODO method to find which fragment to display ?
return new LoginFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Weather";
} else if (position == 1){
return "Comments";
}
else{
return "Dashboard";
}
}
}
#Override
public void onTabReselected(ActionBar.Tab tab,
android.app.FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}
}
LoginFragment
public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
loginButton = (Button) getView().findViewById(R.id.button_login);
loginError = (TextView) getView().findViewById(R.id.login_error);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin(finalLoginUrl);
// attemptPost(postURL);
}
});
}
private void attemptLogin(String url) {
try {
task = new JSONfunctions(getActivity());
task.listener = this;
task.execute(new String[] { url });
} catch (Exception ex) {
Log.e("attempt login", ex.getMessage());
}
}
}
#Override
public void processFinish(String result) {
try {
jsonObject = new JSONObject(result);
int success = Integer.parseInt(jsonObject.getString("Success"));
if (success == 0) {
// Replace LoginFragment and launch DashboardFragment ?
} else {
loginError.setText(jsonObject.getString("ErrorMessage"));
}
} catch (JSONException e) {
Log.e("JSON parsing from login result", e.getMessage());
}
}
}
I'm not sure this is the best way to handle this but you could define a static boolean inside your MainActivity like so:
public static boolean loggedIn = false;
(e.g. below ViewPager mViewPager;)
And then, in your method processFinish(...) inside the LoginFragment when success is 0 just set MainActivity.loggedIn = true;
This way you can simply put in an if-statement inside your default-case in getItem-method to check whether the user is logged in (if so call the Dashboard-Fragment) or not (display Login-Fragment).
Hope this works for you!
Edit: LoginFragment
public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
loginButton = (Button) getView().findViewById(R.id.button_login);
loginError = (TextView) getView().findViewById(R.id.login_error);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin(finalLoginUrl);
// attemptPost(postURL);
}
});
}
private void attemptLogin(String url) {
try {
task = new JSONfunctions(getActivity());
task.listener = this;
task.execute(new String[] { url });
} catch (Exception ex) {
Log.e("attempt login", ex.getMessage());
}
}
#Override
public void processFinish(String result) {
try {
jsonObject = new JSONObject(result);
int success = Integer.parseInt(jsonObject.getString("Success"));
if (success == 0) {
MainActivity.loggedIn = true;
} else {
loginError.setText(jsonObject.getString("ErrorMessage"));
}
} catch (JSONException e) {
Log.e("JSON parsing from login result", e.getMessage());
}
}
}
Was my own fault for not reading the answer here thoroughly. Implemented the code from that answer and got the functionality working :)