Related
Everything works fine, except that when I try to search on my app, it crashes. The problem is in the method onQueryTextChange, please help me to fix it:
MainActivity
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, SearchView.OnQueryTextListener {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
private static final int REQUEST_CAMERA_PERMISSION = 200;
Button goSettings;
ListView listApps;
Context context;
Button go_AndroBooster,goPerms,lockAll,unlockAll,goLogs;
Intent i;
private AccountHeader headerResult = null;
private Drawer result = null;
private MiniDrawer miniResult = null;
private CrossfadeDrawerLayout crossfadeDrawerLayout = null;
MaterialProgressBar loadingBar;
ColorManager colorManager;
RelativeLayout mainLayout;
ArrayList<ApplicationInfo> items;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
colorManager = new ColorManager(this);
setSupportActionBar(toolbar);
mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);
packageManager = getPackageManager();
listApps = (ListView) findViewById(R.id.listApps);
go_AndroBooster = (Button) findViewById(R.id.go_booster);
goPerms = (Button) findViewById(R.id.goPerms);
lockAll = (Button) findViewById(R.id.lock_all);
unlockAll = (Button) findViewById(R.id.unlock_all);
loadingBar = (MaterialProgressBar) findViewById(R.id.loadingBar);
goLogs = (Button) findViewById(R.id.goLogs);
goSettings = (Button) findViewById(R.id.lockSettings);
listApps.setItemsCanFocus(true);
startLockService();
setSupportActionBar(toolbar);
//set the back arrow in the toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#25517d")));
final IProfile profile2 = new ProfileDrawerItem().withIcon(R.drawable.user_icon);
// Create the AccountHeader
headerResult = new AccountHeaderBuilder()
.withActivity(this)
.withTranslucentStatusBar(false)
.withHeaderBackground(R.drawable.header)
.addProfiles(profile2)
.build();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
result = new DrawerBuilder()
.withActivity(this)
.withToolbar(toolbar)
.withDrawerLayout(R.layout.crossfade_material_drawer)
.withHasStableIds(true)
.withDrawerWidthDp(72)
.withGenerateMiniDrawer(true)
.withAccountHeader(headerResult) //set the AccountHeader we created earlier for the header
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.Home).withIcon(R.drawable.homee).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.logs).withIcon(R.drawable.cleanapp).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.resetpass).withIcon(R.drawable.boost).withIdentifier(3),
new PrimaryDrawerItem().withName(R.string.language).withIcon(R.drawable.share).withIdentifier(4),
new PrimaryDrawerItem().withName(R.string.share).withIcon(R.drawable.rate).withIdentifier(6),
new PrimaryDrawerItem().withName(R.string.rate).withIcon(R.drawable.rate).withIdentifier(7)
// new DividerDrawerItem(),
// new SecondaryDrawerItem().withName(R.string.drawer_item_seventh).withIcon(FontAwesome.Icon.faw_github).withIdentifier(7).withSelectable(false)
) // add the items we want to use with our Drawer
.withSelectedItemByPosition(1)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (drawerItem.getIdentifier() == 1) {
// Toast.makeText(MainActivity.this,"2",Toast.LENGTH_LONG).show();
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 2) {
i = new Intent(getApplicationContext(), LogsActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 3) {
i = new Intent(getApplicationContext(), SetLockTypeActivity.class);
startActivity(i);
result.closeDrawer();
} else if (drawerItem.getIdentifier() == 4) {
LanguagesDialog languagesDialog = new LanguagesDialog();
languagesDialog.show(getFragmentManager(), "LanguagesDialogFragment");
} else if (drawerItem.getIdentifier() == 6) {
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "http://play.google.com/store/apps/details?id="
+ getPackageName());
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(sharingIntent, getResources().getText(R.string.shareusing)));
result.closeDrawer();
}else if (drawerItem.getIdentifier() == 7) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id="
+ getPackageName()));
startActivity(browserIntent);
result.closeDrawer();
}
//
//
return false;
}
})
.withSavedInstance(savedInstanceState)
.withShowDrawerOnFirstLaunch(false)
.build();
//get out our drawerLyout
crossfadeDrawerLayout = (CrossfadeDrawerLayout) result.getDrawerLayout();
//define maxDrawerWidth
crossfadeDrawerLayout.setMaxWidthPx(DrawerUIUtils.getOptimalDrawerWidth(this));
//add second view (which is the miniDrawer)
MiniDrawer miniResult = result.getMiniDrawer();
//build the view for the MiniDrawer
View view = miniResult.build(this);
//set the background of the MiniDrawer as this would be transparent
view.setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(this, com.mikepenz.materialdrawer.R.attr.material_drawer_background, com.mikepenz.materialdrawer.R.color.material_drawer_background));
//we do not have the MiniDrawer view during CrossfadeDrawerLayout creation so we will add it here
crossfadeDrawerLayout.getSmallView().addView(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//define the crossfader to be used with the miniDrawer. This is required to be able to automatically toggle open / close
miniResult.withCrossFader(new ICrossfader() {
#Override
public void crossfade() {
boolean isFaded = isCrossfaded();
crossfadeDrawerLayout.crossfade(400);
//only close the drawer if we were already faded and want to close it now
if (isFaded) {
result.getDrawerLayout().closeDrawer(GravityCompat.START);
}
}
#Override
public boolean isCrossfaded() {
return crossfadeDrawerLayout.isCrossfaded();
}
});
//hook to the crossfade event
crossfadeDrawerLayout.withCrossfadeListener(new CrossfadeDrawerLayout.CrossfadeListener() {
#Override
public void onCrossfade(View containerView, float currentSlidePercentage, int slideOffset) {
Log.e("CrossfadeDrawerLayout", "crossfade: " + currentSlidePercentage + " - " + slideOffset);
}
});
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startReqUsageStat();
}
}, 3000);
lockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.lockAllApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
unlockAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ManageLockedApps.resetLockedApps(context);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 2000);
}
});
goPerms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, RequestPermission.class);
startActivity(i);
}
});
goLogs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, LogsActivity.class);
startActivity(i);
}
});
go_AndroBooster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startApplication("");
}
});
goSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(i);
finish();
}
});
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
new LoadApplications().execute();
}
}, 1500);
new Thread(new Runnable() {
#Override
public void run() {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
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();
return super.onOptionsItemSelected(item);
}
private void startLockService() {
if (!isMyServiceRunning(LockService.class)){
context.startService(new Intent(context, LockService.class));
}
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
private void startReqUsageStat(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
if (!checkUsageStatsPermission()){
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
Toast.makeText(context,getString(R.string.please_give_usage_Stats),Toast.LENGTH_LONG).show();
}
}
} public boolean checkUsageStatsPermission(){
final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
final List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0, System.currentTimeMillis());
return !queryUsageStats.isEmpty();
}
public void startApplication(String packageName)
{
try
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info : resolveInfoList)
if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
{
launchComponent(info.activityInfo.packageName, info.activityInfo.name);
return;
}
showInMarket(packageName);
}
catch (Exception e)
{
showInMarket(packageName);
}
}
public String getPattern() {
File file = new File("/data/data/com.project.applocker/files/pattern");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
} catch (IOException e) {
Log.d("okuma hatası", "no 1");
}
return text.toString();
}
private void launchComponent(String packageName, String name)
{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setComponent(new ComponentName(packageName, name));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void showInMarket(String packageName)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final List<ApplicationInfo> appsList = context.getPackageManager().getInstalledApplications(0);
final ApplicationInfo data = appsList.get(i);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.performClick();
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
private class LoadApplications extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(MainActivity.this,
R.layout.app_list_item, applist);
if(!isMyServiceRunning(LockService.class)){
startLockService();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
listApps.setAdapter(listadaptor);
listApps.setOnItemClickListener(MainActivity.this);
loadingBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
loadingBar.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
String[] alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
startLockService();
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (!info.packageName.equals("com.google.android.googlequicksearchbox")) {
if (!info.packageName.equals("com.project.applocker")) {
if (!info.packageName.contains("launcher3")) {
if (!info.packageName.contains("launcher")) {//com.google.android.googlequicksearchbox
if (!info.packageName.contains("trebuchet")) {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
}
Adapter
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo>{
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
List<String> allAppList = null;
List<String> lockedAppList = null;
ColorManager colorManager;
SharedPreferences preferences;
SharedPreferences.Editor editor;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appList) {
super(context, textViewResourceId, appList);
this.context = context;
allAppList = new ArrayList<String>();
colorManager = new ColorManager(context);
lockedAppList = new ArrayList<String>();
this.appsList = appList;
packageManager = context.getPackageManager();
preferences=context.getSharedPreferences("chosen_apps", context.MODE_PRIVATE);
Collections.sort(appsList, new ApplicationInfo.DisplayNameComparator(packageManager));
editor = preferences.edit();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.app_list_item, null);
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
CardView cardViewApps = (CardView) view.findViewById(R.id.cardViewApps);
final SwitchCompat lockApp = (SwitchCompat) view.findViewById(R.id.lockApp);
lockApp.setText(data.loadLabel(packageManager));
iconview.setImageDrawable(data.loadIcon(packageManager));
if(preferences.getBoolean(data.packageName,false)){
lockApp.setChecked(true);
}
else{
lockApp.setChecked(false);
}
lockApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
context.stopService(new Intent(context, LockService.class));
if (lockApp.isChecked()){
Log.d("tıklanmış",""+data.packageName);
editor.putBoolean(data.packageName,true).apply();
}
if (!lockApp.isChecked()){
Log.d("silinmiş",""+data.packageName);
editor.putBoolean(data.packageName,false).apply();
}
context.startService(new Intent(context, LockService.class));
}
});
}
return view;
}
private void startLockService() {
context.startService(new Intent(context, LockService.class));
}
private void stopLockService() {
context.stopService(new Intent(context, LockService.class));
}
}
The problem is here:
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,applist);
listApps.setAdapter(adapter);
return true;
}
return true;
};
I think your method should be like below
#Override
public boolean onQueryTextChange(String newText) {
ArrayList<ApplicationInfo> templist = new ArrayList<>();
for (ApplicationInfo temp : items){
if (temp.toString().contains(newText.toLowerCase())){
templist.add(temp);
}
}
if(templist != null && templist.size() > 0){}
ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,templist);
listApps.setAdapter(adapter);
}else{
listApps.setAdapter(null);
}
return true;
};
In my application I am about to refresh the current viewed fragment after searching an item from API. My search bar is coming from Fragment activity and, when the result is there, it will be viewed in the second fragment, but the problem is, when I click search, it will reset into the 1st fragment.
Here's my code:
private ViewPager mPager;
private MyPagerAdapter mAdapter;
ImageView settings_btn;
EditText search;
//EditText search;
ImageView community_icon;
ImageView loyalty_icon;
ImageView tokens_icon;
Context context;
public CustomerAccount customerAccount;
private MyPagerAdapter pagerAdapter;
String offer = "cheese";
ProgressDialog progressDialog;
CustomListAdapterMerchant adapter;
String searchname;
ArrayList<RowItemMerchant> rowItem;
JSONObject offerlist;
int i;
JSONObject merchantList;
RowItemMerchant items;
ListView listView;
Bundle extras;
String empty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
if(savedInstanceState != null){
search.setText(savedInstanceState.getString("Key"));
}
search = (EditText) findViewById(R.id.searchView);
search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
ConstantSearch.SEARCHNAME = search.getText().toString();
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.d("SearchName",ConstantSearch.SEARCHNAME);
return true;
}
return false;
}
});
search.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// You can identify which key pressed buy checking keyCode value
// with KeyEvent.KEYCODE_
if (keyCode == KeyEvent.KEYCODE_DEL) {
ConstantSearch.SEARCHNAME = "";
Intent intent = getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("IPUTTEDMERCHANT", ConstantSearch.SEARCHNAME);
finish();
startActivity(intent);
Log.e("IME_TEST", "DEL KEY");
}
return false;
}
});
Intent intent = getIntent();
Bundle bd = intent.getExtras();
if(bd != null) {
String getName = (String) bd.get("IPUTTEDMERCHANT");
search.setText(getName);
}
LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!enabled) {
showDialogGPS();
}
mAdapter = new MyPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(mAdapter);
final TextView ref1= (TextView) findViewById(R.id.ref1);
final TextView ref2= (TextView) findViewById(R.id.ref2);
final TextView ref3= (TextView) findViewById(R.id.ref);
final ImageView Image1 = (ImageView) findViewById(R.id.image1);
final ImageView Image2 = (ImageView) findViewById(R.id.image2);
final ImageView Image3 = (ImageView) findViewById(R.id.image3);
settings_btn = (ImageView) findViewById(R.id.settings_button);
settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent settings = new Intent(DashboardActivity.this, SettingsPromotion.class);
startActivity(settings);
}
});
ref1.setTextColor(ContextCompat.getColor(this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
ref1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(0);
setToDefault();
ref1.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image1.setImageResource(R.drawable.ic_community_on);
}
});
loyalty.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(1);
setToDefault();
ref2.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image2.setImageResource(R.drawable.ic_loyalty_on);
}
});
tokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setCurrentItem(2);
setToDefault();
ref3.setTextColor(ContextCompat.getColor(DashboardActivity.this, R.color.orange));
Image3.setImageResource(R.drawable.ic_tokens_on);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);{
String savedText = search.getText().toString();
savedInstanceState.putString("Key", savedText);
}
}
private void showDialogGPS() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Allow \"My App\" to access you location while you use tha app?");
builder.setMessage("My App uses this to help customers find places. connect with merchants and more");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(
new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void setToDefault()
{
TextView ref1 = (TextView) findViewById(R.id.ref1);
TextView ref2 = (TextView) findViewById(R.id.ref2);
TextView ref3 = (TextView) findViewById(R.id.ref3);
ImageView Image1 = (ImageView) findViewById(R.id.image1);
ImageView Image2 = (ImageView) findViewById(R.id.image2);
ImageView Image3 = (ImageView) findViewById(R.id.image3);
ref1.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image1.setImageResource(R.drawable.ic_community_off);
ref2.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image2.setImageResource(R.drawable.ic_loyalty_off);
ref3.setTextColor(ContextCompat.getColor(this, R.color.blackColor));
Image3.setImageResource(R.drawable.ic_tokens_off);
}
public static class MyPagerAdapter extends FragmentPagerAdapter
{
private static final int NUM_ITEMS = 3;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private FragmentOne fragmentOne;
private FragmentTwo fragmentTwo;
private FragmentThree fragmentThree;
public MyPagerAdapter(FragmentManager fm)
{
super(fm);
mFragmentTags = new HashMap<Integer, String>();
fragmentOne = new FragmentOne();
fragmentTwo = new FragmentTwo();
fragmentThree = new FragmentThree();
}
#Override
public int getCount()
{
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position)
{
if (position == 0)
{
return fragmentOne;
}
else if (position == 1)
{
return fragmentTwo;
}
else if (position == 2)
{
return fragmentThree;
}
else
{
Log.e("AuthActivity", "ViewPager invalid position");
return null;
}
}
}
I am making dictionary app having sound sample, when an item in the list is click, a new activity will open containing details view and a button. Can someone help me how can I assign the specific sound to the button. The sound files are placed in raw folder. for example, I click the item 'araw',the details will show and the button must play the sound araw...Pls help me...
heres the codes:
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
DefinitionActivity.java
public class DefinitionActivity extends AppCompatActivity {
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
int[] sounds = new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
Button play = (Button) findViewById(R.id.playbty);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
}
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I do not know how to play the audio when button click
}
});
}
}
Like Pedif said, you should use SoundPool for playing short sounds.
Here is Code from my Tetris like game, the Activity creates the Instance and get a callback when sounds were loaded.
Example as Singleton:
public class Sounds {
private Context ctx;
private static Sounds mSounds = null;
private static SoundPool mSPool = null;
private int sound_gameover;
private int sound_teil_drehen;
private int sound_1_zeile;
private int sound_2_zeile;
private int sound_3_zeile;
private int sound_4_zeile;
private int soundsToLoad = 6;
/**
* Volumecontrol
*/
private AudioManager audioManager;
private float actualVolume;
private float maxVolume;
private float volume;
private IOnSoundReady callback = null;
public static Sounds getInstance(Context ctx, IOnSoundReady mCallback){
if(mSPool == null){
mSounds = new Sounds(ctx, mCallback);
}
return mSounds;
}
private Sounds(Context ctx, IOnSoundReady mIOSoundReady) {
this.ctx = ctx;
this.callback = mIOSoundReady;
initVolume();
AsyncTask<Void, Void, Void> mTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
initSoundPool();
return null;
}
};
mTask.execute();
}
public void unprepare() {
if (mSPool == null) return;
mSPool.release();
mSPool = null;
}
private void initSoundPool(){
mSPool = new SoundPool(6, AudioManager.STREAM_MUSIC, 0);
mSPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
Log.w(TAG, "loaded soundid: " + sampleId);
if(--soundsToLoad == 0 && callback != null){
callback.onSoundReady();
}
}
});
sound_gameover = mSPool.load(ctx, R.raw.game_over, 1);
sound_teil_drehen = mSPool.load(ctx, R.raw.rotate, 1);
sound_1_zeile = mSPool.load(ctx, R.raw.line_1,1);
sound_2_zeile = mSPool.load(ctx, R.raw.line_2, 1);
sound_3_zeile = mSPool.load(ctx, R.raw.line_3, 1);
sound_4_zeile = mSPool.load(ctx, R.raw.line_4, 1);
}
/**
* calculate volume
*/
private void initVolume(){
audioManager = (AudioManager) ctx.getSystemService(SpielActivity.AUDIO_SERVICE);
actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
volume = actualVolume / maxVolume;
}
/**
* plays a sound
* #param soundid
*/
public void playSound(int soundid){
mSPool.play(soundid, volume, volume,1, 0, 1f);
}
}
Interface used when sounds are loaded, implemented by activity:
public interface IOnSoundReady {
void onSoundReady();
}
Usage in your activity:
Sounds mySounds = Sounds.getInstance(this, this);
Play sound:
public static void playSound(int soundid) {
mySounds.playSound(soundid);
}
Hope I could help a bit.
// Try this way
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
// put position of the file
intent.putExtra("position", position);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
// DictionaryActivity.class
public class DefinitionActivity extends AppCompatActivity {
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
int[] sounds = new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
private int songPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
Button play = (Button) findViewById(R.id.playbty);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
songPosition = extras.getInt("position");
}
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Play it here like
MediaPlayer mediaPlayer=MediaPlayer.create(DictionaryActivity.class,sounds[position]);
mediaPlayer.start();
}
});
}
}
You have to use SoundPool.
For sound effects which are short you would use SoundPool otherwise you should use MediaPlayer.
The Reason is the interstitial ad is on wrong way.
Can someone tell me Is there a problem with my interstitial?
Where to put it?
My code from where interstitial is:
public class ActivityMain extends Activity implements OnItemClickListener,
onWelComeButtonClickListener, OnClickListener {
MatrixCursor cursor;
ActionBar actionBar;
DrawerLayout dLayout;
ListView channelListView;
ChannelCustomAdapter adapter;
ActionBarDrawerToggle toggle;
CharSequence title;
Bundle bundle;
Menu menu;
RelativeLayout rlDrawerOpen;
Typeface selectFonts;
TextView tFacebook, tRateus;
AdRequest fullScreenAdRequest;
InterstitialAd fullScreenAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializer();
dLayout.setDrawerListener(toggle);
channelListView.setOnItemClickListener(this);
tFacebook.setOnClickListener(this);
tRateus.setOnClickListener(this);
enableAd();
}
private void enableAd() {
// adding full screen add
fullScreenAdd = new InterstitialAd(this);
fullScreenAdd.setAdUnitId("a151b7d316a5c1d");
fullScreenAdRequest = new AdRequest.Builder().build();
fullScreenAdd.loadAd(fullScreenAdRequest);
fullScreenAdd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.i("FullScreenAdd", "Loaded successfully");
fullScreenAdd.show();
}
#Override
public void onAdFailedToLoad(int errorCode) {
Log.i("FullScreenAdd", "failed to Load");
}
});
}
private void initializer() {
actionBar = getActionBar();
selectFonts = (Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Bold.ttf"));
dLayout = (DrawerLayout) findViewById(R.id.dl_drawerLayout);
rlDrawerOpen = (RelativeLayout) findViewById(R.id.rl_drawer_open);
channelListView = (ListView) findViewById(R.id.lv_channel_List);
title = getResources().getString(R.string.app_name);
tFacebook = (TextView) findViewById(R.id.tvFacbook);
tRateus = (TextView) findViewById(R.id.tvRateUs);
adapter = new ChannelCustomAdapter(this, GlobalData.getInstance()
.getArrChannels());
channelListView.setAdapter(adapter);
toggle = new ActionBarDrawerToggle(this, dLayout, R.drawable.ic_drawer,
R.string.app_name, R.string.app_name) {
#Override
public void onDrawerOpened(View drawerView) {
setTitle("Select Channel");
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
setTitle(title);
invalidateOptionsMenu();
}
};
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
// use the query to search your data somehow
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_LONG)
.show();
} else {
fragmentSelector();
}
}
private void fragmentSelector() {
bundle = getIntent().getBundleExtra("BUNDLE");
if (bundle == null) {
Fragment fr = new WelcomeFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
setTitle(title);
((WelcomeFragment) fr).setOnWelComeButtonClickListener(this);
} else {
selectItem(bundle.getInt("POS"));
setTitle(bundle.getString("NAME"));
}
}
public void selectItem(int position) {
Fragment fr = new RadioFragment();
bundle = new Bundle();
bundle.putString("URL",
GlobalData.getInstance().getArrChannels().get(position)
.getUrl());
bundle.putString("NAME",
GlobalData.getInstance().getArrChannels().get(position)
.getChannelName());
bundle.putInt("POS", position);
fr.setArguments(bundle);
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.fl_content, fr).commit();
title = GlobalData.getInstance().getArrChannels().get(position)
.getChannelName();
dLayout.closeDrawer(rlDrawerOpen);
}
#Override
public void setTitle(CharSequence title) {
actionBar.setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
final SearchView searchView = (SearchView) menu.findItem(R.id.search)
.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (getPositionfromString(query) != -1) {
Intent intent = new Intent(ActivityMain.this,
RadioService.class);
stopService(intent);
selectItem(getPositionfromString(query));
setTitle(query);
} else {
Toast.makeText(getApplicationContext(), "No channel found",
Toast.LENGTH_LONG).show();
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
String[] columnNames = {
"_id", "text"
};
cursor = new MatrixCursor(columnNames);
String[] temp = new String[2];
// int id = 0;
for (int i = 0; i < GlobalData.getInstance().getArrChannels()
.size(); i++) {
if (GlobalData.getInstance().getArrChannels().get(i)
.getChannelName().toLowerCase()
.contains(newText.toLowerCase())) {
temp[0] = Integer.toString(i);
temp[1] = GlobalData.getInstance().getArrChannels()
.get(i).getChannelName();
cursor.addRow(temp);
}
}
String[] from = {
"text"
};
int[] to = {
R.id.text
};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(
ActivityMain.this, R.layout.search_item, cursor, from,
to, SimpleCursorAdapter.NO_SELECTION);
searchView.setSuggestionsAdapter(cursorAdapter);
return true;
}
});
searchView.setOnSuggestionListener(new OnSuggestionListener() {
#Override
public boolean onSuggestionSelect(int position) {
return false;
}
#Override
public boolean onSuggestionClick(int position) {
cursor.moveToPosition(position);
searchView.setQuery(cursor.getString(1), true);
return false;
}
});
return true;
}
private int getPositionfromString(String chn) {
for (int i = 0; i < GlobalData.getInstance().getArrChannels().size(); i++) {
if (chn.contentEquals(GlobalData.getInstance().getArrChannels()
.get(i).getChannelName())) {
return i;
}
}
return -1;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (toggle.onOptionsItemSelected(item)) return true;
if (item.getItemId() == R.id.search) return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.search).setVisible(!dLayout.isDrawerOpen(rlDrawerOpen));
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onItemClick(AdapterView <? > parent, View view, int position,
long id) {
Intent intent = new Intent(ActivityMain.this, RadioService.class);
stopService(intent);
selectItem(position);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onWelComeButtonClick() {
dLayout.openDrawer(rlDrawerOpen);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvFacbook:
Intent i = new Intent(ActivityMain.this, ShowFacebook.class);
startActivity(i);
break;
case R.id.tvRateUs:
String linkurl = "http://play.google.com/store/apps/details?id=com.global.danceradio";
if (linkurl != null) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_TEXT, linkurl);
shareIntent.setType("text/plain");
startActivity(shareIntent);
} else {
Toast.makeText(getApplicationContext(), "Sharing failed...",
Toast.LENGTH_LONG).show();
}
break;
}
}
}
Here, everything looks normal. But there is no the rest of the code. Maybe you create an activity every second.
I would recommend you to write in support of the admob and clarify the issues. Maybe you're lucky and they will unblock you.
https://support.google.com/admob/answer/6201362?hl=en
Check admob support. they updated new photos for better explanation.
I'm developing an android kind-of-gallery-app with Firebase, so I will have plenty of images. I know that I need to be careful about memory management.
When I was searching how to find memory leak in android apps, I came across with LeakCanary. It looks really great, so I used in my app.
Basically my app has 3 fragments, which are Drawer, ProductGrid and ProductDetail. Sometimes LeakCanary says that I have a memory leak in ProductGrid, but I couldn't find it! Usually, adapters or static methods or listeners could cause memory leak because of Context object, but my knowledge is not sufficient to say 'aah that's because of here'
Here are the classes. Where is the leak?(If you suggest me anything that I can improve my code or approach, I would be appreciated!)
Because of body character limit, I put the link leak canary log file.
How I suspect there is a memory leak
First of all, LeakCanary shows a dialog and logs the dump. Second thing is, when I click on an item in drawer, in grid and in detail like 15 times(respectively), memory usage increases. It starts with 18M, increases 22M-23M after showing 3 images(normal). Then it heads up to 29M-30M after clicking on 15 times. If you click on around 30-40, memory usage increases 34M-35M
Edit: I've just figured out that, if I open and close drawer, memory usage increases 0.05M everytime, so one time opening and closing drawer costs 0.1M! What am i missing?
Main.java
public class Main extends ActionBarActivity implements DrawerListener {
private Toolbar mToolbar;
private Drawer drawerFragment;
private HomePage homeFragment;
private FragmentHelper fh = new FragmentHelper();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (homeFragment == null)
homeFragment = new HomePage();
if (savedInstanceState == null) {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (Drawer)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
drawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
drawerFragment.setRetainInstance(true);
displayView(null);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_home) {
getSupportActionBar().setTitle(getString(R.string.app_name));
fh.replace(getSupportFragmentManager(), homeFragment, R.id.container_body);
return true;
}
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position, Category category) {
displayView(category);
}
private void displayView(Category category) {
if (category != null) {
getSupportActionBar().setTitle(category.getName());
ProductGrid gridFragment = new ProductGrid();
Bundle args = new Bundle();
args.putString(Product.CATEGORY_ID, category.getId());
gridFragment.setArguments(args);
fh.replace(getSupportFragmentManager(), gridFragment, R.id.container_body);
} else {
getSupportActionBar().setTitle(getString(R.string.app_name));
fh.replace(getSupportFragmentManager(), homeFragment, R.id.container_body);
}
}
}
Drawer.java
public class Drawer extends Fragment {
private Firebase mFirebase;
private Alert alert;
private RecyclerView recyclerView;
private View containerView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerListener drawerListener;
private DrawerAdapter mAdapter;
private List<Category> mCategories;
public Drawer() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
alert = new Alert(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.drawer, container, false);
mCategories = new ArrayList<>();
mAdapter = new DrawerAdapter(mCategories);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawer_list);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
recyclerView.setItemAnimator(new SlideInOutLeftItemAnimator(recyclerView));
recyclerView.setAdapter(mAdapter);
mFirebase = new Firebase(getActivity().getResources().getString(R.string.firebase_ref))
.child(FirebaseRoots.CATEGORY);
Query query = mFirebase.orderByChild(Category.PRIO);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Category model = dataSnapshot.getValue(Category.class);
model.setId(dataSnapshot.getKey());
mCategories.add(model);
recyclerView.scrollToPosition(mCategories.size() - 1);
mAdapter.notifyItemInserted(mCategories.size() - 1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Category model = dataSnapshot.getValue(Category.class);
model.setId(dataSnapshot.getKey());
int index = -1;
for (int i = 0; i < mCategories.size(); i++) {
if (mCategories.get(i).getId().equals(model.getId())) {
index = i;
break;
}
}
mCategories.set(index, model);
recyclerView.scrollToPosition(0);
mAdapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Category model = dataSnapshot.getValue(Category.class);
model.setId(dataSnapshot.getKey());
int index = -1;
for (int i = 0; i < mCategories.size(); i++) {
if (mCategories.get(i).getId().equals(model.getId())) {
index = i;
break;
}
}
mCategories.remove(index);
recyclerView.scrollToPosition(0);
mAdapter.notifyItemRemoved(index);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
alert.show(firebaseError.toString());
}
});
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity().getApplicationContext(),
recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Category category = mCategories.get(position);
drawerListener.onDrawerItemSelected(view, position, category);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public void setDrawerListener(DrawerListener listener) {
this.drawerListener = listener;
}
}
ProductGrid.java
public class ProductGrid extends Fragment implements ChildEventListener{
private Firebase mFirebaseRef;
private Alert alert;
private RecyclerView recyclerView;
private GridAdapter mAdapter;
private String categoryId;
private ArrayList<Product> mProducts;
private FileSystem fs;
public ProductGrid() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.categoryId = getArguments().getString(Product.CATEGORY_ID);
this.alert = new Alert(getActivity().getApplicationContext());
this.fs = new FileSystem(getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.grid, container, false);
fieldInitialize(layout);
mProducts = new ArrayList<>();
mAdapter = new GridAdapter(mProducts, getActivity().getApplicationContext());
recyclerView.addItemDecoration(new MarginDecoration(getActivity()));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
recyclerView.setAdapter(mAdapter);
mFirebaseRef = new Firebase(getActivity().getResources().getString(R.string.firebase_ref))
.child(FirebaseRoots.PRODUCT);
Query query = mFirebaseRef.orderByChild(Product.CATEGORY_ID).equalTo(categoryId);
query.addChildEventListener(this);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
ProductDetail detailFragment = new ProductDetail();
Bundle args = new Bundle();
args.putSerializable("product", mProducts);
args.putInt("position", position);
detailFragment.setArguments(args);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, detailFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
public void fieldInitialize(View layout) {
recyclerView = (RecyclerView) layout.findViewById(R.id.product_grid_layout);
}
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Product model = dataSnapshot.getValue(Product.class);
model.setId(dataSnapshot.getKey());
mProducts.add(model);
if (!fs.getFileNames().contains(model.getName() + FileExt.JPG.get())) {
fs.writeImage(model.getName(), ImageUtil.base64ToBitmap(
StringUtil.getBase64FromUrl(model.getImageData().getDataUrl())));
}
Collections.sort(mProducts);
recyclerView.scrollToPosition(0);
mAdapter.notifyItemInserted(mProducts.size() - 1);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Product model = dataSnapshot.getValue(Product.class);
model.setId(dataSnapshot.getKey());
fs.writeImage(model.getName(), ImageUtil.base64ToBitmap(
StringUtil.getBase64FromUrl(model.getImageData().getDataUrl())));
int index = -1;
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(model.getId())) {
index = i;
break;
}
}
mProducts.set(index, model);
recyclerView.scrollToPosition(0);
mAdapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Product model = dataSnapshot.getValue(Product.class);
model.setId(dataSnapshot.getKey());
fs.deleteImage(model.getName());
int index = -1;
for (int i = 0; i < mProducts.size(); i++) {
if (mProducts.get(i).getId().equals(model.getId())) {
index = i;
break;
}
}
mProducts.remove(index);
recyclerView.scrollToPosition(0);
mAdapter.notifyItemRemoved(index);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
alert.show(firebaseError.toString());
}
#Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = AcarsanApp.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
ProductDetail.java
public class ProductDetail extends Fragment {
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
private ArrayList<Product> products;
private int position;
public ProductDetail() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
products = (ArrayList<Product>) getArguments().getSerializable("product");
position = getArguments().getInt("position");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.product_detail, container, false);
viewPager = (ViewPager) view.findViewById(R.id.product_gallery);
adapter = new FullScreenImageAdapter(getActivity().getApplicationContext(), products);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
FileSystem
public class FileSystem {
private Context mContext;
public static final String PHOTOS_FOLDER = "photos";
public FileSystem(Context mContext) {
this.mContext = mContext;
}
public void writeImage(String name, Bitmap bitmap) {
String filename = name + FileExt.JPG.get();
File dir = mContext.getDir(PHOTOS_FOLDER, Context.MODE_PRIVATE);
File fileWithinDir = new File(dir, filename);
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream(fileWithinDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<String> getFileNames() {
List<String> fileNames = new ArrayList<>();
File file = mContext.getDir(PHOTOS_FOLDER, Context.MODE_PRIVATE);
File[] files = file.listFiles();
for (File f : files) {
fileNames.add(f.getName());
}
return fileNames;
}
}
ImageUtil
public class ImageUtil {
public static Bitmap base64ToBitmap(String encodedImage) {
if (encodedImage == null)
return null;
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
}