How show Banner Ads on Newspaper Webview Android Eclipse - java

How show Banner Ads on Newspaper Link "Webview" Android Eclipse
I already set Admob "Banner Ads and Interstitial Ads" on my Project. Interstitial Ads Work Correctly but Banner Ads not Show on Webview.
Here my Java & xml Code
Details_Newspaper.Java
package com.nasir.newspaper;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
#SuppressLint("SetJavaScriptEnabled")
public class Details_Newapaper extends Activity {
WebView mWebview;
AdView mAdView;
private InterstitialAd interAd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Adds Progrss bar Support
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.details_newapaper );
// For Banner Ads View
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// For Interstitial Ads View
interAd = new InterstitialAd(this);
interAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest_FC = new AdRequest.Builder().build();
interAd.loadAd(adRequest_FC);
interAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// TODO Auto-generated method stub
displayInterstitial();
}
});
getOverflowMenu();
// Makes Progress bar Visible
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebview.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebview.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
final Activity Activity = this;
mWebview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
Activity.setTitle("Loading..... Please Wait");
Activity.setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
Activity.setTitle(R.string.app_name);
}
});
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Toast.makeText(Activity, description, Toast.LENGTH_SHORT).show();
}
});
String customHtml = getIntent().getStringExtra("Newspaper_Name");
mWebview.loadUrl(customHtml);
setContentView(mWebview);
mWebview.getSettings().setBuiltInZoomControls(true);
}
// On Back Button Press, Go to Website Back
#Override
public void onBackPressed() {
if (mWebview.isFocused() && mWebview.canGoBack()) {
mWebview.goBack();
} else {
super.onBackPressed();
finish();
}
}
// For Interstitial Ads View
public void displayInterstitial() {
if (interAd.isLoaded()) {
interAd.show();
}
}
/** Called when leaving the activity */
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
/** Called when returning to the activity */
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
/** Called before the activity is destroyed */
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
// inflate for action bar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.refresh_main, menu);
return true;
}
// handle click events for action bar items
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
showToast("Refresh was clicked.");
return true;
// case R.id.share:
// showToast("Share was clicked.");
// return true;
//
default:
return super.onOptionsItemSelected(item);
}
}
// put the other two menu on the three dots (overflow)
private void getOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
java.lang.reflect.Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// so that we know something was triggered
public void showToast(String msg){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
details_newspaper.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top|fill_vertical"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-1528948212400372/9325301249" >
</com.google.android.gms.ads.AdView>
</RelativeLayout>

Related

Android Surface View with Custom Size

I am working on an OCR app with a Surface View and Google Vision API, which works fin; but the Surface View extends over the whole Display of the Device (Galaxy Grand Prime). It should only have half of the size or less, so that the recognised text can be displayed in a Text View beneath the Surface View. Although I googled a lot, I couldnĀ“t solve this problem and would appreciate any support and advice, thanks!
The Main Activity:
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
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.widget.Button;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SurfaceView mCameraView;
TextView mTextView;
CameraSource mCameraSource;
private static final String TAG = "MainActivity";
private static final int requestPermissionID = 101;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
mCameraView = findViewById(R.id.surfaceView);
mTextView = findViewById(R.id.text_view);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
startCameraSource();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode != requestPermissionID) {
Log.d(TAG, "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
mCameraSource.start(mCameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void startCameraSource() {
//Create the TextRecognizer
final TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.w(TAG, "Detector dependencies not loaded yet");
} else {
//Initialize camerasource to use high resolution and set Autofocus on.
mCameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.setRequestedFps(2.0f)
.build();
/**
* Add call back to SurfaceView and check if camera permission is granted.
* If permission is granted we can start our cameraSource and pass it to surfaceView
*/
mCameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
requestPermissionID);
return;
}
mCameraSource.start(mCameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCameraSource.stop();
}
});
//Set the TextRecognizer's Processor.
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
/**
* Detect all the text from camera using TextBlock and the values into a stringBuilder
* which will then be set to the textView.
* */
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items = detections.getDetectedItems();
if (items.size() != 0 ){
mTextView.post(new Runnable() {
#Override
public void run() {
StringBuilder stringBuilder = new StringBuilder();
for(int i=0;i<items.size();i++){
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
mTextView.setText(stringBuilder.toString());
// Start NewActivity.class
String recognizedText = mTextView.getText().toString();
Intent i = new Intent(MainActivity.this, ListActivity.class);
i.putExtra("recognized Text", recognizedText);
}
});
}
}
});
}
}
#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.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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
String recognizedText = mTextView.getText().toString();
Intent i = new Intent(MainActivity.this, ListActivity.class);
i.putExtra("recognized Text", recognizedText);
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<SurfaceView
android:id="#+id/surfaceView"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_weight="2"/>
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="8dp"
android:layout_weight="1"
android:gravity="center"
android:textStyle="bold"
android:text="#string/txt_message"
android:textColor="#android:color/black"
android:textSize="20sp" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

How to stop WebView app to going go homepage after every Swipe to refresh?

Every time I swipe to refresh, my app reloads to the homepage instead of reloading the same web-page. I tried every way to detect this behaviour but couldn't find out anything. Can you tell what's the issue here?
Swipe to refresh should only be resfreshing the current web page instead of the whole app right?
MainActivity.java
package com.yoalfaaz.yoalfaaz;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.support.v4.view.MenuItemCompat;
public class MainActivity extends AppCompatActivity {
private WebView YoWeb;
private ShareActionProvider mShareActionProvider;
SwipeRefreshLayout swipe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb() {
YoWeb = (WebView)findViewById(R.id.webview);
WebSettings webSettings = YoWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
YoWeb.loadUrl("https://www.yoalfaaz.com");
swipe.setRefreshing(true);
YoWeb.setWebViewClient(new WebViewClient() {
//onPageFinished Method
public void onPageFinished(WebView view, String url) {
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}
#Override
public void onBackPressed() {
if (YoWeb.canGoBack()) {
YoWeb.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate menu resource file.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.menu_item_share);
// Fetch and store ShareActionProvider
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
// Return true to display menu
return true;
}
// Call to update the share intent
private void setShareIntent(Intent shareIntent) {
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(shareIntent);
}
}
//private Intent setShareIntent() {
// Intent shareIntent = new Intent();
// shareIntent.setAction(Intent.ACTION_SEND);
// shareIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
// shareIntent.setType("text/plain");
// startActivity(shareIntent);
// return shareIntent;
//}
}
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.yoalfaaz.yoalfaaz.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swiperefresh"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
These are the two files responsible for swipe to refresh and you can see all the code that is there. I hope that you might be able to figure out exactly what's the issue here.
Your SwipeRefreshLayout.OnRefreshListener is calling LoadWeb method. Inside LoadWeb you are calling YoWeb.loadUrl("https://www.yoalfaaz.com"); which means you are always setting the webview to go to that URL on refresh. Change your code to be like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
YoWeb = (WebView)findViewById(R.id.webview); // Move your declaration up here
swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
LoadWeb(YoWeb.getUrl()); // Pass in the current url to refresh
}
});
LoadWeb("https://www.yoalfaaz.com"); // load the home page only once
}
public void LoadWeb(String url) // Pass in URL you want to load
{
WebSettings webSettings = YoWeb.getSettings();
webSettings.setJavaScriptEnabled(true);
YoWeb.loadUrl(url); // Load the URL passed into the method
swipe.setRefreshing(true);
YoWeb.setWebViewClient(new WebViewClient() {
//onPageFinished Method
public void onPageFinished(WebView view, String url) {
//Hide the SwipeRefreshLayout
swipe.setRefreshing(false);
}
});
}

Changing the background of a populated menu

I have been trying to figure this out but it's been a disaster.
I have this menu which populates and I can't change the background or I can't add menu icons to it. can someone help me to figure this out please..!
this is my main activity.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:minHeight="?android:attr/actionBarSize" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white" />
<com.vproductions.xinxilanka.views.DrawerNavigationListView
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"/>
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
this is the mainactivity.java
package com.vproductions.xinxilanka.activities;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.vproductions.xinxilanka.utils.EventBus;
import com.squareup.otto.Subscribe;
import com.vproductions.xinxilanka.R;
import com.vproductions.xinxilanka.events.DrawerSectionItemClickedEvent;
import com.vproductions.xinxilanka.fragments.AdvancedSearchFragment;
import com.vproductions.xinxilanka.fragments.NearMapFragment;
import com.vproductions.xinxilanka.fragments.QuickSearchFragment;
import com.vproductions.xinxilanka.repository.FieldRepository;
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private String mCurrentFragmentTitle;
private static Boolean firstInit = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
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));
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (getSupportActionBar() != null)
getSupportActionBar().setTitle(R.string.drawer_opened);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (getSupportActionBar() != null)
getSupportActionBar().setTitle(R.string.drawer_closed);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
if (firstInit || getSupportFragmentManager().getFragments() == null)
displayInitialFragment();
firstInit = false;
}
private void displayInitialFragment() {
getSupportFragmentManager().beginTransaction().replace(R.id.container, QuickSearchFragment.getInstance()).commit();
mCurrentFragmentTitle = getString(R.string.section_quick_search);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#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.
if (mActionBarDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
EventBus.getInstance().register(this);
}
#Override
protected void onStop() {
EventBus.getInstance().unregister(this);
super.onStop();
}
#Subscribe
public void onDrawerSectionItemClickEvent(DrawerSectionItemClickedEvent event) {
mDrawerLayout.closeDrawers();
if (event == null || TextUtils.isEmpty(event.section) || event.section.equalsIgnoreCase(mCurrentFragmentTitle)) {
//return;
}
//Toast.makeText(this, "MainActivity: Section Clicked: " + event.section, Toast.LENGTH_SHORT).show();
if (event.section.equalsIgnoreCase(getString(R.string.section_map))) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, NearMapFragment.getInstance()).commit();
} else if (event.section.equalsIgnoreCase(getString(R.string.section_quick_search))) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, QuickSearchFragment.getInstance()).commit();
} else if (event.section.equalsIgnoreCase(getString(R.string.advanced_search))) {
if (FieldRepository.getInstance().getSeted()) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, AdvancedSearchFragment.getInstance()).commit();
} else {
Toast.makeText(this, getString(R.string.fields_not_loaded), Toast.LENGTH_LONG).show();
}
} else if (event.section.equalsIgnoreCase(getString(R.string.add_property))) {
// go to external website
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://xinxilanka.com/index.php/admin/user/login/"));
startActivity(intent);
} else if (event.section.equalsIgnoreCase(getString(R.string.open_website))) {
// go to external website
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(getString(R.string.script_url)));
startActivity(intent);
} else {
return;
}
mCurrentFragmentTitle = event.section;
}
public void open(View view) {
Intent browserIntent = (new Intent(Intent.ACTION_VIEW, Uri.parse("http://xinxilanka.com/index.php/admin/user/login/")));
startActivity(browserIntent);
}
}
the navigation menu that shows now is just white background and no icons.
I want to add a nice header and some icons to the menu items.
this menu is a auto populated menu.
basically the navigation menu which populates menu items without defining them in a menu file.
see below for drawernavigationlistview class
package com.vproductions.xinxilanka.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.vproductions.xinxilanka.R;
import com.vproductions.xinxilanka.adapters.DrawerNavigationListAdapter;
import com.vproductions.xinxilanka.events.DrawerSectionItemClickedEvent;
import com.vproductions.xinxilanka.utils.EventBus;
/**
* Created by sandi on 04.01.2016..
*/
public class DrawerNavigationListView extends ListView implements AdapterView.OnItemClickListener {
public DrawerNavigationListView(Context context) {
this(context, null);
}
public DrawerNavigationListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawerNavigationListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Populate menu
DrawerNavigationListAdapter adapter = new DrawerNavigationListAdapter(getContext(), 0);
adapter.add(getContext().getString(R.string.section_quick_search));
adapter.add(getContext().getString(R.string.section_map));
adapter.add(getContext().getString(R.string.advanced_search));
adapter.add(getContext().getString(R.string.howto_use));
if (getContext().getString(R.string.website_enabled).equalsIgnoreCase("true")) {
adapter.add(getContext().getString(R.string.add_property));
adapter.add(getContext().getString(R.string.open_website));
}
setAdapter(adapter);
setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
//Toast.makeText(getContext(), "SectionClicked: " + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
EventBus.getInstance().post(new DrawerSectionItemClickedEvent((String) parent.getItemAtPosition(position)));
}
}
navigation_drawer_list_item.xml file
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/navigation_list_selector"
android:gravity="left"
android:padding="8dp"
android:textSize="14sp"
android:drawableStart="#mipmap/ic_stars_black_24dp"
android:drawableLeft="#mipmap/ic_stars_black_24dp"
android:drawablePadding="3dp"
android:textColor="#color/black">
</TextView>
You have to define the background into the DrawerNavigationListAdapter XML.

YouTubeFragmentPlayer Android App - Only Black Box appearing

I am trying to build sample Android app in which the main activity contains a YouTubePlayerFragment. I get no errors with my implementation, but when I run this app on an AVD or my phone, the fragment for the YouTubePlayerFragment is just a black box. No video loads.
Any help is greatly appreciated.
Here is my code:
YouTubeFragment.java
package androidsample.example.com.fragments1;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFragment extends YouTubePlayerFragment implements YouTubePlayer.OnInitializedListener {
// TODO: Rename and change types and number of parameters
public static YouTubeFragment newInstance() {
YouTubeFragment fragment = new YouTubeFragment();
return fragment;
}
private void init(){
initialize(DeveloperKey.DEVELOPER_KEY, this);
}
public YouTubeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.activity_main, container, false);
YouTubeFragment ytf = newInstance();
ytf.init();
//inside fragment use getFragmentManager instead of getFragmentSupportManager
getFragmentManager().beginTransaction()
.add(R.id.youTubePlayer, ytf)
.commit();
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getActivity(), "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
}
MainActivity.java
package androidsample.example.com.fragments1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youTubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
I don't think you need to create a newInstance(). The instance is created in your xml. And when you are in onCreateView that is a specific instance already.
So you should be able to replace these lines
YouTubeFragment ytf = newInstance();
ytf.init();
With
this.init();
Or more simply
init();
With some help, I have a working version of this (problems with target SDK 21, using 19):
YouTubeFailureRecoveryActivity.java
package androidsample.example.com.fragments2;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
//String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
String errorMessage = "custom ERror MessAgE";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer player,
boolean wasRestored) {
// TODO Auto-generated method stub
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return (YouTubePlayerFragment) getFragmentManager().findFragmentById(
R.id.youtube_fragment);
}
}
MainActivity.java
package androidsample.example.com.fragments2;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.youtube.player.YouTubePlayerFragment;
public class MainActivity extends YouTubeFailureRecoveryActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
#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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>

Method to stop Android MediaPlayer using the same button?

I want to stop the Android MediaPlayer in my App using the same button which I use for starting it. As you can see from the sources below, I declared the onClick function of my button in the activity_main.xml. When clicked, the buttons value changes from an triangle to a square, if I click it again, it changes back so there is no problem with this.
The tick(); function is configured to get either the string "start" or the string "stop" dependent on which version of the button has been pressed.
Also the player is very laggy. It should play the click sound every second (for testing if this even works) but it is very laggy.
Here is my MainActivity
package net.k40s.metronome;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.Toast;
import android.os.Handler;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
NumberPicker inputBPM;
ImageView outputFlash;
Button buttonPlay;
protected PowerManager.WakeLock mWakeLock;
final Handler metronomeHandler = new Handler();
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
inputBPM = (NumberPicker) findViewById(R.id.inputBPM);
outputFlash = (ImageView) findViewById(R.id.imageClick);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
inputBPM.setMinValue(20);
inputBPM.setMaxValue(150);
inputBPM.setValue(120);
inputBPM.setWrapSelectorWheel(true);
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Metronome Active");
this.mWakeLock.acquire();
}
}
#Override
public void onDestroy() {
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
this.mWakeLock.release();
}
super.onDestroy();
}
#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);
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();
if (id == R.id.action_settings) {
Intent startActivity = new Intent(this, SettingsActivity.class);
startActivity(startActivity);
return true;
}
if (id == R.id.action_mail){
sendMailToMe();
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
public static class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}
private void tick(String what) {
if (what.equals("start")) {
metronomeHandler.post(metronomeRunnable);
}
if (what.equals("stop")){
if(mp.isPlaying())
{
// TODO stop media playback
}
}
}
final Runnable metronomeRunnable = new Runnable() {
public void run(String what) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.click);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
};
public void playBeat(final View v) {
String activeText = (String) buttonPlay.getText();
if (activeText.equals(getResources().getString(R.string.value_button_play))) {
buttonPlay.setText(R.string.value_button_stop);
inputBPM.setValue(121);
int bpm = inputBPM.getValue();
SharedPreferences sp1 = PreferenceManager.getDefaultSharedPreferences(this);
String pref_measure = sp1.getString("pref_measure", "");
if (pref_measure.equals("4")) {
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {tick("start");}
}, 0, 1000);
}
if (pref_measure.equals("3")) {
/*
Dreivierteltakt start
*/
}
if (pref_measure.equals("2")) {
/*
Zweivierteltakt start
*/
}
if (pref_measure.equals("6")) {
/*
Sechsachteltakt start
*/
}
}
else if (activeText.equals(getResources().getString(R.string.value_button_stop))) {
buttonPlay.setText(R.string.value_button_play);
tick("stop");
}
}
public void sendMailToMe(){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"lukas#k40s.net"});
i.putExtra(Intent.EXTRA_SUBJECT, "I want to say hello.");
i.putExtra(Intent.EXTRA_TEXT , "Hey,");
try {
startActivity(Intent.createChooser(i, getResources().getString(R.string.choose_mail)));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, getResources().getString(R.string.no_clients), Toast.LENGTH_SHORT).show();
}
}
}
And here is my activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:soundEffectsEnabled="true"
tools:context=".MainActivity">
<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/inputBPM"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/value_button_play"
android:id="#+id/buttonPlay"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="playBeat" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/bpm"
android:id="#+id/textView"
android:layout_above="#+id/inputBPM"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageClick"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/flash0" />
</RelativeLayout>
You can find the whole code at GitHub
Thanks for your help. Sorry if I'm really that stupid and overlooked something really obvious.
So try this code below, basically you need to make your timer a field member and then cancel it when they want to stop and then reinitialize it when they click play. I tested it and it works for me. (unrelated code was omitted)
MediaPlayer mp;
Timer myTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
inputBPM = (NumberPicker) findViewById(R.id.inputBPM);
outputFlash = (ImageView) findViewById(R.id.imageClick);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
inputBPM.setMinValue(20);
inputBPM.setMaxValue(150);
inputBPM.setValue(120);
inputBPM.setWrapSelectorWheel(true);
mp = MediaPlayer.create(getApplicationContext(), R.raw.click);
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Metronome Active");
this.mWakeLock.acquire();
}
}
#Override
public void onDestroy() {
SharedPreferences sp0 = PreferenceManager.getDefaultSharedPreferences(this);
Boolean pref_display = sp0.getBoolean("pref_display", false);
if (pref_display) {
this.mWakeLock.release();
}
if (mp != null) {
mp.release();
}
super.onDestroy();
}
private void tick(String what) {
if (what.equals("start")) {
mp.start();
}
else if (what.equals("stop")) {
mp.pause();
}
}
public void playBeat(final View v) {
String activeText = (String) buttonPlay.getText();
if (activeText.equals(getResources().getString(R.string.value_button_play))) {
buttonPlay.setText(R.string.value_button_stop);
inputBPM.setValue(121);
int bpm = inputBPM.getValue();
myTimer = new Timer();
SharedPreferences sp1 = PreferenceManager.getDefaultSharedPreferences(this);
String pref_measure = sp1.getString("pref_measure", "");
if (pref_measure.equals("4")) {
myTimer.schedule(new TimerTask() {
#Override
public void run() {tick("start");}
}, 0, 1000);
}
}
else if (activeText.equals(getResources().getString(R.string.value_button_stop))) {
buttonPlay.setText(R.string.value_button_play);
myTimer.cancel();
myTimer.purge();
myTimer = null;
tick("stop");
}
}

Categories