package sawatop.com.tubemate;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class DetailsActivity extends Activity {
private ProgressBar progressBar;
private WebView web;
private WebView web2;
private String url = "";
private String url2 = "";
private Button buttonClose;
private long lastPressedTime;
private static final int PERIOD = 60000;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
if (event.getDownTime() - lastPressedTime < PERIOD) {
finish();
} else {
Toast.makeText(getApplicationContext(), "click agin to exit", Toast.LENGTH_SHORT).show();
lastPressedTime = event.getEventTime();
} return true;
}
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (getIntent().getExtras() != null) {
url = getIntent().getExtras().getString("KEY_INTENT_URL");
}
buttonClose = (Button) findViewById(R.id.btnClose);
buttonClose.setText("\u0623\u063a\u0644\u0627\u0642 \u0627\u0644\u0646\u0627\u0641\u0630\u0629");
buttonClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
progressBar = (ProgressBar) findViewById(R.id.progress);
web = (WebView) findViewById(R.id.webview); web2 = (WebView) findViewById(R.id.webview2);
web2.getSettings().setJavaScriptEnabled(true);
web.getSettings().setJavaScriptEnabled(true);
if (hasConnection(this)) {
web.loadUrl(url);
web2.loadUrl(url2);
web.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
super.onPageStarted(view, url2, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
super.onPageFinished(view, url2);
progressBar.setVisibility(View.GONE);
// actionBar.show();
}
});
} else {
DisplayAlertDialog(this, "Internet connection not available. \nPlease check your internet connection.");
}
}
public static boolean hasConnection(Context context) {
boolean isNetAvailable = false;
if (context != null) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (mConnectivityManager != null) {
boolean mobileNetwork = false;
boolean wifiNetwork = false;
boolean mobileNetworkConnecetd = false;
boolean wifiNetworkConnecetd = false;
final NetworkInfo mobileInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
final NetworkInfo wifiInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mobileInfo != null) {
mobileNetwork = mobileInfo.isAvailable();
}
if (wifiInfo != null) {
wifiNetwork = wifiInfo.isAvailable();
}
if (wifiNetwork || mobileNetwork) {
if (mobileInfo != null)
mobileNetworkConnecetd = mobileInfo.isConnectedOrConnecting();
wifiNetworkConnecetd = wifiInfo.isConnectedOrConnecting();
}
isNetAvailable = (mobileNetworkConnecetd || wifiNetworkConnecetd);
}
}
return isNetAvailable;
}
private void DisplayAlertDialog(Context context, String Message) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle(web.getTitle());
alertDialog.setMessage(Message);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
how i can add download file from this url
https://r1---sn-ab5l6nes.googlevideo.com/videoplayback?type=video%2F3gpp%3B+codecs%3D%22mp4v.20.3%2C+mp4a.40.2%22&signature=87B209A955C7A0978E5BE6375A33A295321C40FC.5780263682592D055D67206BBEB032021CE7A4C3&dur=332.463&mt=1444993525&mv=m&fexp=9408710%2C9412914%2C9414764%2C9414810%2C9415821%2C9416126%2C9416524%2C9416729%2C9417707%2C9418204%2C9418401%2C9419445%2C9419892%2C9420772%2C9421165%2C9421606%2C9422951&ms=au&source=youtube&mm=31&mn=sn-ab5l6nes&upn=2KMaHc3Sop8&lmt=1416629503243021&mime=video%2F3gpp&itag=17&sver=3&key=yt6&ipbits=0&pl=23&requiressl=yes&gcr=us&expire=1445015194&id=d00aa70927648d0d&sparams=dur%2Cgcr%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Crequiressl%2Csource%2Cupn%2Cexpire&initcwndbps=2678750&ip=158.69.202.190&fallback_host=tc.v15.cache5.googlevideo.com&quality=small&title=Eminem---Guts-Over-Fear-ft-Sia
Related
I'm trying to connect to an ble device, so I've implemented a bluetooth ble scan activity for this, but this does not work on my tablet (Archos 70 3G with android 7.0) but works in my phone (Xiaomi Note 8 Pro). I allowed location and bluetooth both devices. What is the problem? The code of the activity:
package myapp
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import myapp.R;
public class BluetoothListActivity extends Activity {
private BluetoothAdapter mBluetoothAdapter;
// private BluetoothAdapter mBtAdapter;
private TextView mEmptyList;
public static final String TAG = "DeviceListActivity";
List<BluetoothDevice> deviceList;
private DeviceAdapter deviceAdapter;
private ServiceConnection onService = null;
Map<String, Integer> devRssiValues;
private static final long SCAN_PERIOD = 10000; //scanning for 10 seconds
private Handler mHandler;
private boolean mScanning;
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] Results) {
if (requestCode == 1) {
Toast.makeText(this, "Git gud", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Toast.makeText(this, "git gud", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_device_list);
android.view.WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.gravity = Gravity.TOP;
layoutParams.y = 200;
mHandler = new Handler();
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "Ble not supported", Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Not supported", Toast.LENGTH_SHORT).show();
finish();
return;
}
populateList();
mEmptyList = (TextView) findViewById(R.id.empty);
Button cancelButton = (Button) findViewById(R.id.btn_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mScanning == false) scanLeDevice(true);
else finish();
}
});
}
private void populateList() {
/* Initialize device list container */
Log.d(TAG, "populateList");
deviceList = new ArrayList<BluetoothDevice>();
deviceAdapter = new DeviceAdapter(this, deviceList);
devRssiValues = new HashMap<String, Integer>();
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(deviceAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
scanLeDevice(true);
}
private void scanLeDevice(final boolean enable) {
final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
cancelButton.setText(R.string.scan);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
cancelButton.setText(R.string.cancel);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
cancelButton.setText(R.string.scan);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
addDevice(device, rssi);
}
});
}
};
private void addDevice(BluetoothDevice device, int rssi) {
boolean deviceFound = false;
for (BluetoothDevice listDev : deviceList) {
if (listDev.getAddress().equals(device.getAddress())) {
deviceFound = true;
break;
}
}
devRssiValues.put(device.getAddress(), rssi);
if (!deviceFound) {
deviceList.add(device);
mEmptyList.setVisibility(View.GONE);
deviceAdapter.notifyDataSetChanged();
}
}
#Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
}
#Override
public void onStop() {
super.onStop();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
#Override
public void onDestroy() {
super.onDestroy();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice device = deviceList.get(position);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
Bundle b = new Bundle();
b.putString(BluetoothDevice.EXTRA_DEVICE, deviceList.get(position).getAddress());
Intent result = new Intent();
result.putExtras(b);
setResult(Activity.RESULT_OK, result);
Toast.makeText(getApplicationContext(), "Connected to " + deviceList.get(position).getName(), Toast.LENGTH_SHORT).show();
finish();
}
};
public void onPause() {
super.onPause();
scanLeDevice(false);
}
class DeviceAdapter extends BaseAdapter {
Context context;
List<BluetoothDevice> devices;
LayoutInflater inflater;
public DeviceAdapter(Context context, List<BluetoothDevice> devices) {
this.context = context;
inflater = LayoutInflater.from(context);
this.devices = devices;
}
#Override
public int getCount() {
return devices.size();
}
#Override
public Object getItem(int position) {
return devices.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup vg;
if (convertView != null) {
vg = (ViewGroup) convertView;
} else {
vg = (ViewGroup) inflater.inflate(R.layout.device_list_element, null);
}
BluetoothDevice device = devices.get(position);
final TextView tvadd = ((TextView) vg.findViewById(R.id.address));
final TextView tvname = ((TextView) vg.findViewById(R.id.name));
final TextView tvpaired = (TextView) vg.findViewById(R.id.paired);
final TextView tvrssi = (TextView) vg.findViewById(R.id.rssi);
tvrssi.setVisibility(View.VISIBLE);
byte rssival = (byte) devRssiValues.get(device.getAddress()).intValue();
if (rssival != 0) {
tvrssi.setText("Rssi = " + String.valueOf(rssival));
}
tvname.setText(device.getName());
tvadd.setText(device.getAddress());
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.i(TAG, "device::" + device.getName());
tvname.setTextColor(Color.BLACK);
tvadd.setTextColor(Color.BLACK);
tvpaired.setTextColor(Color.GRAY);
tvpaired.setVisibility(View.VISIBLE);
tvpaired.setText(R.string.paired);
tvrssi.setVisibility(View.VISIBLE);
tvrssi.setTextColor(Color.BLACK);
} else {
tvname.setTextColor(Color.BLACK);
tvadd.setTextColor(Color.BLACK);
tvpaired.setVisibility(View.GONE);
tvrssi.setVisibility(View.VISIBLE);
tvrssi.setTextColor(Color.BLACK);
}
return vg;
}
}
private void showMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
So i developed an android news app. A spinner item is available on the toolbar and data reloads according to spinner selection. However, when the data reloads, for some of the items, it directly loads the relevant content but for some others, it loads the previously selected spinner data. Current data for the current item only shows after reloading same spinner data using the swipe refresh functionality which i had implemented. I want the correct data relevant to that selection to load the first time itself without having to refresh all the time.
Below is my MainActivity where all these functions are called.
package com.example.app.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessaging;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="url" //outputs JSON data
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
prefManager = new PrefManager(MainActivity.this);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if (++check > 1) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
//intent.putExtra("NAME_KEY", itemSelected);
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
#Override
public int getCount() {
return pager_number;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).equals(myString)) {
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//TODO DONE
String name = prefManager.spinReadString();
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
//TODO DONE
if (spinConstituency.equals(name))
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
//TODO DONE
prefManager.writeString("" + spinConstID);
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position % 2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
I discovered that from API level 3, one can use the onUserInteraction() on an Activity with a boolean value thereby determining the user's interaction.
Find the documentation in the link below.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
#Override
public void onUserInteraction() {
super.onUserInteraction();
userInteracts = true;
}
The my adjustment goes as thus in the MainActivity.java
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (IsInteracting) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
In Google play service 10.0.1, for the following code, when building it I get the error:
“GooglePlayServicesClient” cannot resolve the symbol
Any idea how to resolve this?
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationRequest;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.asyncTasks.EmployeeSerchResult;
import com.shuan.Project.asyncTasks.GetEmployeeSerach;
import com.shuan.Project.employer.PostViewActivity;
import java.util.List;
import java.util.Locale;
public class EmplyeeSearchActivity extends AppCompatActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private Toolbar toolbar;
private Common mApp;
private Boolean flag = false;
private LocationClient mLocationClient;
private ProgressDialog pDialog;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Location mLastLocation;
private ProgressBar progressBar;
private ListView list;
private AutoCompleteTextView preferSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
mApp = (Common) getApplicationContext();
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
setTheme(R.style.Junior);
} else {
setTheme(R.style.Senior);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emplyee_search);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
if (mApp.getPreference().getString(Common.LEVEL, "").equalsIgnoreCase("1")) {
toolbar.setBackgroundColor(getResources().getColor(R.color.junPrimary));
} else {
toolbar.setBackgroundColor(getResources().getColor(R.color.senPrimary));
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
mLocationRequest = new LocationRequest();
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
list = (ListView) findViewById(R.id.ser_res);
preferSearch = (AutoCompleteTextView) findViewById(R.id.prefered_serach);
new GetEmployeeSerach(EmplyeeSearchActivity.this, progressBar, preferSearch).execute();
preferSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_SEARCH){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
preferSearch.dismissDropDown();
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, preferSearch.getText().toString(),
"all").execute();
}
return false;
}
});
preferSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
TextView txt = (TextView) view.findViewById(R.id.display);
TextView txt1 = (TextView) view.findViewById(R.id.ins_name);
preferSearch.setText(txt.getText().toString());
progressBar.setVisibility(View.VISIBLE);
new EmployeeSerchResult(EmplyeeSearchActivity.this, progressBar, list, txt.getText().toString(),
txt1.getText().toString()).execute();
}
});
preferSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
list.setAdapter(null);
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
Intent in = new Intent(getApplicationContext(), PostViewActivity.class);
in.putExtra("jId", txt.getText().toString());
in.putExtra("apply", "no");
startActivity(in);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.emp_search_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.gps) {
flag = gpsStatus();
if (flag) {
new displayCurrentLocation().execute();
} else {
showGpsAlert();
}
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onDisconnected() {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public class displayCurrentLocation extends AsyncTask<String, String, String> {
String location;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EmplyeeSearchActivity.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Searching");
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Location currentLocation = mLocationClient.getLastLocation();
Geocoder geocoder = new Geocoder(EmplyeeSearchActivity.this, Locale.getDefault());
Location loc = currentLocation;
List<android.location.Address> addresses;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
final android.location.Address address = addresses.get(0);
location = address.getLocality();
}
} catch (Exception e) {
}
return location;
}
#Override
protected void onPostExecute(final String s) {
super.onPostExecute(s);
pDialog.cancel();
Intent in = new Intent(getApplicationContext(), EmployeeSearchResultActivity.class);
in.putExtra("loc", s);
startActivity(in);
}
}
private void showGpsAlert() {
AlertDialog.Builder build = new AlertDialog.Builder(EmplyeeSearchActivity.this);
build.setTitle("Alert")
.setMessage("Turn On your GPS! Find the Jobs & companies")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);
dialog.cancel();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "Can't Find Employer", Toast.LENGTH_SHORT).show();
}
}).show();
}
private Boolean gpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStus) {
return true;
} else {
return false;
}
}
}
as mentioned in this answer i guess GooglePlayServiceClient and has become outdated so remove it and use GoogleApiClientinstead.Also LocationServices.API, and FusedLocationProviderApi were introduced.
Usage of GoogleApiClient :
To use GoogleApiClient the first thing to change is the interface, the activity or service is implementing
//old code of GooglePlayServiceClient :
public class LocationMonitoringService extends Service implements GooglePlayServicesClient.ConnectionCallbacks
//replace the above ^ code with this: new code for GoogleApiClient
public class LocationMonitoringService extends Service implements GoogleApiClient.ConnectionCallbacks
in GooglePlayServiceClient, mLocationClient was just a regular class constructor.
inGoogleApiClient a Builder is used like :
//old code of GooglePlayServiceClient :
LocationClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new LocationClient(this, this, this);
mLocationClient.connect();
}
replace it^ with new builder code of GoogleApiClient :
GoogleApiClient mLocationClient;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mLocationClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationClient.connect();
}
Examples :
Requesting location :
Old code was just a simple call like
mLocationClient.requestLocationUpdates(mLocationRequest, locationListener);
in GoogleApiClient we use FusedLocatonApi like :
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, locationListener);
This post shows you a implementation of most of the methods like :onConnected onConnectionFailed onConnectionSuspended etc.
I have a problem with admob ads.
The banner ad seems to work fine but the Interstitial is not loading.
I have tried various solutions, generating different ad unit id's and trying admob test ids.
QuoteActivity.java
package com.axdev.thequotesgarden;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
public class QuoteActivity extends ActionBarActivity implements
TextToSpeech.OnInitListener {
private int ID;
private String mode,fav,text;
private Quote qte;
private DataBaseHandler db;
private ArrayList<Quote> myList = new ArrayList<Quote>();
private TextView textAuth,textQuote;
private ImageView imgIcon;
private ImageButton btnNext,btnPrevious;
private TextToSpeech tts;
private RoundImage roundedImage;
private AdView adView;
private InterstitialAd interstitial;
SharedPreferences sharedPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(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));
}
db = new DataBaseHandler(this);
textAuth = (TextView) findViewById(R.id.textAuth);
textQuote = (TextView) findViewById(R.id.textQuote);
imgIcon = (ImageView) findViewById(R.id.imgcon);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnPrevious = (ImageButton) findViewById(R.id.btn_prev);
Typeface fontQuote = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Light.ttf");
Typeface fontAuth = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Italic.ttf");
textQuote.setTypeface(fontQuote);
textQuote.setTextSize(18);
textAuth.setTypeface(fontAuth);
ID = getIntent().getExtras().getInt("id");
mode = getIntent().getExtras().getString("mode");
if(mode.equals("qteday")){
qte = db.getQuote(ID);
btnNext.setVisibility(View.GONE);
btnPrevious.setVisibility(View.GONE);
}
else {
myList = (ArrayList<Quote>) getIntent().getSerializableExtra("array");
qte = myList.get(ID);}
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID < (myList.size() - 1)) {
ID++;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID > 0) {
ID--;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
fav = qte.getFav();
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuote);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
if(mode.equals("qteday")){
tts = new TextToSpeech(this, this);
speakOut();
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getResources().getString(R.string.interstitial_ad_unit_id));
AdRequest adRequest2 = new AdRequest.Builder().build();
interstitial.loadAd(adRequest2);
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayInterstitial();
}
});
}
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void checkPicure(){
boolean isExist = false;
InputStream imageStream = null;
try {
imageStream = getAssets().open("authors/"+qte.getFileName()+".jpg");
isExist =true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isExist != false){
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
roundedImage = new RoundImage(theImage);
imgIcon.setImageDrawable(roundedImage );
}
else {
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.mipmap.author);
roundedImage = new RoundImage(bm);
imgIcon.setImageDrawable(roundedImage);
}
}
public void doShare() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Quote");
intent.putExtra(Intent.EXTRA_TEXT,
qte.getQuote() + " - " + qte.getName());
QuoteActivity.this.startActivity(Intent.createChooser(intent,
getResources().getString(R.string.share)));
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Locale loc = new Locale("en", "UK");
tts.setLanguage(loc);
tts.setSpeechRate((float) 0.8);
speakOut();
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean speaker = sharedPrefs.getBoolean("prefSpeaker", true);
if (speaker.equals(true)) {
text = qte.getQuote() + "\n" + qte.getName();
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
else {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, 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_quote, menu);
if (fav.equals("0")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.not_fav);
}
if (fav.equals("1")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.fav);
}
;
return true;
}
#TargetApi(11)
private void copyToClipBoard(String qte) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(qte);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("text", qte);
clipboard.setPrimaryClip(clip);
}
}
#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 android.R.id.home:
this.finish();
break;
case R.id.action_share:
doShare();
break;
case R.id.copy:
String text = qte.getQuote() + "- " + qte.getName();
copyToClipBoard(text);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.copy_msg),
Toast.LENGTH_LONG).show();
break;
case R.id.action_favorite:
if (qte.getFav().equals("0")) {
qte.setFav("1");
db.updateQuote(qte);
item.setIcon(R.mipmap.fav);
} else if (qte.getFav().equals("1")) {
qte.setFav("0");
db.updateQuote(qte);
item.setIcon(R.mipmap.not_fav);
}
}
return true;
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
QuotesActivity.java
package com.axdev.thequotesgarden;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import java.util.ArrayList;
import java.util.List;
public class QuotesActivity extends ActionBarActivity {
private ArrayList<Quote> imageArry = new ArrayList<Quote>();
private QuotesListAdapter adapter;
private String Activitytype;
private DataBaseHandler db;
private ListView dataList;
private int count;
private ImageView noQuotes;
private AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(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));
}
db = new DataBaseHandler(this);
noQuotes = (ImageView)findViewById(R.id.NoQuotes);
adapter = new QuotesListAdapter(this, R.layout.quote_items, imageArry);
dataList = (ListView) findViewById(R.id.quotesList);
Button btnLoadMore = new Button(this);
btnLoadMore.setBackgroundResource(R.drawable.btn_green);
btnLoadMore.setText(getResources().getText(R.string.btn_LoadMore));
btnLoadMore.setTextColor(0xffffffff);
Activitytype = getIntent().getExtras().getString("mode");
if (Activitytype.equals("isCategory")) {
String categoryValue = getIntent().getExtras()
.getString("category");
List<Quote> contacts = db.getQuotesByCategory(categoryValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
}
if (Activitytype.equals("isAuthor")) {
String authorValue = getIntent().getExtras().getString("name");
List<Quote> contacts = db.getQuotesByAuthor(authorValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
}
if (Activitytype.equals("isFavorite")) {
actionBar.setTitle(getResources().getText(R.string.title_activity_favorites));
List<Quote> contacts = db.getFavorites();
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
if (imageArry.isEmpty()){
noQuotes.setVisibility(View.VISIBLE);
}
}
if (Activitytype.equals("allQuotes")) {
List<Quote> contacts = db.getAllQuotes(" LIMIT 50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
dataList.addFooterView(btnLoadMore);
}
dataList.setAdapter(adapter);
dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
Intent i = new Intent(getApplicationContext(),
QuoteActivity.class);
Quote srr = imageArry.get(position);
i.putExtra("id",position);
i.putExtra("array", imageArry);
i.putExtra("mode", "");
startActivity(i);
}
});
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new loadMoreListView().execute();
}
});
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuotes);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Before starting background task
// Show Progress Dialog etc,.
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
count += 50;
List<Quote> contacts = db.getAllQuotes(" LIMIT "+count+ ",50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
int currentPosition = dataList.getFirstVisiblePosition();
adapter = new QuotesListAdapter(QuotesActivity.this, R.layout.quote_items, imageArry);
dataList.setSelectionFromTop(currentPosition + 1, 0);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
}
}
#Override
public void onBackPressed()
{
finish();
super.onBackPressed(); // optional depending on your needs
}
#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_quotes, 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.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
}
return true;
}
}
The simplest answer is that mode is not equal to "qteday"
if(mode.equals("qteday")){
Unless that is true, the interstitial will never be loaded.
I am beginner in android development. Below i give my main activity.java code. My requirement if internet connection or wifi not working on mobile devices then following thing perform
If internet connection not working then show the my splash screen backrgound on start of application and give the dialogue box or alert like this screenshot of trip advisor Check this image and screenshot. If cancel button press then dialogue box disappear and only display splash screen and if press try again then try to perform connect to internet.
In my code i take the code buy dialogue box, i not want buy function this is not my requirement. i want exactly like trip advisor. For me easy if somebody edit the my code and show where make changes very thanks in advance
package com.example.edarabia;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity{
WebView mywebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebview = (WebView) findViewById(R.id.webview);
if(isNetworkConnected() == true){
mywebview.getSettings().setJavaScriptEnabled(true);
mywebview.setWebViewClient(new myWebClient());
mywebview.loadUrl("http://www.grafdom.com/operations/projects/ma/edarabiaapp/");
mywebview.getSettings().setBuiltInZoomControls(true);
mywebview.getSettings().setLoadWithOverviewMode(false);
mywebview.getSettings().setUseWideViewPort(false);
}else{
showBuyDialog();
}
}
// #Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
// if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
// mywebview.goBack();
// return true;
// }
// return super.onKeyDown(keyCode, event);
// }
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
mywebview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
finish();
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
//// This method will retun boolean value if net conect then value will be true otherwise false
private boolean isNetworkConnected() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showBuyDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("just for testing");
builder.setMessage("Check you net conectivity....");
builder.setCancelable(false);
builder.setPositiveButton("Buy", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent browserIntent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("https://www.google.com"));
startActivity(browserIntent);
}
});
builder.show();
}
}
This might be helpful:
Detect whether there is an Internet connection available on Android
or try digging into BroadcastReceivers.
Sample code:
public class InternetConnectionStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
_v("Network connectivity change");
if (intent.getExtras() != null) {
NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
_v("Network " + ni.getTypeName() + " connected");
onNetworkConnection(context, true);
}
}
if (intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
_v("There's no network connectivity");
onNetworkConnection(context, false);
}
}
private void onNetworkConnection(Context context, boolean isConnected) {
//show dialog
}
}
I got the solution and below the updated code
package com.example.edarabia;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity{
WebView mywebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isNetworkConnected() == true){
setContentView(R.layout.activity_main);
mywebview = (WebView) findViewById(R.id.webview);
mywebview.getSettings().setJavaScriptEnabled(true);
mywebview.setWebViewClient(new myWebClient());
mywebview.loadUrl("http://www.grafdom.com/operations/projects/ma/edarabiaapp/");
mywebview.getSettings().setBuiltInZoomControls(true);
mywebview.getSettings().setLoadWithOverviewMode(false);
mywebview.getSettings().setUseWideViewPort(false);
}else{
setContentView(R.layout.splash);
showBuyDialog();
}
}
// #Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
// if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
// mywebview.goBack();
// return true;
// }
// return super.onKeyDown(keyCode, event);
// }
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && mywebview.canGoBack()) {
mywebview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
finish();
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
//// This method will retun boolean value if net conect then value will be true otherwise false
private boolean isNetworkConnected() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showBuyDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Unable to connect");
builder.setMessage("You Must have an Internet connection to use Edarabia. Please connect and try again.");
builder.setCancelable(false);
builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
builder.show();
}
}
Try to replace showButDialog() method,
public void showBuyDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Unable to connect");
builder.setMessage("You must have an Internet connection to use TripAdvisor. Please connect and try again.");
builder.setCancelable(false);
builder.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
isNetworkConnected();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
And to get the UI same as in the picture, add following line before application tag, like this,
<uses-sdk android:targetSdkVersion="15" />
This kind of dialog is available from Android OS 3.0 (Honey Comb) and above. So you cannot see dialog in previous versions.