hey guys i'm sufferening to problem how to call tab fragments inside fragment.i am always click on button show unfortunately app closed and in logcat show nullpointer exception.i implemented but gettting errror null object reference
Lead_Fragment Main fragment
in which define the code add all tabs in toolbar and show the view of mainfragment
in which define the code add all tabs in toolbar and show the view of mainfragment
in which define the code add all tabs in toolbar and show the view of mainfragment
package com.example.dashboard;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.admin.bdayevent.R;
public class Lead_Fragment extends Fragment implements TabLayout.OnTabSelectedListener,Frgmentchangelistener {
private TabLayout tabLayout;
private ViewPager viewPager;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_lead_fragment, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.leadtabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Step1"));
tabLayout.addTab(tabLayout.newTab().setText("Step2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager)view.findViewById(R.id.leadmain_container);
//Creating our pager adapter
Lead_Pager adapter = new Lead_Pager(getFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(this);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state)
{
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
}
});
Lead_step1 fragment1 = new Lead_step1();
FragmentManager fragmentManager =getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.leadmain_container, fragment1);
// fragmentTransaction.hide(Step1.this);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return view;
}
public void onTabSelected(TabLayout.Tab tab)
{
viewPager.setCurrentItem(tab.getPosition());
// Toast.makeText(getApplicationContext(),"tab selected "+tab.getPosition(),Toast.LENGTH_SHORT).show();
}
// public void replaceFragment(Fragment fragment, boolean addToBackStack) {
// FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
// if (addToBackStack)
// {
// transaction.addToBackStack(null);
// }
// transaction.replace(R.id.fragment_container, fragment);
// transaction.commit();
// getChildFragmentManager().executePendingTransactions();
// }
public void onTabUnselected(TabLayout.Tab tab)
{
// Toast.makeText(getApplicationContext(),"tab unselected",Toast.LENGTH_SHORT).show();
}
public void onTabReselected(TabLayout.Tab tab)
{
}
void switchFragment1(int target)
{
viewPager.setCurrentItem(target);
}
#Override
public void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.leadmain_container, fragment, fragment.toString());
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
}
Lead_tab1 this is the first fragment which contain the form like registration page those values stored in sqlite db but when i cliked on button show the null object Rerference(nul pointer) this is the first fragment which contain the form like registration page those values stored in sqlite db but when i cliked on button show the null object Rerference(nul pointer)
package com.example.dashboard;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.admin.bdayevent.R;
import com.example.admin.bdayevent.Registration;
/**
* Created by admin on 4/28/2016.
*/
public class Lead_step1 extends Fragment implements View.OnClickListener{
EditText customername,customermobile,referncename;
Button nextbtn;
String MobilePattern = "[0-9]{10}";
SharedPreferences lead_pref = null;
Lead_Fragment lead_fragment;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view= inflater.inflate(R.layout.lead_step1, container, false);
customername = (EditText) view.findViewById(R.id.lead_customername);
customermobile = (EditText) view.findViewById(R.id.lead_mobileno);
referncename = (EditText) view.findViewById(R.id.lead_referencename);
nextbtn=(Button)view.findViewById(R.id.leadnext);
nextbtn.setOnClickListener(this);
return view;
}
public void onClick(View v)
{
if (customername.getText().toString().trim().equals("")) {
customername.setError("please enter name");
}
else if (customermobile.getText().toString().trim().equals("")) {
customermobile.setError("please enter 10 digit mobileno");
}
else if (referncename.getText().toString().trim().equals("")) {
referncename.setError("please enter refernce name");
}
else if(customermobile.getText().toString().matches(MobilePattern) == false)
{
customermobile.setError("plz enter 10 digit mobile number");
}
else
{
((Lead_Fragment) getParentFragment()).switchFragment1(2);
String Lead_name=customername.getText().toString().trim();
String Lead_Mobile=customermobile.getText().toString().trim();
String Lead_Reference=referncename.getText().toString();
System.out.println("value of leads"+Lead_name+":"+Lead_Mobile+":"+Lead_Reference);
lead_pref = getActivity().getSharedPreferences("lead_pref",getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = lead_pref.edit();
editor.putString("key_Lead_name", Lead_name);
editor.putString("key_Lead_Mobile", Lead_Mobile);
editor.putString("key_Lead_Reference", Lead_Reference);
editor.commit();
}
}
}
Lead_tab2, this is the second fragment which contain the form like registration page similar to first fragement which in define 3 editetext.
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import com.example.admin.bdayevent.Database;
import com.example.admin.bdayevent.R;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Lead_step2 extends Fragment implements View.OnClickListener {
EditText eventname, eventlocation, eventdate, eventtime;
Button submit_btn;
private int mYear, mMonth, mDay, mHour, mMinute;
DatePickerDialog datePickerDialog;
private static final String TIME24HOURS_PATTERN =
" (([0-1]?[0-9])|(2[0-3])):[0-5][0-9] ";
private Pattern pattern;
private Matcher matcher;
SharedPreferences Lead2;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.lead_step2, container, false);
eventname = (EditText) view.findViewById(R.id.lead_eventname);
eventlocation = (EditText) view.findViewById(R.id.lead_location);
eventdate = (EditText) view.findViewById(R.id.lead_date);
eventtime = (EditText) view.findViewById(R.id.lead_time);
submit_btn = (Button) view.findViewById(R.id.lead_submitbtn);
eventdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(getActivity(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
eventdate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
} else {
//datePickerDialog.
}
}
});
eventtime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(),
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute)
{
boolean isPM = (hourOfDay >= 12);
eventtime.setText(String.format("%02d:%02d %s", (hourOfDay == 12 || hourOfDay == 0) ? 12 : hourOfDay % 12, minute, isPM ? "PM" : "AM"));
}
}, mHour, mMinute, false);
timePickerDialog.show();
} else {
// Hide your calender here
}
}
});
submit_btn.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v)
{
if (eventname.getText().toString().trim().equals("")) {
eventname.setError("please enter eventname");
} else if (eventlocation.getText().toString().trim().equals("")) {
eventname.setError("please enter eventlocation");
} else if (eventdate.getText().toString().trim().equals("")) {
eventdate.setError("please enter evendate");
} else if (eventtime.getText().toString().trim().equals("")) {
eventtime.setError("please enter Eventtime");
}
else if (validateTime(String.valueOf(eventdate.getText())))
{
eventdate.setError("please enter Valid Date");
}
else if(validateDate(String.valueOf(eventtime.getText())))
{
eventtime.setError("please enter Valid Date");
}
else
{
Toast.makeText(getContext(), "Welcome to leadgenration", Toast.LENGTH_SHORT);
// ((Lead_Fragment) getParentFragment()).switchFragment1(2);
new Lead_generation().execute();
}
}
class Lead_generation extends AsyncTask<Void,Void,Boolean>
{
protected void onPreExecute()
{
//System.out.println("value of user is preexecute:" + User_mobile + "" + User_password);
progressDialog = new ProgressDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenting....plz wait");
progressDialog.show();
}
protected Boolean doInBackground(Void... params)
{
if(Send_Lead())
{
}
return false;
}
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
if(result==true)
{
Toast.makeText(getActivity(),"Lead Added Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(),"not add Lead",Toast.LENGTH_SHORT).show();
}
}
}
public boolean Send_Lead()
{
Lead2=getActivity().getSharedPreferences("lead_pref", getContext().MODE_PRIVATE);
String Lead_Cutom_name = Lead2.getString("key_firstname","");
String Lead_Custom_contact = Lead2.getString("key_lastname","");
String Lead_Custom_reference = Lead2.getString("key_user_org","");
String Lead_Eventname=eventname.getText().toString().trim();
String Lead_Eventlocation=eventlocation.getText().toString().trim();
String Lead_EventDate=eventdate.getText().toString().trim();
String Lead_EventTime=eventtime.getText().toString().trim();
System.out.println("value of all leads"+Lead_Cutom_name+" "+Lead_Custom_contact+" "
+Lead_Custom_reference+" "+Lead_Eventname+" "+Lead_Eventlocation+" "+Lead_EventDate+" "+Lead_EventTime);
if(Database.ADD_Lead(getActivity(),Lead_Cutom_name,Lead_Custom_contact,Lead_Custom_reference,Lead_Eventname,Lead_Eventlocation,
Lead_EventDate,Lead_EventTime))
{
return true;
}
else
{
return false;
}
}
public boolean validateTime(final String time)
{
matcher = pattern.matcher(time);
return matcher.matches();
}
public boolean validateDate(String date)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try {
sdf.parse(date);
return true;
} catch (ParseException ex) {
return false;
}
}
}
LOCATFILE
this is the logcat file show background processing also show the any type of error occur in your project
05-11 06:16:53.858 13059-13059/com.example.admin.bdayevent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.bdayevent, PID: 13059
java.lang.ClassCastException: com.example.dashboard.New_dashboard cannot be cast to com.example.admin.bdayevent.Registration
at com.example.dashboard.Lead_step1.onClick(Lead_step1.java:67)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try like this
put one container or use the existing container and make a fragment transaction there when you click the button. like this
NEWFragment new_fragment = new NEWFragment();
FragmentTransaction transaction = (context).getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, new_fragment, new_fragment.toString());
transaction.addToBackStack(new_fragment.toString());
new_fragment.setArguments(bundle);
transaction.commitAllowingStateLoss();
Related
I am trying to pass values from a fragment which contains a recycler view to another fragment which are all part of the bottombar.
I have tried using interface to achieve this, but my app crashes and shows a NullPointerException.
My first fragment contains a checkbox along with a Edit Text showing current Location, price and an image button which serves as a DatePicker.
When the user checks the checkbox he can enter the date into the EditText field from the image button.
The user can pick three dates into the EditText Fields.
My question is how to make these entries (location,price and date)
pass to the third fragment?
I have taken reference from this to implement the interface.
Here is my code
Textproperty1.java
import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.example.sumitroy.pitchads.TextProperty1_Schedule_Classes.TextProperty1_Schedule;
import com.example.sumitroy.pitchads.TimesofIndia.TOITextFragment;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.OnMenuTabClickListener;
import java.util.ArrayList;
public class TextProperty1 extends AppCompatActivity {
BottomBar bottomBar;
String test=null;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_property1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar appbar = getSupportActionBar();
appbar.setDisplayHomeAsUpEnabled(true);
appbar.setDisplayShowHomeEnabled(true);
bottomBar=BottomBar.attach(this,savedInstanceState);
bottomBar.noNavBarGoodness();
bottomBar.noTabletGoodness();
bottomBar.noResizeGoodness();
bottomBar.hideShadow();
bottomBar.setItemsFromMenu(R.menu.bottombar_textproperty, new OnMenuTabClickListener() {
#Override
public void onMenuTabSelected(#IdRes int menuItemId) {
if(menuItemId==R.id.textproperty_bottombaritem1)
{
TextProperty1_Schedule f=new TextProperty1_Schedule();
Intent intent=new Intent(getApplicationContext(),TextProperty1_Schedule.class);
intent.putExtra(test,"check");
getSupportFragmentManager().beginTransaction().replace(R.id.textframe,f).commit();
}
else if(menuItemId==R.id.textproperty_bottombaritem2)
{
TextProperty1_EditText f=new TextProperty1_EditText();
getSupportFragmentManager().beginTransaction().replace(R.id.textframe,f).commit();
}
else
{
TextProperty1_ConfirmAd f=new TextProperty1_ConfirmAd();
getSupportFragmentManager().beginTransaction().replace(R.id.textframe,f).commit();
}
}
#Override
public void onMenuTabReSelected(#IdRes int menuItemId) {
}
});
}
#Nullable
#Override
public Intent getSupportParentActivityIntent() {
String from=getIntent().getExtras().getString("from");
Intent newintent=null;
if(from.equals("FAV"))
{
newintent=new Intent(this,TOITextFragment.class);
}
return newintent;
}
}
TextProperty1_Schedule.java
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sumitroy.pitchads.R;
import com.example.sumitroy.pitchads.TextProperty1;
import com.example.sumitroy.pitchads.TextProperty1_ConfirmAd;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.jar.Manifest;
/**
* A simple {#link Fragment} subclass.
*/
public class TextProperty1_Schedule extends Fragment {
TextView textView;
private static final int MY_PERMISSION_REQUEST_LOCATION=1;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<TextProperty1_Schedule_Location>scheduleLocationList;
int imageid[]={R.drawable.location_show};
public TextProperty1_Schedule() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview;
rootview= inflater.inflate(R.layout.fragment_text_property1__schedule, container, false);
textView=(TextView)rootview.findViewById(R.id.yourCity);
if(ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION))
{
ActivityCompat.requestPermissions(getActivity(),new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSION_REQUEST_LOCATION);
}
else
{
ActivityCompat.requestPermissions(getActivity(),new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSION_REQUEST_LOCATION);
}
}
else
{
LocationManager locationManager=(LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);
Location location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
try
{
textView.setText(herelocation1(location.getLatitude(),location.getLongitude()));
}
catch (Exception e)
{
e.printStackTrace();
//Toast.makeText(getContext(),"Not Found!!",Toast.LENGTH_LONG).show();
}
}
scheduleLocationList=new ArrayList<>();
for(int i=1;i<=15;i++)
{
if(i==1)
{
TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Bangalore", "1000", " "," "," ", false,imageid[0]);
scheduleLocationList.add(sl);
}
else if(i==2)
{
TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Jamshedpur", "250", " "," "," ",false,imageid[0]);
scheduleLocationList.add(sl);
}
else if(i==3)
{
TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Indore", "100", " "," "," ", false,imageid[0]);
scheduleLocationList.add(sl);
}
else if(i==4)
{
TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Mumbai", "450", " "," "," ", false,imageid[0]);
scheduleLocationList.add(sl);
}
else if(i==5)
{
TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Goa", "450", " "," "," ", false,imageid[0]);
scheduleLocationList.add(sl);
}
else
{
TextProperty1_Schedule_Location sl = new TextProperty1_Schedule_Location("Goa", "450", " "," "," ", false,imageid[0]);
scheduleLocationList.add(sl);
}
}
mRecyclerView = (RecyclerView)rootview.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new TextProperty1_CardViewScheduleAdapter(scheduleLocationList,communication);
mRecyclerView.setAdapter(mAdapter);
return rootview;
}
#Override
public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults) {
switch (requestCode)
{
case MY_PERMISSION_REQUEST_LOCATION:{
if(grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED)
{
LocationManager locationManager=(LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);
Location location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
try
{
textView.setText(herelocation1(location.getLatitude(),location.getLongitude()));
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getContext(),"Please Switch On Your Location!!",Toast.LENGTH_LONG).show();
}
}
}
else
{
Toast.makeText(getContext(),"No Permission granted!",Toast.LENGTH_LONG).show();
}
}
}
}
public String herelocation1(double lat,double lon)
{
String currcity="";
Geocoder geocoder=new Geocoder(getActivity(), Locale.getDefault());
List<Address> addressList;
try
{
addressList=geocoder.getFromLocation(lat,lon,1);
if(addressList.size() > 0)
{
currcity=addressList.get(0).getLocality();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return currcity;
}
TextProperty1_CardViewScheduleAdapter.FragmentCommunication communication=new TextProperty1_CardViewScheduleAdapter.FragmentCommunication() {
#Override
public void respond(ArrayList<String> locattion_confirm, ArrayList<String> price_confirm, ArrayList<String> dates1_confirm, ArrayList<String> dates2_confirm, ArrayList<String> dates3_confirm) {
TextProperty1_ConfirmAd fragmentB=new TextProperty1_ConfirmAd();
Bundle bundle=new Bundle();
bundle.putString("Location", String.valueOf(locattion_confirm));
bundle.putString("Price", String.valueOf(price_confirm));
bundle.putString("Dates1", String.valueOf(dates1_confirm));
bundle.putString("Dates2", String.valueOf(dates2_confirm));
bundle.putString("Dates3", String.valueOf(dates3_confirm));
fragmentB.setArguments(bundle);
}
};
}
TextProperty1_CardViewScheduleAdapter.java
import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sumitroy.pitchads.R;
import com.example.sumitroy.pitchads.TextProperty1_ConfirmAd;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by Sumit Roy on 06-Apr-17.
*/
public class TextProperty1_CardViewScheduleAdapter extends
RecyclerView.Adapter<TextProperty1_CardViewScheduleAdapter.ViewHolder> {
public ArrayList<String> location=new ArrayList<String>();
public ArrayList<String>price=new ArrayList<String>();
public ArrayList<String>dates1=new ArrayList<String>();
public ArrayList<String>dates2=new ArrayList<String>();
public ArrayList<String>dates3=new ArrayList<String>();
private FragmentCommunication mCommunicator;
public int day,month,year;
int imagebuttonclick=0;
private List<TextProperty1_Schedule_Location> stList;
public TextProperty1_CardViewScheduleAdapter(List<TextProperty1_Schedule_Location> schedule_locations,FragmentCommunication communication) {
this.stList = schedule_locations;
this.mCommunicator=communication;
}
// Create new views
#Override
public TextProperty1_CardViewScheduleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.textproperty1_list_schedule_card, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView,mCommunicator);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
final int pos = position;
viewHolder.tvLocate.setText(stList.get(position).getLocation());
viewHolder.tvPrice.setText(stList.get(position).getPrice());
viewHolder.chkSelected.setChecked(stList.get(position).isSelected());
viewHolder.chkSelected.setTag(stList.get(position));
viewHolder.img.setImageResource(stList.get(position).getUrl());
viewHolder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(final View v) {
//Click Event for check box
CheckBox cb = (CheckBox) v;
TextProperty1_Schedule_Location contact = (TextProperty1_Schedule_Location) cb.getTag();
contact.setSelected(cb.isChecked());
stList.get(pos).setSelected(cb.isChecked());
imagebuttonclick=0;
/*Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show(); */
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Click event for image button
imagebuttonclick+=1;
if(imagebuttonclick==1)
{
//Toast.makeText(view.getContext(),"Clicked once",Toast.LENGTH_SHORT).show();
final Calendar calendar=Calendar.getInstance();
day=calendar.get(Calendar.DAY_OF_MONTH);
month=calendar.get(Calendar.MONTH);
day=day+1;
year=calendar.get(Calendar.YEAR);
Context context=v.getContext();
DatePickerDialog datePickerDialog=new DatePickerDialog(context, 0, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
String selected_date=" " + i2+ "/" + i1 + "/" + i;
//Toast.makeText(v.getContext(),selected_date,Toast.LENGTH_SHORT).show();
viewHolder.dates.setText(selected_date);
String getlocation,getprice,getdate1;
getlocation=viewHolder.tvLocate.getText().toString();
getprice=viewHolder.tvPrice.getText().toString();
getdate1=viewHolder.dates.getText().toString();
if(getdate1.length()!=0)
{
location.add(getlocation); //Pass this value to a different fragment
price.add(getprice);//Pass this value to a different fragment
dates1.add(getdate1);//Pass this value to a different fragment
}
}
},year,month,day
);
//Will set datepicker dialog from current date
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
datePickerDialog.setTitle("Select Date");
datePickerDialog.show();
}
else if(imagebuttonclick==2)
{
//Toast.makeText(view.getContext(),"More Than once",Toast.LENGTH_SHORT).show();
final Calendar calendar=Calendar.getInstance();
day=calendar.get(Calendar.DAY_OF_MONTH);
day=day+2;
month=calendar.get(Calendar.MONTH);
year=calendar.get(Calendar.YEAR);
Context context=v.getContext();
DatePickerDialog datePickerDialog=new DatePickerDialog(context, 0, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
String selected_date=" " + i2+ "/" + i1 + "/" + i;
//Toast.makeText(v.getContext(),selected_date,Toast.LENGTH_SHORT).show();
String getdate2;
viewHolder.dates2.setText(selected_date);
getdate2=viewHolder.dates2.getText().toString();
if(getdate2.length()!=0)
{
dates2.add(getdate2); //Pass this value to a different fragment
}
}
},year,month,day
);
//Will set datepicker dialog from current date
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
datePickerDialog.setTitle("Select Date");
calendar.add(Calendar.DAY_OF_MONTH,+1);
datePickerDialog.show();
}
else if(imagebuttonclick==3)
{
//Toast.makeText(view.getContext(),"More Than once",Toast.LENGTH_SHORT).show();
final Calendar calendar=Calendar.getInstance();
day=calendar.get(Calendar.DAY_OF_MONTH);
day=day+3;
month=calendar.get(Calendar.MONTH);
year=calendar.get(Calendar.YEAR);
Context context=v.getContext();
DatePickerDialog datePickerDialog=new DatePickerDialog(context, 0, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
String selected_date=" " + i2+ "/" + i1 + "/" + i;
//Toast.makeText(v.getContext(),selected_date,Toast.LENGTH_SHORT).show();
String getdate3;
viewHolder.dates3.setText(selected_date);
getdate3=viewHolder.dates3.getText().toString();
if(getdate3.length()!=0)
{
dates3.add(getdate3); //Pass this value to a different fragment
}
}
},year,month,day
);
//Will set datepicker dialog from current date
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
datePickerDialog.setTitle("Select Date");
datePickerDialog.show();
}
else
{
Toast.makeText(view.getContext(),"Can Enter Ads only for three days",Toast.LENGTH_SHORT).show();
imagebuttonclick=0;
}
}
});
if(viewHolder.chkSelected.isChecked()==false)
{
viewHolder.dates.setText(" ");
viewHolder.dates2.setText(" ");
viewHolder.dates3.setText(" ");
}
TextProperty1_ConfirmAd fragmentB=new TextProperty1_ConfirmAd();
Bundle bundle=new Bundle();
bundle.putString("Location", String.valueOf(location));
fragmentB.setArguments(bundle);
}
});
mCommunicator.respond(location,price,dates1,dates2,dates3);
TextProperty1_ConfirmAd fragmentB=new TextProperty1_ConfirmAd();
Bundle bundle=new Bundle();
bundle.putString("Location", String.valueOf(location));
bundle.putString("Price", String.valueOf(price));
bundle.putString("Dates1", String.valueOf(dates1));
bundle.putString("Dates2", String.valueOf(dates2));
bundle.putString("Dates3", String.valueOf(dates3));
fragmentB.setArguments(bundle);
}
// Return the size arraylist
#Override
public int getItemCount() {
return stList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvLocate;
public TextView tvPrice;
public EditText dates;
public EditText dates2;
public EditText dates3;
public ImageButton img;
public CheckBox chkSelected;
FragmentCommunication mcommunication;
public TextProperty1_Schedule_Location singlestudent;
public ViewHolder(View itemLayoutView,FragmentCommunication communicator) {
super(itemLayoutView);
chkSelected = (CheckBox) itemLayoutView
.findViewById(R.id.checkbox1);
tvLocate = (TextView) itemLayoutView.findViewById(R.id.tvLocation);
tvPrice = (TextView) itemLayoutView.findViewById(R.id.tvPrice);
img=(ImageButton)itemLayoutView.findViewById(R.id.itemImage);
dates = (EditText) itemLayoutView.findViewById(R.id.tvDates);
dates2=(EditText)itemLayoutView.findViewById(R.id.tvDates2);
dates3=(EditText)itemLayoutView.findViewById(R.id.tvDates3);
mcommunication=communicator;
}
}
// method to access in activity after updating selection
public List<TextProperty1_Schedule_Location> getStudentist() {
return stList;
}
public interface FragmentCommunication {
void respond(ArrayList<String> locattion_confirm,ArrayList<String> price_confirm,ArrayList<String> dates1_confirm,ArrayList<String> dates2_confirm,ArrayList<String> dates3_confirm);
}
}
TextProperty1_ConfirmAd
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class TextProperty1_ConfirmAd extends Fragment {
TextView textView1,textView2,textView3,textView4,textView5;
ArrayList<String>get_location;
ArrayList<String>get_price;
ArrayList<String>get_dates1;
ArrayList<String>get_dates2;
ArrayList<String>get_dates3;
public TextProperty1_ConfirmAd() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
get_location=getArguments().getStringArrayList("Location");
get_price=getArguments().getStringArrayList("Price");
get_dates1=getArguments().getStringArrayList("Dates1");
get_dates2=getArguments().getStringArrayList("Dates2");
get_dates3=getArguments().getStringArrayList("Dates3");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view;
view=inflater.inflate(R.layout.fragment_text_property1__confirm_ad, container, false);
textView1=(TextView)view.findViewById(R.id.textView1);
textView2=(TextView)view.findViewById(R.id.textView2);
textView3=(TextView)view.findViewById(R.id.textView3);
textView4=(TextView)view.findViewById(R.id.textView4);
textView5=(TextView)view.findViewById(R.id.textView5);
textView1.setText((CharSequence) get_location);
textView2.setText((CharSequence) get_price);
textView3.setText((CharSequence) get_dates1);
textView4.setText((CharSequence) get_dates2);
textView5.setText((CharSequence) get_dates3);
return view;
}
}
For transfer data from fragments you should using Bundle. In your code I see that you put in bundle String (method public void respond), but in method onCrerate you call method getStringArrayList(). You call different methods and you get NullPointerException.
You can use greenrobot/EventBus. Register EventBus in all those fragment where you need an event. To get event #Subscribe a method with a required model. And perform your action within runOnUIThread(). I think your objective will be achieved. And remember one thing, don't forget to unregister EventBus when Fragment/Activity is destroyed.
Follow these steps-
Create a Bus Model
public class BusModelAdapterItems {
private ArrayList<String> stringArrayList;
public BusModelAdapterItems(ArrayList<String> stringArrayList) {
this.stringArrayList = stringArrayList;
}
public ArrayList<String> getStringArrayList() {
return stringArrayList;
}
}
In your fragment put the codes-
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
}
#org.greenrobot.eventbus.Subscribe
public void onAdapterUpdate(final BusModelAdapterItems items) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// do what you want
// items.getStringArrayList();
}
});
}
From your Adapter please put this code-
// the array list that adapter holds and you want to pass to the fragments
EventBus.getDefault().post(new BusModelAdapterItems(arrayList));
here is my Code,the Activityis to show 7 tabs from Mon. to Sun.each tabs use the same fragment,I wanna add a ListView to load the imformation,but I don't how to do
Activity:
package space.levan.myclass.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
import space.levan.myclass.R;
import space.levan.myclass.fragment.LessonFragment;
import space.levan.myclass.utils.InfoUtil;
import space.levan.myclass.utils.NetUtil;
/**
* Created by 339 on 2016/5/3.
*/
public class ScheduleActivity extends AppCompatActivity implements MaterialTabListener{
#Bind(R.id.materialTabHost)
MaterialTabHost mTabHost;
#Bind(R.id.pager)
ViewPager mViewPager;
ViewPagerAdapter adapter;
private List<HashMap<String, Object>> ClassInfos;
private HashMap<String, Object> ClassInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
ButterKnife.bind(this);
setTitle("课程表");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Fragment lessonFragment;
adapter = new ViewPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
mTabHost.setSelectedNavigationItem(position);
}
});
// insert all tabs from pagerAdapter data
for (int i = 0; i < adapter.getCount(); i++) {
mTabHost.addTab(
mTabHost.newTab()
.setText(adapter.getPageTitle(i))
.setTabListener(this)
);
}
Calendar calendar = Calendar.getInstance();
int temp = calendar.get(Calendar.DAY_OF_WEEK) - 2;
mViewPager.setCurrentItem(temp);
Map<String, String> loginInfo = InfoUtil.getLoginInfo(ScheduleActivity.this);
getLesson(loginInfo.get("StuToken"));
}
public String getLesson(final String mToken) {
new Thread() {
public void run() {
String result = NetUtil.getSchedule(mToken);
if (result != null) {
try {
JSONObject jsonObject = new JSONObject(result);
int error = jsonObject.getInt("error");
String message = jsonObject.getString("message");
switch (error) {
case 0:
getDes(jsonObject);
break;
case 1:
showToast(message);
break;
case 2:
reLogin();
break;
default:
break;
}
}catch (Exception e) {
e.printStackTrace();
}
} else {
showToast("数据异常");
}
}
}.start();
return null;
}
private void getDes(JSONObject jsonObject) {
try {
JSONObject Object = jsonObject.getJSONObject("data");
JSONObject data = Object.getJSONObject("data");
for (int i = 1; i < 7; i++) {
JSONObject day = data.getJSONObject(""+i);
for (int n = 1; n < 5; n++) {
JSONArray lesson = day.getJSONArray(""+n);
ClassInfos = new ArrayList<>();
for(int m = 0; m < lesson.length();m++) {
JSONObject des = (JSONObject) lesson.get(m);
String name = des.getString("course");
String teacher = des.getString("teacher");
String time = des.getString("time");
String room = des.getString("classroom");
/*showToast("星期:" + i + "\n节次:" + n + "\n课程名字:"
+ name + "\n任课老师:" + teacher + "\n上课周数:" + time
+ "\n教室:" + room);*/
ClassInfo = new HashMap<>();
ClassInfo.put("Name","课程名字:" + name);
ClassInfo.put("Teacher","上课老师:" + teacher);
ClassInfo.put("Time","上课周次:" + time);
ClassInfo.put("Room","上课教室:" + room);
ClassInfos.add(ClassInfo);
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
private void showToast(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScheduleActivity.this,message, Toast.LENGTH_SHORT).show();
}
});
}
private void reLogin() {
InfoUtil.deleteUserInfo(ScheduleActivity.this);
runOnUiThread(new Runnable() {
#Override
public void run() {
final Intent intent = getPackageManager().
getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Toast.makeText(ScheduleActivity.this,
"数据异常,请重新登录帐号",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onTabSelected(MaterialTab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(MaterialTab tab) {
}
#Override
public void onTabUnselected(MaterialTab tab) {
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int num) {
return new LessonFragment();
}
#Override
public int getCount() {
return 7;
}
#Override
public CharSequence getPageTitle(int position) {
int temp = position+1;
return "星期" + temp;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
menu.add(0, 1, 0, R.string.home_about);
return true;
}
/**
* 用于界面返回按钮
* #param item
* #return
*/
#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:
this.finish();
break;
case 1:
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
Here is fragment :
package space.levan.myclass.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by 339 on 2016/5/5.
*/
public class LessonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
TextView text = new TextView(container.getContext());
text.setText("(╯°Д°)╯︵┴┴");
text.setGravity(Gravity.CENTER);
return text;
}
}
You just need to add a ListView in the LessonFragment.
Follow these steps:
Create a layout file with a listview.
Inflate this layout in onCreateView method of LessonFragment and find this listview.
now, set an adapter for this listview, with the data you want.(hoping you know how to set an adapter)
And now you have a listview in each tab.
public class LessonFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_lesson, container, false);
mListView = (ListView) rootView.findViewById(R.id.listview);
//create an adapter
//set the above adapter to the listview
return rootView;
}
}
I'm using PagerDatePicker library in Android to pick a date and do some work on corresponding date's fragment. But the problem I'm getting is that when I click on a date, I get correct date on corresponding date's textview but not on Toast or Logcat.
When I swipe on the screen (since, it is a viewpager, I can just swipe to move to the next date as shown here),or click on any date, I get correct date on the textView but on Logcat or Toast, it shows the date of a day after or a day before the selected date.
How is it possible that it is showing correct text on textView and incorrect string on Toast/Logcat.
There are 3 Java files - MainActivity.java -
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_main_container, DatePickerDefaultFragment.newInstance())
.commit();
}
}
DatePickerDefaultFragment.java -
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import pl.rspective.pagerdatepicker.PagerDatePickerDateFormat;
import pl.rspective.pagerdatepicker.adapter.DatePagerFragmentAdapter;
import pl.rspective.pagerdatepicker.adapter.DefaultDateAdapter;
import pl.rspective.pagerdatepicker.model.DateItem;
import pl.rspective.pagerdatepicker.view.DateRecyclerView;
import pl.rspective.pagerdatepicker.view.RecyclerViewInsetDecoration;
public class DatePickerDefaultFragment extends Fragment {
private DateRecyclerView dateList;
private ViewPager pager;
LocalDate localDate;
DateTime dateTime;
public static DatePickerDefaultFragment newInstance() {
return new DatePickerDefaultFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_picker_default, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
pager = (ViewPager) view.findViewById(R.id.pager);
dateList = (DateRecyclerView) view.findViewById(R.id.date_list);
// [Setting today's date in the DatePicker.]
localDate = new LocalDate();
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd-MM-yyyy");
Log.i(getClass().getName(), localDate.toString(fmt));
String DATE_START = localDate.toString(fmt);
String DATE_END = localDate.plusYears(5).toString(fmt);
Log.i(getClass().getName(), DATE_END);
// [END]
dateList.addItemDecoration(new RecyclerViewInsetDecoration(getActivity(), R.dimen.date_card_insets));
Date start = null;
Date end = null;
Date defaultDate = null;
try {
start = PagerDatePickerDateFormat.DATE_PICKER_DD_MM_YYYY_FORMAT.parse(DATE_START);
end = PagerDatePickerDateFormat.DATE_PICKER_DD_MM_YYYY_FORMAT.parse(DATE_END);
defaultDate = PagerDatePickerDateFormat.DATE_PICKER_DD_MM_YYYY_FORMAT.parse(DATE_START );
} catch (ParseException e) {
e.printStackTrace();
}
dateList.setAdapter(new DefaultDateAdapter(start, end, defaultDate));
DatePagerFragmentAdapter fragmentAdapter = new DatePagerFragmentAdapter(getFragmentManager(), dateList.getDateAdapter()) {
#Override
protected Fragment getFragment(int position, long date) {
return SimplePageFragment.newInstance(position, date);
}
};
pager.setAdapter(fragmentAdapter);
dateList.setPager(pager);
dateList.setDatePickerListener(new DateRecyclerView.DatePickerListener() {
#Override
public void onDatePickerItemClick(DateItem dateItem, int position) {
// Toast.makeText(getActivity(), "Clicked: " + position, Toast.LENGTH_SHORT).show();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
Toast.makeText(getActivity(), "Date - " + simpleDateFormat.format(dateItem.getDate()), Toast.LENGTH_SHORT).show();
}
#Override
public void onDatePickerPageSelected(int position) {
}
#Override
public void onDatePickerPageStateChanged(int state) {
}
#Override
public void onDatePickerPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
});
}
}
and SimplePageFragment.java -
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
public class SimplePageFragment extends Fragment {
private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy");
private static final String DATE_PICKER_DATE_KEY = "date_picker_date_key";
private static final String DATE_PICKER_POSITION_KEY = "date_picker_position_key";
private final String TAG = getClass().getSimpleName();
private TextView tvDate;
private TextView tvPosition;
private int position;
private long date;
private DateTime dateTime;
public static SimplePageFragment newInstance(int position, long date) {
Bundle bundle = new Bundle();
bundle.putInt(DATE_PICKER_POSITION_KEY, position);
bundle.putLong(DATE_PICKER_DATE_KEY, date);
SimplePageFragment simplePageFragment = new SimplePageFragment();
simplePageFragment.setArguments(bundle);
return simplePageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(DATE_PICKER_POSITION_KEY, -1);
date = getArguments().getLong(DATE_PICKER_DATE_KEY, -1);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_page_simple, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvDate = (TextView) view.findViewById(R.id.tv_date_label);
tvPosition = (TextView) view.findViewById(R.id.tv_position_label);
dateTime = new DateTime(date);
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
Log.i(TAG, dateTime.toString(formatter));
// tvDate.setText("fun");
String ss = dateTime.toString(formatter);
tvDate.setText(ss);
// Log.e("DATE", "" + dateTime.toString(formatter));
Log.e("DATE2", ss);
// Toast.makeText(getActivity(), SIMPLE_DATE_FORMAT.format(date), Toast.LENGTH_SHORT).show();
// tvPosition.setText(String.valueOf(position));
}
}
and there's this fragment_page_simple.xml layout used in SimplePageFragment -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff343434"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tv_date_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="20sp"
android:textColor="#0f0"/>
<TextView
android:id="#+id/tv_position_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:textSize="16sp"
android:textColor="#ffff3f49"/>
</LinearLayout>
This is just a quick shoot but did you try to use standard java Date classes. The library is based on them, you are using JodaTime library. This shouldn't do any difference but who knows. It's really weird that you have correct value in textView and wrong in logcat.
I checked the demo app, and I am getting correct values in logcat/toast - I used standard Java date class.
final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
dateList = (DateRecyclerView) view.findViewById(R.id.date_list);
dateList.setDatePickerListener(new DateRecyclerView.DatePickerListener() {
#Override
public void onDatePickerItemClick(DateItem dateItem, int position) {
Toast.makeText(context, "date = " + SIMPLE_DATE_FORMAT.format(dateItem.getDate()), Toast.LENGTH_LONG).show();
someTextView.setText(SIMPLE_DATE_FORMAT.format(dateItem.getDate()));
}
#Override
public void onDatePickerPageSelected(int position) {
}
#Override
public void onDatePickerPageStateChanged(int state) {
}
#Override
public void onDatePickerPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
});
I am developing Horizontal Scrolling pages and tabs
MY app is working well in all devices in foreground, but when it goes to background, after one hour, the logs saying that Process com.example.myapp has died. When i reopen the app , the gridview data is not appearing but when scrolling horizontally , getView() method displaying all data like images and text.
that means app has data but view is not formed when process has died. And if i press back button and re-open the app, It is working good
My MainActivity.java is here
package com.bbgusa.bbgdemo.ui.phone;
import java.util.List;
import java.util.Vector;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TabHost;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.listener.phone.CustomViewPager;
import com.bbgusa.bbgdemo.ui.chat.phone.ChatFragmentTab;
import com.bbgusa.bbgdemo.ui.dialpad.phone.DialerFragment;
import com.bbgusa.bbgdemo.ui.home.phone.AlarmFragmentPhone;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragment;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragmentTab;
import com.bbgusa.bbgdemo.ui.home.phone.InfoFragPhone;
import com.bbgusa.bbgdemo.ui.home.phone.MapPhone;
import com.bbgusa.bbgdemo.ui.home.phone.WeatherFragmentPhone;
import com.bbgusa.bbgdemo.ui.messages.phone.MessagesFragment;
import com.bbgusa.bbgdemo.ui.settings.phone.AboutFragment;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentChangedListenerPhone;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
public class MainActivity extends FragmentActivity implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, OnFragmentChangedListenerPhone {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_phone);
this.initialiseTabHost(savedInstanceState);
initialiseViewPager();
}
/**
* Initialise ViewPager
*/
private void initialiseViewPager() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,HomeFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, DialerFragment.class.getName()));
fragments.add(Fragment.instantiate(this,MessagesFragment.class.getName()));
fragments.add(Fragment.instantiate(this,ChatFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, AboutFragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
this.mViewPager = (CustomViewPager) findViewById(R.id.tabviewpager);
this.mViewPager.setAdapter(this.mPagerAdapter);
this.mViewPager.setOnPageChangeListener(this);
this.mViewPager.setOffscreenPageLimit(5);
this.mViewPager.setCurrentItem(0);
}
#Override
public void onFragmentChangePhone(JSONObject response, String whichView, String title, String mPhoneNo) {
Bundle b = new Bundle();
if(response != null)
b.putString("JSONObject", response.toString());
if(title != null)
b.putString("Title", title);
String propertyId = UConnectUtils.getPropertyId(mPref, getString(R.string.property_id));
b.putString(UConnectUtils.PROPERTY_ID_KEY, propertyId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = null;
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
// getSupportFragmentManager().popBackStack();
fragment = new HomeFragment();
} else if (whichView.equals(ConstantsManager.WEATHER)) {
fragment = new WeatherFragmentPhone();
}else if (whichView.equals(ConstantsManager.ALARM)) {
fragment = new AlarmFragmentPhone();
}else if (whichView.equals(ConstantsManager.MAPS)) {
fragment = new MapPhone();
}else if (whichView.equals(ConstantsManager.HELP)) {
fragment = new InfoFragPhone();
}
if (whichView.equals(ConstantsManager.MAPS)) { // to show plus-icon on map top right corner
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, "", View.VISIBLE);
} else if (!whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, mPhoneNo, View.GONE);
}
fragment.setArguments(b);
ft.add(R.id.main_home_frag, fragment);
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
fragmentManager.popBackStack();
} else {
ft.addToBackStack(fragment.toString());
}
ft.commit();
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
}
}
and my HomeFragmentTab.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentTabChangedListener;
#SuppressLint("NewApi")
public class HomeFragmentTab extends Fragment implements OnFragmentTabChangedListener{
private static final String TAG = HomeFragmentTab.class.getSimpleName();
private static HomeFragmentTab tab;
private MainActivity activityPhone;
public static HomeFragmentTab getInstance() {
return tab;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activityPhone = (MainActivity) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
if (container == null) {
return null;
}
Log.i(TAG, "onCreateView");
v = inflater.inflate(R.layout.hometab_phone, container, false);
tab = this;
activityPhone.onFragmentChangePhone(null, ConstantsManager.GRIDVIEWPAGER, getResources().getString(R.string.app_name), "");
return v;
}
#Override
public void onFragmentTabChange(int i, String title, String mPhoneNo, int mapV) {
}
}
and HomeFragment.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.ImageCacheManager;
import com.bbgusa.bbgdemo.ui.cms.tablet.TestTopics;
import com.bbgusa.bbgdemo.ui.cms.tablet.TopicList;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.onGridViewVisibilityChangedListener;
import com.bbgusa.bbgdemo.utils.common.UCConstants;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.IconPagerAdapter;
import com.viewpagerindicator.PageIndicator;
public class HomeFragment extends Fragment implements onGridViewVisibilityChangedListener{
private static final String TAG = HomeFragment.class.getSimpleName();
private ViewPager mViewPager;
private MainActivity activity;
private PageIndicator mIndicator;
private Animation mRotateAnim;
private Dialog indiacatorDialog;
private LinearLayout homeFragmentLL;
private static HomeFragment homeFragment;
public static final HomeFragment getInstance() {
return homeFragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (MainActivity) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.home_phone, container, false);
homeFragment = this;
UConnectUtils.setLauncher(true);
mViewPager = (ViewPager) v.findViewById(R.id.viewpager);
mIndicator = (IconPageIndicator) v.findViewById(R.id.indicator);
homeFragmentLL = (LinearLayout) v.findViewById(R.id.homeFragment);
indiacatorDialog = new Dialog(getActivity());
indiacatorDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
indiacatorDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
indiacatorDialog.setContentView(R.layout.indicator_dialog);
indiacatorDialog.setCanceledOnTouchOutside(false);
Window window = indiacatorDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mRotateAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_and_scale);
UConnectUtils.addAnimationFrameCount(mRotateAnim);
indicatorAnim();
// for property id
// if (activity.isInterNetAvailable()) {
Log.i(TAG, "onCreateView========== isInterNetAvailable");
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
// }
return v;
}
protected void parseJson(JSONObject rootResponce) {
TestTopics.imageUrls.clear();
TestTopics.titles.clear();
TestTopics.mMainMenuID.clear();
TestTopics.mViewType.clear();
TestTopics.mPhoneNo.clear();
try {
//get the Version
String version = rootResponce.optString("VERSION");
SharedPreferences mPref;
SharedPreferences.Editor edit;
mPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
edit = mPref.edit();
edit.putString(getResources().getString(R.string.pref_cms_version_key), version).commit();
JSONArray jsonArray = rootResponce.getJSONArray("MAINMENU");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childMenuObject = jsonArray.getJSONObject(i);
int mainMenuID = childMenuObject.optInt("mainMenuId");
String title = childMenuObject.optString("title");
String viewType = childMenuObject.optString("viewType");
String imageUrl = childMenuObject.optString("imageUrl");
String phoneNo = childMenuObject.optString("phoneNo");
TestTopics.mMainMenuID.add(mainMenuID);
TestTopics.imageUrls.add(imageUrl);
TestTopics.titles.add(title);
TestTopics.mViewType.add(viewType);
TestTopics.mPhoneNo.add(phoneNo);
}
// Create a TopicList for this demo. Save it as the shared instance
// in
// TopicList
String sampleText = getResources().getString(R.string.sample_topic_text);
TopicList tlist = new TopicList(sampleText);
TopicList.setInstance(tlist);
// Create an adapter object that creates the fragments that we need
// to display the images and titles of all the topics.
MyAdapter mAdapter = new MyAdapter(getActivity().getSupportFragmentManager(), tlist, getResources());
// mViewPager.removeAllViews();
mViewPager.setAdapter(mAdapter);
// mViewPager.setPageTransformer(true, new DepthPageTransformer());
mIndicator.setViewPager(mViewPager);
mIndicator.setCurrentItem(0);
mIndicator.notifyDataSetChanged();
ViewTreeObserver observer = mViewPager.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
mViewPager.bringChildToFront(mViewPager.getChildAt(0));
if(Build.VERSION.SDK_INT >= UCConstants.ICE_CREAM_SANDWICH_MR1){
mViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}else{
mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
/*Fragment f = new GridViewFragment();
FragmentTransaction t = getFragmentManager().beginTransaction();
t.replace(R.id.main_home_frag, f);
t.commit();*/
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adapter class
*
* This adapter class sets up GridFragment objects to be displayed by a
* ViewPager.
*/
public static class MyAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter {
private TopicList mTopicList;
private int mNumItems = 0;
private int mNumFragments = 0;
/**
* Return a new adapter.
*/
public MyAdapter(FragmentManager fm, TopicList db, Resources res) {
super(fm);
setup(db, res);
}
/**
* Get the number of fragments to be displayed in the ViewPager.
*/
#Override
public int getCount() {
Log.i(TAG, "getCount : mNumFragments = "+mNumFragments);
return mNumFragments;
}
/**
* Return a new GridFragment that is used to display n items at the
* position given.
*
* #param position
* int - the position of the fragement; 0..numFragments-1
*/
#Override
public Fragment getItem(int position) {
// Create a new Fragment and supply the fragment number, image
// position, and image count as arguments.
// (This was how arguments were handled in the original pager
// example.)
Bundle args = new Bundle();
args.putInt("num", position + 1);
args.putInt("firstImage", position * mNumItems);
// The last page might not have the full number of items.
int imageCount = mNumItems;
if (position == (mNumFragments - 1)) {
int numTopics = mTopicList.getNumTopics();
int rem = numTopics % mNumItems;
if (rem > 0)
imageCount = rem;
}
args.putInt("imageCount", imageCount);
args.putSerializable("topicList", TopicList.getInstance());
// Return a new GridFragment object.
Log.i(TAG, "created fragmenat number:==== "+position+" "+1);
GridViewFragmentPhone f = new GridViewFragmentPhone();
f.setArguments(args);
Log.i(TAG, "getItem : imageCount = "+imageCount);
return f;
}
/**
* Set up the adapter using information from a TopicList and resources
* object. When this method completes, all the instance variables of the
* adapter are valid;
*
* #param tlist
* TopicList
* #param res
* Resources
* #return void
*/
void setup(TopicList tlist, Resources res) {
mTopicList = tlist;
if ((tlist == null) || (res == null)) {
mNumItems = 2;//DEFAULT_NUM_ITEMS;
mNumFragments = 2;//DEFAULT_NUM_FRAGMENTS;
} else {
int numTopics = tlist.getNumTopics();
int numRowsGV = res.getInteger(R.integer.num_of_rows_gridview);
int numColsGV = res.getInteger(R.integer.num_of_cols_gridview);
int numTopicsPerPage = numRowsGV * numColsGV;
int numFragments = numTopics / numTopicsPerPage;
if (numTopics % numTopicsPerPage != 0)
numFragments++; // Add one if there is a partial page
mNumFragments = numFragments;
mNumItems = numTopicsPerPage;
}
} // end setup
#Override
public int getIconResId(int index) {
int[] ICON = new int[mNumFragments];
for (int i = 0; i < mNumFragments; i++) {
ICON[i] = R.drawable.slidericon;
}
return ICON[index % ICON.length];
}
} // end class MyAdapter
#Override
public void onGridViewVisibilityChanged(boolean hide) {
if(hide){
homeFragmentLL.setVisibility(View.GONE);
}else {
homeFragmentLL.setVisibility(View.VISIBLE);
}
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
private class CmsPropertyAsync extends AsyncTask<String, Void, String> {
MainActivity context;
CmsPropertyAsync(MainActivity activityTab) {
context = activityTab;
}
#Override
protected String doInBackground(String... params) {
String propertyId = UConnectUtils.getPropertyId(PreferenceManager.getDefaultSharedPreferences(context),getResources().getString(R.string.property_id));
if(propertyId != null && propertyId.length() > 0){
return propertyId;
}
return UConnectUtils.requestPropertyId(params[0], params[1]);
}
#Override
protected void onPostExecute(String propertyId) {
if(propertyId == null){
indiacatorDialog.dismiss();
showPropertyIdTimeoutAlert(getActivity());
return;
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString(getString(R.string.property_id),propertyId).commit();
String url = null;
String locale = Locale.getDefault().getLanguage();
url = UCConstants.CMS_BASE_URL+"mainMenu?propertyId="+propertyId+"&lang="+locale;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJson(response);
indiacatorDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (activity != null) {
// activity.getConnection(error);
}
indiacatorDialog.dismiss();
}
});
ImageCacheManager.getInstance().getQueueForMainmenu().add(jsObjRequest);
}
}
private void indicatorAnim() {
if (indiacatorDialog != null) {
ImageView alertIndicator = (ImageView) indiacatorDialog.findViewById(R.id.alert_indicator);
alertIndicator.startAnimation(mRotateAnim);
if (!getActivity().isFinishing()) {
indiacatorDialog.show();
}
}
}
// Show alert for Time out
private void showPropertyIdTimeoutAlert(final Activity context) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setIcon(R.drawable.alert_dialog_icon);
alertDialog.setTitle(context.getString(R.string.timeout_msg));
alertDialog.setMessage(context.getString(R.string.timeout_msg2));
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
indicatorAnim();
// for property id
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
}
});
alertDialog.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
getActivity().finish();
}
});
AlertDialog alert = alertDialog.create();
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
if (context != null && !context.isFinishing()) {
alert.show();
}
}
}
Actually, some data is being saved with onSavedInstaceState(). The data is not being deleted when process has been killed on LowMemory.
I fixed this with
#Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}
Just do not call super class. Just comment like above
I am trying to launch a timePicker on click of edittext
I have constructed most of the things !
Buffet_offerings_breakfast_menu2.java
import java.util.Calendar;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import com.androidbegin.jsonparsetutorial.R;
public class Buffet_offerings_breakfast_menu2 extends Fragment{
RadioGroup radioGroup;
EditText from;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
from=(EditText) getActivity().findViewById(R.id.from_lunch_edit_text_id);
from.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// show the time picker dialog
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
}); // this is on onCreate() method..
}
public void onTimePicked(Calendar time)
{
// display the selected time in the TextView
from.setText(DateFormat.format("h:mm a", time));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View view=inflater.inflate(R.layout.buffet_offerings_breakfast_menu2, container, false);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup1);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
if(checkedId == R.id.SelectDaysRG_ID)
{
view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.VISIBLE);
}
else if(checkedId == R.id.WeekdaysRG_ID)
{
view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.INVISIBLE);
}
else if(checkedId == R.id.WeekendsRG_ID)
{
view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.INVISIBLE);
}
}
});
return view;
}
}
TimePickerFragment.java
import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements OnTimeSetListener
{
private TimePickedListener mListener;
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onAttach(Activity activity)
{
// when the fragment is initially shown (i.e. attached to the activity), cast the activity to the callback interface type
super.onAttach(activity);
try
{
mListener = (TimePickedListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + " must implement " + TimePickedListener.class.getName());
}
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
// when the time is selected, send it to the activity via its callback interface method
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
mListener.onTimePicked(c);
}
public static interface TimePickedListener
{
public void onTimePicked(Calendar time);
}
}
I am getting two errors as::
Error1::
for line
newFragment.show(getSupportFragmentManager(), "timePicker");
As -
The method getSupportFragmentManager() is undefined for the type new View.OnClickListener(){}
Error2::
for line
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
As -
TimePickerDialog cannot be resolved to a type
How can i resolve this !
For the first error you can store the getSupprotFragmentManager() in a private variable declared in the class and then use it here.
Use getFragmentmanager() instead of getSupportFragmentManager() in your Fragment class.
Implement TimePickedListener interface in ur FragmentActivity and update the fragment
public class MainActivity extends FragmentActivity implements TimePickedListener {
Calendar time =null;
Fragment_Main fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onTimePicked(Calendar time){
fragment = (Fragment_Main) getSupportFragmentManager().findFragmentById(R.id.new_homescreen_two_fragment);
fragment.onTimePicked(time);
}
}
And this will be in ur fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
view = inflater.inflate(R.layout.buffet_offerings_breakfast_menu2, container, false);
from = (EditText) view.findViewById(R.id.etDepDate);
from.setText("Here");
from.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// show the time picker dialog
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
}); // this is on onCreate() method..
return view;
}
public void onTimePicked(Calendar time) {
// display the selected time in the TextView
from.setText(DateFormat.format("h:mm a", time));
}
I think your problem is from getSupportFragmentManager() at newFragment.show(getSupportFragmentManager(), "timePicker");. Your TimePickerDialog is a Fragmentwhich is committed into Buffet_offerings_breakfast_menu2 fragment (nested fragment). So use getChildFragmentManager() instead of getSupportFragmentManager().