how can i intent back from (activity1-> fragment1) actually my design concept is like ( fragment1-> activity1-> fragment1) in fragment1 i click the data it bring me to activity1 for edit purpose or either update the data or remove the data after click either both button it will bring me back to the fragment1 and look the overall data but my problem is i click either both button it will jump out from the app, how can i solve this problem? using intent or ?
the code below is Update_detail_info ( activity1 )
public class Update_detail_info extends AppCompatActivity implements View.OnClickListener {
EditText weight,bodyf,timef,datef,commentf;
Button btnUpdate, btnRemove;
long weight_id;
SQLControlerWeight dbcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_detail_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbcon = new SQLControlerWeight(this);
dbcon.openDatabase();
btnUpdate = (Button) findViewById(R.id.button_update);
btnRemove = (Button) findViewById(R.id.button_remove);
Intent i = getIntent();
String weightID = i.getStringExtra("weightId");
String dN = i.getStringExtra("dateNum");
String tN = i.getStringExtra("timeNum");
String wN = i.getStringExtra("weightNum");
String bN = i.getStringExtra("bodyFatNum");
String cM = i.getStringExtra("comment");
weight_id = Long.parseLong(weightID);
datef.setText(dN);
timef.setText(tN);
weight.setText(wN);
bodyf.setText(bN);
commentf.setText(cM);
btnUpdate.setOnClickListener(this);
btnRemove.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_update:
String d_update = datef.getText().toString();
String t_update = timef.getText().toString();
String w_update = weight.getText().toString();
String b_update = bodyf.getText().toString();
String c_update = commentf.getText().toString();
dbcon.updateNote(weight_id,w_update,b_update,d_update,t_update,c_update);
this.returnHome();
break;
case R.id.button_remove:
dbcon.deleteNote(weight_id);
this.returnHome();
break;
}
}
public void returnHome() { // is that here the code are wrong ? cause i need to jump back to the previous fragment1
Intent home_intent = new Intent(getApplicationContext(),
HistoryF.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(home_intent);
}
}
break;
}
code below is the fragment for HistoryF ( fragment1)
public class HistoryF extends Fragment {
View contentView;
ListView list;
SQLControlerWeight dbconnection;
TextView weight_num, date_num, time_num, bf_num, comment,weight_ID;
private SimpleCursorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contentView = inflater.inflate(R.layout.history_fragment, container, false);
dbconnection = new SQLControlerWeight(getActivity());
dbconnection.openDatabase();
list = (ListView) contentView.findViewById(R.id.listViewWeight);
Cursor cursor = dbconnection.readNote();
String[] from = new String[]{
DBHelperNote.WEIGHT_ID,
DBHelperNote.WEIGHT_NUM,
DBHelperNote.BODY_FAT,
DBHelperNote.WEIGHT_DATE,
DBHelperNote.WEIGHT_TIME,
DBHelperNote.WEIGHT_COMMENTS
};
int[] to = new int[]{
R.id.weight_id,
R.id.weight_num,
R.id.bf_num,
R.id.date_num,
R.id.time_num,
R.id.comment_text
};
adapter = new SimpleCursorAdapter(
contentView.getContext(), R.layout.history, cursor, from, to,0);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
weight_ID = (TextView) view.findViewById(R.id.weight_id);
weight_num = (TextView) view.findViewById(R.id.weight_num);
bf_num = (TextView) view.findViewById(R.id.bf_num);
date_num = (TextView) view.findViewById(R.id.date_num);
time_num = (TextView) view.findViewById(R.id.time_num);
comment = (TextView) view.findViewById(R.id.comment_text);
String weightId = weight_ID.getText().toString();
String wn = weight_num.getText().toString();
String bfn = bf_num.getText().toString();
String dn = date_num.getText().toString();
String tn = time_num.getText().toString();
String cm = comment.getText().toString();
Intent modify_intent = new Intent(getActivity(), Update_detail_info.class);
modify_intent.putExtra("weightId", weightId);
modify_intent.putExtra("dateNum", dn);
modify_intent.putExtra("timeNum", tn);
modify_intent.putExtra("weightNum", wn);
modify_intent.putExtra("bodyFatNum", bfn);
modify_intent.putExtra("comment", cm);
startActivity(modify_intent);
}
});
return contentView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
this is my main activity for control the tab
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new KeyInWeightF(), "TRACK");
adapter.addFragment(new HistoryF(), "HISTORY");
adapter.addFragment(new AnalysisF(), "GRAPH");
viewPager.setAdapter(adapter);
}
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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can simply use this code on your returnHome()
Intent intent = NavUtils.getParentActivityIntent(Update_detail_info.this); //get parent activity
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(Update_detail_info.this, intent); // and then navigate it to parent
or
NavUtils.navigateUpFromSameTask(Update_detail_info.this);
both worked same
and in your manifest file define parentActivity
manifest.xml
<activity
android:name="com.example.yourApp.MainActivity" ...>
...
</activity>
<!-- A child of the main activity -->
<activity
android:name="com.example.yourApp.Update_detail_info"
android:label="#string/title_activity_Update_detail"
android:parentActivityName="com.example.yourApp.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.yourApp.MainActivity" />
</activity>
For more details to Providing Up Navigation go to this link.
And for understand startactivityforresult go to this link
Related
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;
using UnityEngine.UI;
public class admobVideo : MonoBehaviour {
RewardBasedVideoAd rewardBasedVideo;
static InterstitialAd interstitial;
string VideoID = "ca-app-pub-6032262586397129~2821965113";
string adUnitId = "ca-app-pub-6032262586397129/5003220953";
public static admobVideo Instance;
void Start ()
{
Instance = this;
DontDestroyOnLoad(gameObject);
RequestRewardBasedVideo();
RequestInterstitial();
}
public void RequestRewardBasedVideo()
{
rewardBasedVideo = RewardBasedVideoAd.Instance;
rewardBasedVideo.LoadAd(new AdRequest.Builder().Build(), adUnitId);
}
public void RequestInterstitial()
{
interstitial = new InterstitialAd(VideoID);
interstitial.LoadAd(new AdRequest.Builder().Build());
}
public void ShowAd()
{
if(rewardBasedVideo.IsLoaded())
{
rewardBasedVideo.Show();
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
}
public static void ShowInter()
{
showInterstitial(interstitial);
}
private void showAdd(RewardBasedVideoAd r)
{
if (r.IsLoaded())
{
//Subscribe to Ad event
r.Show();
r.OnAdRewarded += HandleRewardBasedVideoRewarded;
}
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
PlayerPrefs.SetInt("coins", PlayerPrefs.GetInt("coins") + 5);
GameObject.FindGameObjectWithTag("Coins").GetComponent<Text>().text = PlayerPrefs.GetInt("coins").ToString();
GameObject.FindGameObjectWithTag("Double").GetComponent<Button>().interactable = false;
Debug.Log("Pref: " + PlayerPrefs.GetInt("coins"));
}
static void showInterstitial(InterstitialAd i)
{
if (i.IsLoaded())
{
i.Show();
}
}
}
I am rewarding players with 5 coins , But when I click button nothing appears , I have tried to change code in many ways but no positive result.
when i click in the button in unity the console show me "Dummy is loaded" and "Dummy showrewardedbasedvideoad"
Method that is called upon button click is ShowAd(). Please Help
Please check by adding debug in HandleRewardBasedVideoRewarded method to check if it's called.
Also check you have added listener for that as you have not mentioned this in your code mentioned above.
rewardBasedVideo.OnAdRewarded += this.HandleRewardBasedVideoRewarded;
You have not initialised mobileAds with your app id:
MobileAds.Initialize();
Good evening, I am creating an application and I need help with this error.
the
log cat of the error:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at cqdevelopers.incrediblediet.Fragment3.getAddressKeyValueFile(Fragment3.java:90)
at cqdevelopers.incrediblediet.Fragment3.onCreateView(Fragment3.java:25)
<!-- begin snippet: js hide: false -->
<!-- language: lang-js -->
05-16 02:25:21.711 6498-6498/cqdevelopers.incrediblediet E/AndroidRuntime: FATAL EXCEPTION: main
Process: cqdevelopers.incrediblediet, PID: 6498
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at cqdevelopers.incrediblediet.Fragment3.getAddressKeyValueFile(Fragment3.java:90)
at cqdevelopers.incrediblediet.Fragment3.onCreateView(Fragment3.java:25)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:1920)
at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2050)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2108)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2553)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2197)
at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2403)
at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1737)
at android.app.Activity.dispatchTouchEvent(Activity.java:2765)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2364)
at android.view.View.dispatchPointerEvent(View.java:9514)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4230)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4096)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3787)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3669)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3844)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3695)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3661)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3669)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3642)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5922)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5896)
at android.view.
Fragment3.java:
public class Fragment3 extends Fragment {
private EditText editText;
private TextView textView;
private Button button;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment3_layout, container, false);
getAddressKeyValueFile();
editText = (EditText) v.findViewById(R.id.tvadress);
textView = (TextView) v.findViewById(R.id.textView);
button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String address = null;
address = editText.getText().toString();
textView.setText(address);
setAddressKeyValueFile(address);
}
});
return v;
}
private void getAddressKeyValue() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("r", Context.MODE_PRIVATE);
String key = getString(R.string.address);
String existingAddress = sharedPreferences.getString(key, null);
if (existingAddress != null) {
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
textView.setText(existingAddress);
}
}
private void setAddressKeyValue(String address)
{
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("d" ,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String key = getString(R.string.address);
editor.putString(key,address);
editor.commit();
}
private void getAddressKeyValueFile()
{
Context context = getContext().getApplicationContext();
String fileName = getString(R.string.filename);
SharedPreferences sharedPreferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);
String key = getString(R.string.address);
String existingAddress = sharedPreferences.getString(key,null);
if(existingAddress != null)
{
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
textView.setText(existingAddress);
}
}
private void setAddressKeyValueFile(String address)
{
Context context = getContext().getApplicationContext();
String fileName = getString(R.string.filename);
SharedPreferences sharedPreferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String key = getString(R.string.address);
editor.putString(key, address);
editor.commit();
}
}
And fragment3.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="cqdevelopers.incrediblediet.MainActivity$PlaceholderFragment">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvadress"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="register"
android:id="#+id/textView2"
android:layout_marginTop="23dp"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/tvadress"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView"
android:layout_marginTop="29dp"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Kindly have a look on exception and let me know where i am doing wrong, your help is appreciated thanks in Advance.
change position of getAddressKeyValueFile
//getAddressKeyValueFile();
editText = (EditText) v.findViewById(R.id.tvadress);
textView = (TextView) v.findViewById(R.id.textView);
getAddressKeyValueFile();
and delete line:
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
in getAddressKeyValueFile()
This line of code textView = (TextView) v.findViewById(R.id.textView); is trying to get the TexView with the id textView from the activity's layout not from the fragment's layout.
You should change:
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
textView.setText(existingAddress);
to:
if(textView!=null){
textView.setText(existingAddress);
}
in both the getAddressKeyValueFile() and getAddressKeyValue() methods.
Also, in the onCreateView(...) method, call getAddressKeyValueFile(); only after textView has been initialized.
in the getAddressValueFile, change the way the strings are retrived.
private void getAddressKeyValueFile()
{
Context context = getContext().getApplicationContext();
String fileName = getResources.getString(R.string.filename);
SharedPreferences sharedPreferences = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);
String key = getResources.getString(R.string.address);
String existingAddress = sharedPreferences.getString(key,null);
if(existingAddress != null)
{
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
textView.setText(existingAddress);
}
}
instead of
getString(R.string.filename)
change to
getResources.getString(R.string.filename)
Also, make similar changes in the setAddressKeyValue method.
EBelow is my code for adding EditText to my layout and it works fine but I want it to create the new EditText boxes below the ones that was created. If you see something in the code I should change or improve, pls comment.Thanks in advance.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_weight_log);
relativeLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
tt= (EditText)findViewById(R.id.tt);
dd = (EditText)findViewById(R.id.dd);
aa = (Button) findViewById(R.id.add);
aa.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) { aa();}});
}
public void aa()
{ for(i = 0; i <100; ++i);
RelativeLayout layout = (RelativeLayout) findViewById(R.id.relativeLayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams (
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.BELOW);
params.setMargins(0,600,0,0);
EditText edtTxt = new EditText(this);
int maxLength = 5;
edtTxt.setHint("editText1");
edtTxt.setLayoutParams(params);
edtTxt.setBackgroundColor(Color.WHITE);
edtTxt.setInputType(InputType.TYPE_CLASS_DATETIME);
edtTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
edtTxt.setFilters(fArray);
layout.addView(edtTxt);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params1.setMargins(0,600,0,0);
EditText editText = new EditText(this);
int maxLength1 = 4;
editText.setHint("editText2");
editText.setLayoutParams(params1);
editText.setBackgroundColor(Color.WHITE);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
fArray[0] = new InputFilter.LengthFilter(maxLength1);
editText.setFilters(fArray);
layout.addView(editText);
}
Try changing to linear layout and setting its orientation to vertical. Then if you will add a new view it will be added below your previous view.
I have drawn a customized navigation drawer with ListView and header but when i scroll the List the checkbox in the List are getting unchecked.
Secondly when i click on the reset button in the header part I want that all the checkbox in the Listview should get get unchecked. I have been trying this to get it working but unable to find any solution..
The snippets are
public class NavigationDrawer extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.filter_navigation_drawer, container,false);
drawerListView= ( ListView ) view.findViewById( R.id.listDrawer );
drawerListView.setOnItemClickListener(new FilterDrawerItemClickListener());
dataList.add(new FilterDrawerItem("sample1",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample3",true));
dataList.add(new FilterDrawerItem("sample4",true));
dataList.add(new FilterDrawerItem("sample5",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample2",true));
dataList.add(new FilterDrawerItem("sample2",true));
adapter = new FilterCustomDrawerAdapter(getActivity(), R.layout.drawer_filter,dataList,drawerStatus);
drawerListView.setAdapter(adapter);
adapter.getFilterList();
resetBtn = (TextView)view.findViewById(R.id.filterby_reset);
if(resetBtn != null){
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
application.setFilterStatus("reset");
for(int i=0; i<dataList.size(); i++){
dataList.get(i).setCheckBoxId(false);
}
adapter.notifyDataSetChanged();
// this.onCreateView();
}
});
}
return view;
}
}
FilterCustomDrawerAdapter.java
public class FilterCustomDrawerAdapter extends ArrayAdapter<FilterDrawerItem> {
Context context;
List<FilterDrawerItem> drawerItemList;
int layoutResID;
int item = 0;
String status;
List<Integer> filterList = new ArrayList<Integer>();
DrawerStatus drawerStatus;
StataApplication application = StataApplication.getInstance();
HashMap<Integer, Boolean> checked; // newly added code
public FilterCustomDrawerAdapter(Context context, int layoutResourceID,
List<FilterDrawerItem> listItems,DrawerStatus drawerStatus) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
this.drawerStatus = drawerStatus;
checked = new HashMap<Integer, Boolean>(getCount());
}
public FilterCustomDrawerAdapter(Context context, int layoutResourceID,
List<FilterDrawerItem> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.drawerItemList = listItems;
this.layoutResID = layoutResourceID;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final FilterDrawerItemHolder drawerHolder;
View view = convertView;
if (view == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
drawerHolder = new FilterDrawerItemHolder();
view = inflater.inflate(layoutResID, parent, false);
drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_filterName);
drawerHolder.checkBox = (CheckBox) view.findViewById(R.id.drawer_cbox);
view.setTag(drawerHolder);
} else {
drawerHolder = (FilterDrawerItemHolder) view.getTag();
}
FilterDrawerItem dItem = (FilterDrawerItem) this.drawerItemList.get(position);
drawerHolder.ItemName.setText(dItem.getItemName());
TextView resetView = (TextView)view.findViewById(R.id.filterby_reset);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.drawer_cbox);
// Newly added code
Boolean isChecked = checked.get(position);
checkBox.setChecked(isChecked == null ? false : isChecked);
// if(application.getFilterStatus() != null) {
if(checkBox.isChecked()){
drawerHolder.checkBox.setChecked(false);
}
// }
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked) {
filterList.add(new Integer(position));
checked.put(position, true);
} else {
filterList.remove(new Integer(position));
checked.put(position, false);
}
}
});
drawerHolder.checkBox.setTag(position);
Log.d("FILTER_LIST_SIZE",String.valueOf(filterList.size()));
return view;
}
private static class FilterDrawerItemHolder {
TextView ItemName;
CheckBox checkBox;
}
public List<Integer> getFilterList(){
return filterList;
}
}
In the image below when I scroll the list and if i make the checkbox sample1 and sample 2 checked it becomes unchecked on scrolling.
and also on clicking reset button in the header i want all my checkbox to be unchecked..
Not able to get this working ...
UPDATE 1
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<FilterDrawerItem> adapterDataList = adapter.getDrawerItemList();
for(int i=0; i<adapterDataList.size(); i++){ // At this place i am getting the size as 9
adapterDataList.get(i).setCheckBoxId(false);
}
adapter.setDrawerItemList(adapterDataList);
adapter.notifyDataSetChanged();
}
});
In your FilterDrawerItem class, make a boolean variable isChecked.
Now in your adapter class, write something like this:
if(dItem.isChecked){
drawerHolder.checkBox.setChecked(true);
}
else{
drawerHolder.checkBox.setChecked(false);
}
and in your OnCheckedChangeListener:
if (isChecked) {
//your other code
dItem.setChecked(true);
notifyDataSetChanged();
} else {
//your other code
dItem.setChecked(false);
notifyDataSetChanged();
}
#Orest Savchak's answer is also right, but keeping track of checkboxes in your POJO classes will help you to retrieve the checked items later and also do other things easier, like you want to uncheck all the checkboxes on click of "Reset" button. For that, in onClick() on reset button, you'll just need to do:
for(int i=0; i<FilterDrawerItem.size; i++){
FilterDrawerItem.get(i).setChecked(false);
}
adapterObject.notifyDataSetChanged();
EDIT 1:
Create getter setter for drawerItemList in your adapter and then in onClick() of reset button, in place of dataList, do as following:
List<FilterDrawerItem> adapterDataList=adapter.getDataList();
for(int i=0; i<adapterDataList.size(); i++){
adapterDataList.get(i).setCheckBoxId(false);
}
adapter.setDataList(adapterDataList);
adapter.notifyDataSetChanged();
It because of recycling use of views in ListView. You should create some HashMap:
HashMap<Integer, Boolean> checked;
Then in your constructor do this:
checked = new HashMap<Integer, Boolean>(getCount());
After set OnCheckedChangeListener on your checkboxes, and in event method do this:
checked.put(position, yourCheckBoxCheckedState);
And in getView() method do this:
Boolean isChecked = checked.get(position);
checkBox.setChecked(isChecked == null ? false : isChecked)
Try this, I think it should help
UPDATE
resetBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.deselectAll();
}
});
Then in adapter create method:
public void deselectAll() {
checked = new HashMap<Integer, Boolean>(getCount());
notifyDataSetChanged();
}
Here is my requirement :
I'am loading one html file on to a WebView. I have a button in html file to select the date. When i click on that button i want to open android date picker dialog. And after selecting the date, i want to display the selected date in html file. Can anyone guide me. please.
HTML :
<input type="button" value="Select Date" onClick="openDatePickerDialog()" />
<p id = "date">--</p>
Javascript :
function openDatePickerDialog() {
AndroidFunction.openDatePickerDialog();
}
function callFromActivity(date) {
document.getElementById('date').innerHTML = date;
}
My Activity :
public class MainActivity extends Activity {
WebView myBrowser;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myBrowser = (WebView)findViewById(R.id.mybrowser);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/test.html");
}
public class MyJavaScriptInterface
{
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
Context mContext;
MyJavaScriptInterface(Context c)
{
mContext = c;
}
public void openDatePickerDialog()
{
Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//updateDisplay();
showDialog(DATE_DIALOG_ID);
}
private void updateDisplay() {
String date = new StringBuilder().append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" ").toString();
Toast.makeText(getApplicationContext(), date, Toast.LENGTH_LONG).show();
myBrowser.loadUrl("javascript:callFromActivity(\""+date+"\")");
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(MainActivity.this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
}
}
Problem : I'am not getting DatePicker Dialog When i click on button. Where i'am going wrong ? Is my approach correct ?
Here is a sample code I use do show, derived from the code here:
In the html code, add 2 javascript functions:
// Fonction d'appel calendrier Android
function f_CallCalendar(Tag)
{
MSSAndroidFunction.openDatePickerDialog(Tag);
}
// Fonction de retour de la date
function callFromActivity_RetDate(Tag, data) {
document.Form.vDate.value = data;
}
The Tag is the id of the input form to be completed. You call the javascript functions like this:
<input name="vDate" type="text" size="11" />
<input name="Submit" type="button" onclick="f_CallCalendar('vDate')" value="Calendrier*" />
And here is the java code implemented. Note that the MyJavaScriptInterface is declared inside the MainActivity:
public class MainActivity extends Activity
implements TextWatcher{
WebView MainWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainWebView = (WebView)findViewById(R.id.main_webview);
MainWebView.getSettings().setJavaScriptEnabled(true);
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
MainWebView.addJavascriptInterface(myJavaScriptInterface, "MyJavaScriptInterface");
}
// Classe de prise en charge du java privé
public class MyJavaScriptInterface
{
public String m_szTagId;
Context mContext;
MyJavaScriptInterface(Context c)
{
mContext = c;
}
public void openDatePickerDialog(String szTagId)
{
m_szTagId = szTagId;
Calendar c = Calendar.getInstance();
DatePickerDialog dp = new DatePickerDialog(mContext, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
String szDate = String.format("%02d/%02d/%04d", dayOfMonth, monthOfYear+1, year);
MainWebView.loadUrl("javascript:callFromActivity_RetDate(\""+m_szTagId+"\", \""+szDate+"\")");
} }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
dp.show();
}
} // Class MyJavaScriptInterface
} // class MainActivity
Here is it. Hope this can help.
public void openDatePickerDialog()
{
Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//updateDisplay();
DatePickerDialog dp = new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
dp.show();
}
can you try this once.