How can I show a DialogFragment from a BasePreferenceActivity? - android

I have a SettingsPreferenceActivity that Extends BasePreferenceActivity, and in that list of preferences I have an item called Upgrade. When clicking this upgrade item, I need to show a DialogFragment which is my upgrade screen. Here is the code I'm trying to use...
DialogFragment dialogFragment =
UpgradeDialogFragment.dialogWithEntry("leftMenuUpgrade");
dialogFragment.show(this.getSupportFragmentManager(), "purchase");
I'm getting an error saying "Cannot resolve method getSupportFragmentManager()".
I've tried using getFragmentManager() as well, and I get the same issue.
How can I show this DIalogFragment from my BasePreferenceActivity?
The old developers used this code...
Intent data = new Intent();
data.putExtra(EXTRA_UPGRADE, true);
setResult(RESULT_OK, data);
finish();
but it doesn't work. Nothing happens at all, so I'm trying to fix this for a client.
Full Activity...
package com.tp.activity;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceCategory;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.NavUtils;
import android.support.v4.app.FragmentManager;
import android.view.MenuItem;
import com.tp.Constants;
import com.tp.HubApplication;
import com.tp.MixpanelConstants;
import com.tp.R;
import com.tp.VariantConstants;
import com.tp.app.settings.ProfileActivity;
import com.tp.auth.Group;
import com.tp.auth.Session;
import com.tp.payment.PurchaseDialogFragment;
import com.tp.payment.UpgradeDialogFragment;
import com.tp.payment.UpgradePolicy;
import android.support.v4.app.DialogFragment;
import com.tp.payment.UpgradeDialogFragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.inject.Inject;
public class SettingsPreferenceActivity extends BasePreferenceActivity {
private static final String MANAGE_HUBS_KEY = "MANAGE_HUBS";
private static final String PROFILE_KEY = "PROFILE";
private static final String UPGRADE_KEY = "UPGRADE";
private static final String CALENDAR_KEY = "CALENDAR";
private static final String FEEDBACK_KEY = "FEEDBACK";
private static final String HELP_KEY = "HELP";
private static final int INTENT_SEND_FEEDBACK_REQUEST = 23986;
public static final String EXTRA_UPGRADE = "upgrade";
#Inject
Session mSession;
#Inject
UpgradePolicy mUpgradePolicy;
private HubApplication mApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mApp = (HubApplication) getApplication();
addPreferencesFromResource(R.xml.settings);
findPreference(PROFILE_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, ProfileActivity.class);
startActivity(intent);
return true;
}
});
if (mUpgradePolicy.shouldPromoteUpgrade()) {
findPreference(UPGRADE_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// Intent data = new Intent();
// data.putExtra(EXTRA_UPGRADE, true);
// setResult(RESULT_OK, data);
// finish();
DialogFragment dialogFragment =
UpgradeDialogFragment.dialogWithEntry("leftMenuUpgrade");
dialogFragment.show(getSupportFragmentManager(), EXTRA_UPGRADE);
return true;
}
});
} else {
findPreference(UPGRADE_KEY).setTitle("Upgraded");
}
findPreference(CALENDAR_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, CalendarSettingsActivity.class);
startActivity(intent);
return true;
}
});
findPreference(FEEDBACK_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
mApp.getMixPanel().track(MixpanelConstants.FEEDBACK_CLICKED, null);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{VariantConstants.FEEDBACK_EMAIL});
try {
startActivityForResult(intent, INTENT_SEND_FEEDBACK_REQUEST);
} catch (ActivityNotFoundException e) {
}
return true;
}
});
findPreference(HELP_KEY).setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, HelpActivity.class);
startActivity(intent);
return true;
}
});
getSupportActionBar().setTitle(R.string.settings_settings);
}
#Override
protected void onResume() {
super.onResume();
PreferenceCategory hubCategory = (PreferenceCategory) findPreference(MANAGE_HUBS_KEY);
hubCategory.removeAll();
List<Group> allGroups = new ArrayList<Group>(mSession.getGroups());
Collections.sort(allGroups, new Comparator<Group>() {
#Override
public int compare(Group lhs, Group rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
for (final Group group : allGroups) {
Preference groupPref = new Preference(this);
groupPref.setTitle(group.getName());
groupPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, GroupSettingsActivity.class);
intent.putExtra(Constants.ITEM_ID, group.getId());
startActivity(intent);
return true;
}
});
hubCategory.addPreference(groupPref);
}
Preference createHubPref = new Preference(this);
createHubPref.setTitle(R.string.settings_create_hub);
createHubPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsPreferenceActivity.this, AddGroupActivity.class);
startActivity(intent);
return true;
}
});
hubCategory.addPreference(createHubPref);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
finish();
return true;
default:
return super.onMenuItemSelected(featureId, item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == INTENT_SEND_FEEDBACK_REQUEST && resultCode == Activity.RESULT_OK) {
mApp.getMixPanel().track(MixpanelConstants.FEEDBACK_SENT, null);
}
}
}

Related

Get Acknowledge in Fragment from MainActivity, when my menu filter (sorting in MainActivity) is clicked

I have menu item in MainActivity it is filter(sort), I want that if user click on filter menu like A-z or z-a, in my MainActivity's onclick it is clicked but i want to get acknowledge in fragments as well
[nhewuhfduehiuhuewhucuewcueucueuncneincineincinencneincineinciniencineicnnecnnecneicniencnnecncncncnicnincincncnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnncncicieicieicicnicnncncicn]
code:
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Adapter.ViewPagerAdapter;
import com.tekitsolutions.remindme.Fragment.HomeFragment;
import com.tekitsolutions.remindme.Fragment.OfficeFragment;
import com.tekitsolutions.remindme.Fragment.OtherFragment;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Profile;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RemindMe;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Utils.CommonUtils.CREATE_PASSCODE_ACTIVITY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GET_PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IMAGE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_SEARCH;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.USERNAME;
public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, AdapterInterface, HamburgerMenuInterface, SearchListener, MenuItemListener {
private static final String TAG = MainActivity.class.getSimpleName();
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.recycler_view)
RecyclerView listView;
private String phoneNum = null, getImage = null, getUsername = null;
private int first = 0, position = 0;
private ActionBar actionBar;
private DatabaseAdapter dbAdapter;
private ReminderListAdapter listAdapter;
private List<Reminder> listItems = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private MenuItemListener searchListener;
private DrawerLayout drawer;
private SharedPreferences profilePreference;
private TextView navUsername, navMobile;
private ImageView navImage;
private View headerView;
private NavigationView navigationView;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
CREATE_PASSCODE_ACTIVITY = 0;
setThemeAndLoadLocale(MainActivity.this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
ButterKnife.bind(this);
setToolbar(toolbar, getString(R.string.app_name));
profilePreference = getSharedPreferences(PROFILE, MODE_PRIVATE);
getDataPhoneNumber();
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
navUsername = headerView.findViewById(R.id.profile_name);
navMobile = headerView.findViewById(R.id.mobile_number);
navImage = headerView.findViewById(R.id.profile_image);
if (!phoneNum.isEmpty()) {
first = 1;
getProfileData();
}
Menu menu = navigationView.getMenu();
MenuItem tools = menu.findItem(R.id.nav_general_setting);
SpannableString s = new SpannableString(tools.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s.length(), 0);
tools.setTitle(s);
Menu menu2 = navigationView.getMenu();
MenuItem tools2 = menu2.findItem(R.id.nav_communicate);
SpannableString s2 = new SpannableString(tools2.getTitle());
s2.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s2.length(), 0);
tools2.setTitle(s2);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new HomeFragment(), getResources().getString(R.string.fragment_home));
adapter.AddFragment(new OfficeFragment(), getResources().getString(R.string.fragment_office));
adapter.AddFragment(new OtherFragment(), getResources().getString(R.string.fragment_other));
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
listAdapter = new ReminderListAdapter(this, listItems, MainActivity.this, this, this);
listView.setHasFixedSize(true);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddReminderActivity.class));
}
});
dbAdapter = new DatabaseAdapter(this);
HomeFragment homeFragment = new HomeFragment();
homeFragment.setListener(this);
}
#Override
public void onClickFavoriteById(int isFavorite, long id) {
}
private void setData() {
if (getUsername != null && !getUsername.isEmpty()) {
navUsername.setText(getUsername.trim());
}
if (phoneNum != null && !phoneNum.isEmpty()) {
navMobile.setVisibility(View.VISIBLE);
navMobile.setText(phoneNum);
}
if (getImage != null && !getImage.isEmpty()) {
Bitmap bitmap = convertBase64ToBitMap(getImage);
navImage.setImageBitmap(bitmap);
} else {
navImage.setImageResource(R.drawable.user_image);
}
}
private void storeInSharedPreference() {
editor = getSharedPreferences(PROFILE, MODE_PRIVATE).edit();
editor.putString(USERNAME, getUsername);
editor.putString(IMAGE, getImage);
editor.apply();
}
private void getProfileData() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<List<Profile>> profileDetails = apiInterface.getProfileDetails(phoneNum);
profileDetails.enqueue(new Callback<List<Profile>>() {
#Override
public void onResponse(Call<List<Profile>> call, Response<List<Profile>> response) {
int statusCode = response.code();
if (statusCode == 200) {
List<Profile> responseList = response.body();
Profile profile = responseList.get(0);
showLog("username: " + profile.getProfileName());
getUsername = profile.getProfileName();
if (getUsername == null) {
showLog("Null");
} else {
showLog("Not null");
}
getImage = profile.getImage();
phoneNum = profile.getProfileNo();
setData();
storeInSharedPreference();
}
}
#Override
public void onFailure(Call<List<Profile>> call, Throwable t) {
showLog("Failed: " + t.getMessage());
}
});
}
private void getDataFromSharedPref() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
getUsername = profilePreference.getString(USERNAME, "");
getImage = profilePreference.getString(IMAGE, "");
}
private void getDataPhoneNumber() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Intent intent = null;
switch (item.getItemId()) {
case R.id.nav_profile:
intent = new Intent(this, ProfileActivity.class);
intent.putExtra(GET_PROFILE, true);
intent.putExtra(IMAGE, getImage);
intent.putExtra(USERNAME, getUsername);
startActivity(intent);
break;
case R.id.nav_favorite:
intent = new Intent(MainActivity.this, AddFavoriteReminder.class);
startActivity(intent);
break;
case R.id.nav_setting:
intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
break;
case R.id.nav_passcode:
intent = new Intent(this, PasscodeActivity.class);
startActivity(intent);
break;
case R.id.nav_share:
String link = "https://drive.google.com/drive/folders/1sDS_hGb5s5SjyDIK3me3oY8cS1Oo1I4F?usp=sharing";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
SpannableString ss = new SpannableString("Android is a Software stack");
String shareBodyText = link;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));
return true;
case R.id.nav_help:
intent = new Intent(MainActivity.this, HelpActivity.class);
startActivity(intent);
break;
case R.id.nav_feedback:
intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("message/rfc822");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"jimmytrivedi#outlook.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Remind Me Feedback");
intent.putExtra(Intent.EXTRA_TEXT, "Developer Team,");
try {
startActivity(Intent.createChooser(intent, "Send Email"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public void onClickReminderList(int position) {
}
private Bitmap convertBase64ToBitMap(String profileImage) {
try {
byte[] encodeByte = Base64.decode(profileImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch (Exception e) {
showLog("" + e.getMessage());
return null;
}
}
#Override
protected void onResume() {
super.onResume();
CREATE_PASSCODE_ACTIVITY = 0;
if (RemindMe.isChanged()) {
RemindMe.setChanged(false);
recreate();
}
getDataFromSharedPref();
setData();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.search:
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivityForResult(intent, PICK_SEARCH);
break;
case R.id.filter:
break;
case R.id.ascending:
position = 1;
break;
case R.id.descending:
position = 2;
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fragment_search, menu);
getMenuInflater().inflate(R.menu.menu_filter, menu);
return true;
}
#Override
public void onClickHamburger(long id) {
}
#Override
public void onClickListItem(int position) {
}
#Override
public void setToolbar(Toolbar toolBar, String title) {
super.setToolbar(toolBar, title);
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onSelectedProviderSearchItem(General general) {
}
#Override
public void onSelectedParticularPaymentSearchItem(ParticularPayment particularPayment) {
}
#Override
public void onSelectedReminderSearchItem(Reminder reminder) {
}
#Override
public void unused(int position) {
}
#Override
public void onFilterItem(int position) {
}
}
Interface
MenuItemListener
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
public interface MenuItemListener {
void onFilterItem(int position);
}
HomeFragment:
package com.tekitsolutions.remindme.Fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tekitsolutions.remindme.Activity.AddReminderActivity;
import com.tekitsolutions.remindme.Activity.MainActivity;
import com.tekitsolutions.remindme.Activity.ReminderDetailActivity;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Receiver.AlarmReceiver;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RecyclerViewClickListener;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_FAVORITE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_TYPE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.HOME;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IS_EDIT;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_HOME;
public class HomeFragment extends Fragment implements AdapterInterface, HamburgerMenuInterface, Callback<String>, SearchListener, MenuItemListener {
private static final String TAG = HomeFragment.class.getSimpleName();
public MainActivity activity;
public Context context;
View view;
private DatabaseAdapter dbAdapter;
private List<Reminder> listItems = new ArrayList<>();
private ReminderListAdapter listAdapter;
private MenuItemListener menuItemListener;
private RecyclerView listView;
private TextView tvNoData;
private AdapterInterface listener;
private HamburgerMenuInterface menuInterface;
private AlertDialog.Builder builder;
private Reminder reminder;
private long reminderId = 0;
private int getFavorite = 0;
public HomeFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = view.findViewById(R.id.recycler_view);
tvNoData = view.findViewById(R.id.tv_no_data);
dbAdapter = new DatabaseAdapter(getContext());
listAdapter = new ReminderListAdapter(getActivity(), listItems, HomeFragment.this, this, this);
listView.setHasFixedSize(false);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
listView.addOnItemTouchListener(new RecyclerViewClickListener.RecyclerTouchListener(getContext(),
listView, new RecyclerViewClickListener.ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}
));
loadAllReminders();
}
#Override
public void onStart() {
super.onStart();
loadAllReminders();
}
private void loadAllReminders() {
listItems.clear();
List<Reminder> list = dbAdapter.getReminderById(REMINDER_TYPE_ID, HOME);
if (list.size() > 0) {
tvNoData.setVisibility(View.GONE);
listItems.addAll(list);
listAdapter.notifyDataSetChanged();
} else {
tvNoData.setVisibility(View.VISIBLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.menuItemListener = (MenuItemListener) getActivity();
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onFilterItem(int position) {
showLog("test: " + position);
}
public void setListener(MenuItemListener listener) {
this.menuItemListener = listener;
}
}
You can do this with EventBus or Interface. You can follow these steps for EventBus.
Implement EventBus
implementation 'org.greenrobot:eventbus:3.1.1'
EventBustDataEvents.class
public class EventBusDataEvents{
public static class isClick {
boolean isClick;
public isClick(boolean isClick) {
this.isClick = isClick;
}
public boolean getIsClick() {
return isClick;
}
public void setIsClick(boolean isClick) {
this.isClick = isClick;
}
}
}
MainActivity.class
EventBus.getDefault().postSticky(new EventBusDataEvents.isClick(true));
Fragment.class
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void isClick(EventBusDataEvents.isClick click) {
if (click.isClick()) {
}
}
#Override
public void onStart() {
super.onStart();
try {
EventBus.getDefault().register(this);
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
EventBus.getDefault().unregister(this);
} catch (Exception e) {
}
}
Or Interface
IMainActivity.class // interface class
public interface IMainActivity {
void onClick();}
MainActivity.class
private IMainActivity listener; //This will be described above as a field.
public void setOnEventListener(IMainActivity listener) {
IMainActivity = listener;
}
//buttonClickEvent
listener.OnClick();
Fragment.class
//onCreateView
setOnEventListener(new IMainActivity() {
#Override
public void onClick() {
}
});

ListView displays data twice

I am working on a small application to save the data of the book (such as the name of the book, the type of the book, the author of the book and the year of publication) in a database, but when the data is returned from the databases using CursorLoader It's shown twice in ListView
This is a code of AddBook activity.
package training.android.com.librarycard;
import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
public class AddBook extends AppCompatActivity
implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_BOOK_LOADER = 0;
Spinner mBookType;
EditText mBookTitle, mBookAuthor, mBookPublishYear;
String bookType;
int position;
private boolean bookHasChanged = false;
private Uri currentBookUri;
private View.OnTouchListener touchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
bookHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Intent intent = getIntent();
if (intent != null) {
currentBookUri = intent.getData();
if (currentBookUri == null) {
setTitle("Add a book");
invalidateOptionsMenu();
} else {
setTitle("Edit a book");
getLoaderManager().initLoader(EXISTING_BOOK_LOADER, null, this);
}
}
mBookType = findViewById(R.id.spinner);
mBookTitle = findViewById(R.id.book_title);
mBookAuthor = findViewById(R.id.book_author);
mBookPublishYear = findViewById(R.id.publish_year);
mBookType.setOnTouchListener(touchListener);
mBookAuthor.setOnTouchListener(touchListener);
mBookTitle.setOnTouchListener(touchListener);
mBookPublishYear.setOnTouchListener(touchListener);
setupBookTypeSpinner();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (currentBookUri == null) {
MenuItem menuItem = menu.findItem(R.id.action_delete);
menuItem.setVisible(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_save:
setBook();
finish();
return true;
case R.id.action_delete:
showDeleteConfirmationDialog();
return true;
case android.R.id.home:
if (!bookHasChanged) {
NavUtils.navigateUpFromSameTask(AddBook.this);
return true;
}
DialogInterface.OnClickListener discardButtonClickListener
= new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
NavUtils.navigateUpFromSameTask(AddBook.this);
}
};
showUnsavedChangeDialog(discardButtonClickListener);
return true;
}
return super.onOptionsItemSelected(item);
}
private void showUnsavedChangeDialog(DialogInterface.OnClickListener discardButtonClickListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Discard your changes and quit editing?");
builder.setPositiveButton("Discard", discardButtonClickListener);
builder.setNegativeButton("Keep editing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showDeleteConfirmationDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete this book ?");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
deleteBook();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (dialog != null)
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void deleteBook() {
if (currentBookUri != null) {
int rowDeleted = getContentResolver().delete(currentBookUri, null, null);
if (rowDeleted == 0)
Toast.makeText(this, "Delete book failed", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Delete book successful", Toast.LENGTH_SHORT).show();
}
finish();
}
public void setupBookTypeSpinner() {
final ArrayAdapter<CharSequence> bookTypeAdapter = ArrayAdapter.createFromResource(
this, R.array.books_type, R.layout.support_simple_spinner_dropdown_item);
bookTypeAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mBookType.setAdapter(bookTypeAdapter);
mBookType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
bookType = parent.getSelectedItem().toString();
position = parent.getSelectedItemPosition();
Log.i("BookTypeSelection", bookType+"");
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setBook() {
String bookTitle = mBookTitle.getText().toString().trim();
String bookAuthor = mBookAuthor.getText().toString().trim();
String publishYear = mBookPublishYear.getText().toString().trim();
if (currentBookUri == null && TextUtils.isEmpty(bookTitle) && TextUtils.isEmpty(bookAuthor)
&& TextUtils.isEmpty(publishYear))
return;
Database database = new Database(this);
SQLiteDatabase db = database.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE, bookTitle);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR, bookAuthor);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR, publishYear);
values.put(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE, bookType);
if (currentBookUri == null) {
Uri uri = getContentResolver().insert(LibraryCardContract.LibraryCard.CONTENT_URI, values);
if (uri == null) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
} else {
int rowAffected = getContentResolver().update(currentBookUri, values, null, null);
if (rowAffected == 0) {
Toast.makeText(this, "Error with saving book", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Book saved", Toast.LENGTH_SHORT).show();
}
}
db.insert(LibraryCardContract.LibraryCard.TABLE_NAME, null, values);
Toast.makeText(this, "Insert new book", Toast.LENGTH_SHORT).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String [] projection = {
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR };
return new CursorLoader(this,currentBookUri,projection,
null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.moveToFirst()){
String title = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String publishYear = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = data.getString(
data.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
mBookTitle.setText(title);
mBookAuthor.setText(author);
mBookType.setSelection(position);
mBookPublishYear.setText(publishYear);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mBookTitle.setText("");
mBookType.setSelection(position);
mBookAuthor.setText("");
mBookPublishYear.setText("");
}
#Override
public void onBackPressed() {
if(!bookHasChanged){
super.onBackPressed();
return;
}
DialogInterface.OnClickListener discardButtonClickListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
};
showUnsavedChangeDialog(discardButtonClickListener);
}
}
And this is a code of Home activity that contains a listView to
display the data.
package training.android.com.librarycard;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import training.android.com.librarycard.Database.Database;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.Models.BookCursorAdapter;
import training.android.com.librarycard.Models.BookDetail;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final int BOOK_LOADER = 0;
private ListView mBookList;
private BookCursorAdapter cursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mBookList = findViewById(R.id.books_rv);
cursorAdapter = new BookCursorAdapter(this, null);
mBookList.setAdapter(cursorAdapter);
mBookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Home.this, AddBook.class);
Uri currentPetUri = ContentUris.withAppendedId(LibraryCardContract.LibraryCard.CONTENT_URI, id);
intent.setData(currentPetUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(BOOK_LOADER, null, this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), AddBook.class);
startActivity(intent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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, menu);
return true;
}
#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.
int id = item.getItemId();
switch (id) {
case R.id.delete_all_books:
deleteAllBooks();
return true;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
private void deleteAllBooks() {
int rowDeleted = getContentResolver().delete(LibraryCardContract.LibraryCard.CONTENT_URI,
null, null);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
LibraryCardContract.LibraryCard._ID,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR,
LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE,
LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR};
return new CursorLoader(this, LibraryCardContract.LibraryCard.CONTENT_URI,
projection,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
> This is a code of **BookCursorAdapter** class.
package training.android.com.librarycard.Models;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import training.android.com.librarycard.Database.LibraryCardContract;
import training.android.com.librarycard.R;
/**
* Created by Hassan on 4/9/2018.
*/
public class BookCursorAdapter extends CursorAdapter {
public BookCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context)
.inflate(R.layout.book_list,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView bookTitle = view.findViewById(R.id.book_name_tv);
TextView bookAuthor = view.findViewById(R.id.author_tv);
TextView bookType = view.findViewById(R.id.book_type_tv);
TextView publishYear = view.findViewById(R.id.publish_year_tv);
String title = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TITLE));
String type = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_TYPE));
String year = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_PUBLISH_YEAR));
String author = cursor.getString(
cursor.getColumnIndexOrThrow(LibraryCardContract.LibraryCard.COLUMN_BOOK_AUTHOR));
bookAuthor.setText(author);
bookTitle.setText(title);
bookType.setText(type);
publishYear.setText(year);
}
#Override
public int getCount() {
return super.getCount();
}
}
Screenshot of the application
enter image description here

Get single JSON value from response Retrofit

Im trying to get a single value from JSON using Retrofit, i followed a tutorial but i got an error saying that "Class anonymous class derived from Callback must be either declared ...." .
what im specifically trying to achieve is to echo a single json property value in a empty string like String Axe = ""; and i fill it with a specific value from the json file from the server. here is what i tried.
Json format
"axe1": {"test1"}
The ApiInterface
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
#GET("test.json")
Call<JsonObject> readJsonFromFileUri();
}
The MainActivity
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends ActionBarActivity {
DataBaseHandler db;
private AlertDialog dialog;
public static final int IntialQteOfDayId = 8;
private ImageView btn_quotes, btn_authors, btn_favorites, btn_categories, btn_qteday, btn_rateus ;
final Context context = this;
SharedPreferences preferences;
private static final int RESULT_SETTINGS = 1;
// URL of object to be parsed
// This string will hold the results
String data = "";
class Myads{
String bnr;
String intt;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://yourdomain.com/s/ ")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<JsonObject> jsonCall = apiInterface.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
JsonObject json = new JsonObject(body().toString());
Gson gson = new Gson();
Myads ad = gson.fromJson(jsonString, Myads.class);
Log.i(LOG_TAG, String.valueOf(ad.bnr));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
Typeface bold = Typeface.createFromAsset(getAssets(),
"fonts/extrabold.otf");
db = new DataBaseHandler(this);
db.openDataBase() ;
TextView cat = (TextView) findViewById(R.id.titlecat);
cat.setTypeface(bold);
TextView alls = (TextView) findViewById(R.id.titlest);
alls.setTypeface(bold);
TextView fav = (TextView) findViewById(R.id.titlefav);
fav.setTypeface(bold);
TextView qday = (TextView) findViewById(R.id.titleqday);
qday.setTypeface(bold);
TextView rate = (TextView) findViewById(R.id.titleqrate);
rate.setTypeface(bold);
btn_quotes = (ImageView) findViewById(R.id.btn_quotes);
//btn_authors= (Button) findViewById(R.id.btn_authors);
btn_categories = (ImageView) findViewById(R.id.btn_categories);
btn_favorites = (ImageView) findViewById(R.id.btn_favorites);
btn_qteday = (ImageView) findViewById(R.id.btn_qteday);
btn_rateus = (ImageView) findViewById(R.id.btn_rateus);
btn_quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("mode", "allQuotes");
startActivity(intent);
}
});
/*btn_authors.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent author = new Intent(MainActivity.this,
AuteursActivity.class);
startActivity(author);
}
});*/
btn_favorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent favorites = new Intent(MainActivity.this,
QuotesActivity.class);
favorites.putExtra("mode", "isFavorite");
startActivity(favorites);
}
});
btn_categories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent category = new Intent(MainActivity.this,
CategoryActivity.class);
startActivity(category);
}
});
btn_qteday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Intent qteDay = new Intent(MainActivity.this,
QuoteActivity.class);
qteDay.putExtra("id",
preferences.getInt("id", IntialQteOfDayId));
qteDay.putExtra("mode", "qteday");
startActivity(qteDay);
}
});
btn_rateus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage(getResources().getString(
R.string.ratethisapp_msg));
builder.setTitle(getResources().getString(
R.string.ratethisapp_title));
builder.setPositiveButton(
getResources().getString(R.string.rate_it),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Intent fire = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())); //dz.amine.thequotesgarden"));
startActivity(fire);
}
});
builder.setNegativeButton(
getResources().getString(R.string.cancel),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
});
}
#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) {
// 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_settings) {
Intent i = new Intent(this, UserSettingActivity.class);
startActivityForResult(i, RESULT_SETTINGS);
}
return super.onOptionsItemSelected(item);
}
}
So, i want the value of Json axe1 which is test1 to be parsed and put in into the empty string
You are using wrong import:
import com.android.volley.Response;
Replace it with
import retrofit2.Response;
Firstly, your JSON format is invalid, it should be {"axe1": "test1"}.
To store it you could do :
JSONObject json = new JSONObject(response.body().toString());
Log.i(LOG_TAG, json.getString("axe1"));

My ListView acitviity evrytime call previous arraylist when add new data in database

I create an activity thats populate from database and fill to ArrayList.
when add a new data in database and call listview activity thats change ArrayList to last with for example 6 and previous ArrayList with 5 item.
when i finish activity use below code:
Intent intent = new Intent(ListViewClass.this, AddClass.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
ListViewClass.this.onDestroy();
//NamayeshListYadavar.this.finish();
but when call ListViewClass thasts save previous ArrayList and new ArrayList and evrytime switch between two ArrayList.
When i debug my program show me 2 ArrayList with same name but different id and size.how to i can delete previous ArrayList when finish activity and call AddClass in my project?
Also i use
#Override
public void onDestroy() {
super.onDestroy();
Runtime.getRuntime().gc();
}
but in not work.
please help me friends.
and sorry for bad english.
This is all of my oncreate code
all of my code is :
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.blueprogrammers.utils.SomeUtils;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class NamayeshListYadavar extends HeaderFooter {
//AlarmData[] daro_data;
ArrayList<AlarmData> daro_data = new ArrayList<AlarmData>();
Handler mHandler = new Handler();
String myValue;
List<AlarmData> alarmList;
NamayeshListAdaptor adapter;
ListView list;
public String font1="byekan.ttf";
public String font2="BMitraBd.ttf";
private static final int RUN_EDIT = 1100;
/*** 0 for vibre 1 for melody and 2 for melody and vivre***/
int alarmtype = 2, vibre=0;
Boolean animlockBoolean=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup vg = (ViewGroup) findViewById(R.id.lldata);
ViewGroup.inflate(this, R.layout.yadavar_list, vg);
list = (ListView) findViewById(R.id.yadavar_listview);
createCollection();
adapter = new NamayeshListAdaptor(this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
TextView tv = (TextView) arg1.findViewById(R.id.txtid);
//String text = tv.getText().toString();
myValue = (String) tv.getText();
Intent intent = new Intent(NamayeshListYadavar.this, EditYadavar.class);
intent.putExtra("YADAVAR-ID", myValue);
startActivity(intent);
NamayeshListYadavar.this.finish();
//startActivityForResult(intent, RUN_EDIT);
}
});
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
new textSearh().execute();
}
}, 0, 500);
}
public void clickMe(View v){
switch (v.getId()) {
case R.id.txttarikhetmam:
break;
default:
break;
}
}
class textSearh extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
runOnUiThread(new Runnable() {
public void run() {
final SharedPreferences preferences = getSharedPreferences("DaroPref", 0);
final int del = preferences.getInt("delid", 9999);
Boolean checkBoolean =preferences.getBoolean("delbol", false);
if(checkBoolean){
Editor editor = preferences.edit();
editor.putBoolean("delbol", false);
editor.commit();
deleteView(del);
}
}
});
return null;
}
protected void onPostExecute(String file_url) {
}
}
private void createCollection() {
DatabaseHandler db= new DatabaseHandler(this);
alarmList = new ArrayList<AlarmData>();
alarmList = db.getViewAlarm("SELECT AlarmID, idDrug, alarmTime , nameYadavar, done, alarmDate FROM Alarm where done =0");
ArrayList<AlarmData> alarm_dat = new ArrayList<AlarmData>(alarmList);
this.daro_data=alarm_dat;
db.close();
}
public void deleteView(final int del){
createCollection2();
Animation anim = AnimationUtils.loadAnimation(
NamayeshListYadavar.this, android.R.anim.slide_out_right
);
try{
anim.setDuration(500);
list.getChildAt(del).startAnimation(anim );
new Handler().postDelayed(new Runnable() {
public void run() {
createCollection2();
adapter = new NamayeshListAdaptor(NamayeshListYadavar.this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
}
}, anim.getDuration());
}catch(Exception e){
e.printStackTrace();
}
}
public void btnbtnClick(View v)
{
switch (v.getId()) {
case R.id.btnadd:
Intent intent = new Intent(NamayeshListYadavar.this, TanzimSaat.class);
intent.putExtra("CLASS-TYPE", "NamayeshListYadavar");
startActivityForResult(intent, RUN_EDIT);
//startActivityForResult(intent, RUN_EDIT);
break;
case R.id.btnbar:
this.finish();
break;
default:
break;
}
}
#Override
public void onBackPressed() {
this.finish();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RUN_EDIT:
createCollection2();
adapter = new NamayeshListAdaptor(this,
R.layout.namayeshyadavar, daro_data);
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
break;
}
}
}
Finally i fixed problem by add below code
public void onBackPressed() {
timer.cancel();
this.finish();
}
Timer is my problem

can't override onContextItemSelected in Fragment

I'm trying to convert Activity to a fragment and can't override this methods : onCreateOptionsMenu,onOptionsItemSelected,onContextItemSelected.
,maybe some import statements are missing ? don't know what to do.Her is my Class file :
package com.wts.ui;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainFragment extends Fragment {
protected final static int REQUEST_CODE = 1;
public static WordsDBAdapter dbAdapter;
private CustomAdapter cDataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
// context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
private final static int IDM_INFO = 103;
// options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
private static final int IDM_SETTINGS = 203;
private static final int IDM_QUESTION = 204;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbAdapter = new WordsDBAdapter(getActivity());
dbAdapter.open();
displayListView();
registerForContextMenu(listView);
// ================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor) listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(WordsDBAdapter.ID_COL);
return false;
}
});
// ================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if (word.length() > 0 && translate.length() >= 0) {
Cursor cursor = dbAdapter.fetchWordsByName(word);// chek is
// word
// repeat
if (cursor.moveToFirst()) {
Toast.makeText(getActivity().getApplicationContext(),
getResources().getString(R.string.word_exist),
Toast.LENGTH_SHORT).show();
} else if (!CheckWordInput(word)
|| !CheckTranslateInput(translate)) {
Toast.makeText(
getActivity().getApplicationContext(),
getResources().getString(
R.string.incorrect_input),
Toast.LENGTH_SHORT).show();
} else {
dbAdapter.insertWord(word, translate, " ",
String.valueOf(false), 0, 0, new Date());
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
button = (Button) view.findViewById(R.id.buttonAddWord);
listView = (ListView) view.findViewById(R.id.listWords);
editWord = (EditText) view.findViewById(R.id.editWord);
editTranslate = (EditText) view.findViewById(R.id.editTranslate);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// setContentView(R.layout.activity_main);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_EDIT]);
menu.add(Menu.NONE, IDM_INFO, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_INFO]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_DELETE]);
}
}
//
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT: {
Intent intent = new Intent(getActivity(), EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(WordsDBAdapter.WORD_COL));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(WordsDBAdapter.TRANS_COL));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(WordsDBAdapter.DESC_COL));
startActivityForResult(intent, REQUEST_CODE);
}
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
case IDM_INFO: {
Intent intent = new Intent(getActivity(), InformationActivity.class);
for (int i = 1; i <= InformationActivity.nListItems; i++)
intent.putExtra(String.valueOf(i), cursor.getString(i));
startActivity(intent);
}
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
private void displayListView() {
// Cursor cursor = dbAdapter.fetchAllTranslated();
Cursor cursor = dbAdapter.fetchAllTranslated();
String[] columns = new String[] { WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION, WordsDBAdapter.KEY_SUCCEEDED, };
int[] to = new int[] { R.id.textViewTranslate, R.id.textViewWord,
R.id.textViewSuccessPoints };
cDataAdapter = new CustomAdapter(getActivity(), R.layout.word_info,
cursor, columns, to);
listView.setAdapter(cDataAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_ABOUT: {
Intent intent = new Intent(getActivity(), AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT: {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
break;
}
case IDM_SETTINGS: {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
break;
}
case IDM_QUESTION: {
if (!StartActivity.isMainActivitySart)
getActivity().onBackPressed();
else {
Intent intent = new Intent(getActivity(),
QuestionActivity.class);
startActivity(intent);
}
}
break;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
if (intent.hasExtra(getResources().getString(R.string.fstRow))) {
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(
getResources().getString(R.string.fstRow)),
intent.getExtras().getString(
getResources().getString(R.string.scndRow)),
intent.getExtras().getString(
getResources().getString(R.string.thrdRow)),
null, null, null, null);
displayListView();
}
}
}
#Override
public void onResume() {
super.onResume();
SettingsManager.setPreferedLanguage(getActivity());// set language
displayListView();
}
public static boolean CheckTranslateInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{0,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
public static boolean CheckWordInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{1,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
#Override
public void onDetach() {
super.onDetach();
dbAdapter.close();
}
}
You have to think about what you want your Fragment to be - Fragment or SherlockFragment?
You import this:
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
And so, your overrides aren't overrides because Menu & friends are different classes right now than what Fragment needs - they are ActionBarSherlock's classes.
If you extend SherlockFragment instead, your overrides should work, and it is recommended to extend SherlockFragment if you are using ActionBarSherlock (which based on your tags, you are).
If you want to keep this as a regular fragment, then import:
android.view.Menu
android.view.MenuItem
android.view.MenuInflater

Categories

Resources