I have been trying to create a simple drop down menu when I click my action bar icon and have certain selections link to particular activities.
Something like this:
I've tried to follow this but no luck.
Android ActionBar ActionProvider submenu
How to add submenu items to ActionBar action in code?
Currently I have this as my Java code, but the drop down menu appears under my appname instead of the overflow icon:
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
SpinnerAdapter adapter =
ArrayAdapter.createFromResource(this, R.array.actions,
android.R.layout.simple_spinner_dropdown_item);
// Callback
OnNavigationListener callback = new OnNavigationListener() {
String[] items = getResources().getStringArray(R.array.actions); // List items from res
#Override
public boolean onNavigationItemSelected(int position, long id) {
// Do stuff when navigation item is selected
Log.d("NavigationItemSelected", items[position]); // Debug
return true;
}
};
You can use Preference Activity for this. So Just Create a xml folder in res folder. and create a settings.xml
<?xml version="1.0" encoding="utf-8"?>
<com.xxx.MyPreferenceCategory
android:title="#string/about_application" >
<Preference
android:key="shareApp"
android:summary="#string/share_app_summary"
android:title="#string/share_app" />
<Preference
android:key="rateApp"
android:summary="#string/rate_app_summary"
android:title="#string/rate_app" />
<Preference
android:key="version"
android:summary="#string/version_app_summary"
android:title="#string/version_app" />
</com.xxx.MyPreferenceCategory>
<com.xxx.MyPreferenceCategory
android:title="#string/about_developer" >
<Preference
android:key="contactUs"
android:summary="#string/contact_us_summary"
android:title="#string/contact_app" />
<Preference
android:key="aboutUs"
android:title="#string/about_app" />
<Preference
android:key="terms"
android:title="#string/about_app_terms" />
<Preference
android:key="policy"
android:title="#string/about_app_policy" />
</com.xxx.MyPreferenceCategory>
After that create an MyPreferenceCategory.java.
public class MyPreferenceCategory extends PreferenceCategory{
public MyPreferenceCategory(Context context) {
super(context);
}
private TextView categoryTitle;
public MyPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyPreferenceCategory(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected View onCreateView(ViewGroup parent) {
categoryTitle = (TextView) super.onCreateView(parent);
return categoryTitle;
}
}
After that create a MenuOptions.java file
public class MenuOptions extends SherlockPreferenceActivity {
Handler disconnectHandler;
Runnable disconnectCallback;
Preference shareApp, rateApp, contactUs, aboutUs, termsCondition,
privacyPolicy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(android.R.id.list).setBackgroundColor(Color.WHITE);
disconnectHandler = new Handler() {
public void handleMessage(Message msg) {
}
};
disconnectCallback = new Runnable() {
#Override
public void run() {
}
};
shareApp = (Preference) findPreference("shareApp");
shareApp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
//do your stuff
return false;
}
});
rateApp = (Preference) findPreference("rateApp");
rateApp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
//do your stuff
return false;
}
});
contactUs = (Preference) findPreference("contactUs");
contactUs.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
//do your stuff
return false;
}
});
aboutUs = (Preference) findPreference("aboutUs");
aboutUs.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
return false;
}
});
termsCondition = (Preference) findPreference("terms");
termsCondition
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
return false;
}
});
privacyPolicy = (Preference) findPreference("policy");
privacyPolicy
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
After that where you are where you are using action bar setting button where put this code.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(getBaseContext(), MenuOptions.class);
startActivity(intent);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
Related
I've been working on the Android SDK platform, and it is a bit unclear how to save an application's state. I'm creating a menu which has CheckBoxes. I do get the idea of SharedPreferences but I'm not able to get my head around the implementation of SharedPreferences in CheckBoxes.
I want those checkboxes (multiple checkboxes) stay checked/unchecked even if the user relaunches the app.
public class MainActivity extends AppCompatActivity {
protected WebView myWebView;
protected TextView text_selection;
protected TextView mOutputText;
public static final String TAG = "mytag";
protected SharedPreferences sharedPreferences;
protected SharedPreferences.Editor editor;
private final String PREFERENCE_FILE_KEY = "myAppPreference";
private Context context;
protected CheckBox animal, fisheries, dairy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
//sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
//Context context = getActivity();
//SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean("animal", false);
editor.putBoolean("fisheries", false);
editor.putBoolean("dairy", false);
//editor.putBoolean("checkbox", checkbox.isChecked()));
editor.commit();
this.myWebView = (WebView) findViewById(R.id.webview);
this.text_selection = findViewById(R.id.text_selected);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("------");
//mOutputText = (TextView) findViewById(R.id.tv_output);
mOutputText = findViewById(R.id.textView);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if(task.isSuccessful()){
String token=task.getResult().getToken();
Log.d(TAG, "onComplete: Token: "+token);
mOutputText.setText("Token has been generated");
}else{
mOutputText.setText("Token failed");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
if (sharedPreferences.getBoolean("animal", false)) {
// findItem id function return the id of the menu
menu.findItem(R.id.animal).setChecked(true);
} else if (sharedPreferences.getBoolean("fisheries", false)) {
menu.findItem(R.id.fisheries).setChecked(true);
} else if (sharedPreferences.getBoolean("dairy", false)) {
menu.findItem(R.id.dairy).setChecked(true);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("animal", false);
} else {
item.setChecked(true);
editor.putBoolean("animal", true);
}
break;
case R.id.fisheries:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("fisheries", false);
} else {
item.setChecked(true);
editor.putBoolean("fisheries", true);
}
break;
case R.id.dairy:
if (item.isChecked()) {
item.setChecked(false);
editor.putBoolean("dairy", false);
} else {
item.setChecked(true);
editor.putBoolean("dairy", true);
}
break;
}
editor.commit();
return super.onOptionsItemSelected(item);
}
}
Below example;
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
editor.putBoolean("dairy", isChecked);
editor.commit();
}
});
Replace the beginning stuff in your onCreate with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(PREFERENCE_FILE_KEY, Context.MODE_PRIVATE);
animal = (CheckBox)findViewById(R.id.animal);
fisheries = (CheckBox)findViewById(R.id.fisheries);
dairy = (CheckBox)findViewById(R.id.dairy);
animal.setChecked(getCheckboxStatus("animal"));
animal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("animal", isChecked);
}
}
);
fisheries.setChecked(getCheckboxStatus("fisheries"));
fisheries.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("fisheries", isChecked);
}
}
);
dairy.setChecked(getCheckboxStatus("dairy"));
dairy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
saveCheckBoxValue("dairy", isChecked);
}
}
);
// Your WebView and Firebase stuff
}
private void saveCheckBoxValue(String key, boolean isChecked) {
editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean getCheckboxStatus(String key) {
return sharedPreferences.getBoolean(key, false);
}
Change the onCreateOptionsMenu function to the following:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
menu.findItem(R.id.animal).setChecked(sharedPreferences.getBoolean("animal", false));
menu.findItem(R.id.fisheries).setChecked(sharedPreferences.getBoolean("fisheries", false));
menu.findItem(R.id.dairy).setChecked(sharedPreferences.getBoolean("dairy", false));
return true;
}
Change the onOptionsItemSelected function to:
#Override
public boolean onOptionsItemSelected(MenuItem item){
editor = sharedPreferences.edit();
switch (item.getItemId()) {
case R.id.animal:
editor.putBoolean("animal", item.isChecked());
break;
case R.id.fisheries:
editor.putBoolean("fisheries", item.isChecked());
break;
case R.id.dairy:
editor.putBoolean("dairy", item.isChecked());
break;
}
editor.apply();
return super.onOptionsItemSelected(item);
}
(Sorry for changing the whole question as I found the actual problem after troubleshooting)I have my activity as followed:
public class MyAppActivity extends AppCompatActivity{
#Override
protected void onCreate(...)
{
//...
this.setContentView(contentViewResID);
Toolbar toolbar = (Toolbar) this.findViewById(toolbarResID);
this.setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onPause() {...}
#Override
protected void onResume() {...}
#Override
public boolean onSupportNavigateUp() {
Log.d("onSupportNavigateUp()", "pressed");
finish();
return super.onSupportNavigateUp();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {...}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {...}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == menuAddFood) {
Intent intent = new Intent(this, ActivityAddFood.class);
this.startActivity(intent);
}
if (item == menuSettings){
Intent intent = new Intent(this, ActivitySetting.class);
this.startActivity(intent);
}
if(item == menuUsername){
}
return true;
}
}
EDIT:
After my troubleshooting, I found out after override the onOptionsItemSelected(), onSupportNavigateUp() no longer fired anymore when I pressed the top left BACK / UP / HOME button. I want to do finish() inside onSupportNavigateUp() How to solve this?
You have to override the method in your current Activity and call the super:
public class ActivityExample extends MyAppActivity {
Context context = this;
AppCompatActivity activity = this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.createMyView(R.layout.activity_log_in, R.id.toolbar);
// ...
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
Also, if you override onOptionsItemSelected, then onSupportNavigateUp will not be called.
//DONT OVERRIDE THIS METHOD
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
break;
}
return true;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Can someone explain to me this cryptic logcat message below and also explain how to solve the issue in the code below as well. Thank you and happy holidays :)
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)' on a null object reference
at com.meguillaume.cloudmusic.MainActivity.onCreateOptionsMenu(MainActivity.java:183)
at android.app.Activity.onCreatePanelMenu(Activity.java:3142)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:360)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:88)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:331)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:88)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private static final String TAG = "MainActivity";
private TracksAdapter mAdapter;
//List is actually an interfact (Hold down command and left click to view.) and arraylist is
//actually a class that implements that interface.
private List<Track> mTracks;
private TextView mSelectedTitle;
private ImageView mSelectedThumbnail;
private MediaPlayer mMediaPlayer;
private ImageView mPlayerStateButton;
private SearchView mSearchView;
private List<Track> mPreviousTracks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
toggleSongState();
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mPlayerStateButton.setImageResource(R.drawable.ic_play);
}
});
toolbar = (Toolbar) findViewById(R.id.player_toolbar);
mSelectedTitle = (TextView) findViewById(R.id.selected_title);
mSelectedThumbnail = (ImageView) findViewById(R.id.selected_thumbnail);
mPlayerStateButton = (ImageView) findViewById(R.id.player_state);
mPlayerStateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggleSongState();
}
});
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.songs_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mTracks = new ArrayList<Track>(); //BC of the list interface array list can implement here
mAdapter = new TracksAdapter(this, mTracks);
mAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Track selectedTrack = mTracks.get(position);
mSelectedTitle.setText(selectedTrack.getTitle());
Picasso.with(MainActivity.this).load(selectedTrack.getAvatarURL()).into(mSelectedThumbnail);
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.reset();
try {
mMediaPlayer.setDataSource(selectedTrack.getStreamURL() + "?client_id=" + SoundCloudService.CLIENT_ID);
mMediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
});
recyclerView.setAdapter(mAdapter);
SoundCloudService service = SoundCloud.getService();
service.getRecentSongs(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()), new Callback<List<Track>>() {
#Override
public void success(List<Track> tracks, Response response) {
updateTracks(tracks);
}
#Override
public void failure(RetrofitError error) {
Log.d(TAG, "Error is " + error);
}
});
}
private void updateTracks(List<Track> tracks) {
mTracks.clear();
mTracks.addAll(tracks);
mAdapter.notifyDataSetChanged();
}
private void toggleSongState() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mPlayerStateButton.setImageResource(R.drawable.ic_play);
} else {
mMediaPlayer.start();
mPlayerStateButton.setImageResource(R.drawable.ic_pause);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}
}
#Override
public boolean onQueryTextSubmit(String query) {
mSearchView.clearFocus();
SoundCloud.getService().searchSongs(query, new Callback<List<Track>>() {
#Override
public void success(List<Track> tracks, Response response) {
updateTracks(tracks);
}
#Override
public void failure(RetrofitError error) {
}
});
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#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);
mSearchView = (SearchView) menu.findItem(R.id.search_view).getActionView();
mSearchView.setOnQueryTextListener(this);
MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.search_view), new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
mPreviousTracks = new ArrayList<Track>(mTracks);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
updateTracks(mPreviousTracks);
return true;
}
});
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.search_view) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Near Line 183 of your program file, there is a line invoking
mSearchView.setOnQueryTextListener(this);
but mSerachView was still null (that probably means the line before, about menu.findItem(), returned a null)
#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);
mSearchView = (SearchView) menu.findItem(R.id.search_view).getActionView();
mSearchView.setOnQueryTextListener(this); // <--- This line gave you the NullPointerException
MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.search_view), new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
mPreviousTracks = new ArrayList<Track>(mTracks);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
updateTracks(mPreviousTracks);
return true;
}
});
return true;
}
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 have a Drawscreen.class file which the main activity and Drawthegraph.class which extends view. I have a method in Drawthegraph.class which I need to call from Drawscreen.class.How can I do that?
Drawscreen.class-
public class Drawscreen extends ActionBarActivity
{
//LinearLayout linear=(LinearLayout)findViewById(R.id.main_layout);
//draw=(Drawthegraph)findViewById(R.id.main_layout);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
ActionBar actionbar=getSupportActionBar();
actionbar.show();
View drawthegraph=new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawscreen, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
case R.id.undo:/*Call method of view here*/
break;
}
return super.onOptionsItemSelected(item);
}
}
Drawthegraph.class
public class Drawthegraph extends View
{
private int lines;
----
----
public void decrease_lines() /*Call this function from Drawscreen*/
{
if(lines>0)
{
lines--;
}
}
Use your drawthegraph variable as an instance field:
public class Drawscreen extends ActionBarActivity
{
//LinearLayout linear=(LinearLayout)findViewById(R.id.main_layout);
//draw=(Drawthegraph)findViewById(R.id.main_layout);
private Drawthegraph drawthegraph;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
ActionBar actionbar=getSupportActionBar();
actionbar.show();
this.drawthegraph=new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawscreen, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
case R.id.undo:/*Call method of view here*/
drawthegraph.decrease_lines();
break;
}
return super.onOptionsItemSelected(item);
}
}
Your Drawthegraph object must be a field of your Activity:
public class Drawscreen extends ActionBarActivity {
Drawthegraph drawthegraph;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
drawthegraph = new Drawthegraph(this);
setContentView(drawthegraph);
drawthegraph.setBackgroundColor(color.Ivory);
}
...
then you can call wherever you want in your Drawscreen:
drawthegraph.decrease_lines();