application class returning null value - android

This is my non-activity class:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class PostManager {
private Bundle bundle;
private Context context;
private Session session;
private String victimId=null;
public PostManager() {
SavedFriend savedFriend = new SavedFriend();
bundle = savedFriend.getBundle();
context = savedFriend.getContext();
session = savedFriend.getSession();
victimId = savedFriend.getfriendsId();
Log.e("postManager", victimId);
Log.e("postManager", bundle.getString("message"));
}
}
This is my application class:
import java.util.List;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import com.facebook.Session;
import com.facebook.model.GraphUser;
public class SavedFriend extends Application {
private List<GraphUser> selectedUsers;
private String friendsId;
private Session session;
private Bundle bundle;
private Context context;
public List<GraphUser> getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(List<GraphUser> selectedUsers) {
this.selectedUsers = selectedUsers;
}
public String getfriendsId() {
return friendsId;
}
public void setfriendsId(String id) {
this.friendsId = id;
}
public Session getSession(){
return session;
}
public void setSession(Session session){
this.session = session;
}
public void setContext(Context context){
this.context = context;
}
public Context getContext(){
return context;
}
public void setBundle(Bundle bundle){
this.bundle = bundle;
}
public Bundle getBundle(){
return bundle;
}
}
I have used the data of the application class in a fragment class (friendsId) which is not null.
When I call the application class's data from PostManager it returning the value null.
I have tried to see the value of friendsId and message by Log.e. but it gives me nullPointer exception.
Does that means all of the values I call in my PostManager constructor from application class are null? If yes, what should I do?
I need the session, applicationcontext, message, friendsId value in my PostManager class. I can pass these values to PostManager, but this class is called by onReceive() of alarm class which class extends BroadcastReceiver, and this alarm is set from another class which extend Fragment. All the values I need are created by this class except friendsId, and I don't know how to pass these value from first class->alarm class->postmanager class.
In manifest for alarm class:
<application android:name=".SavedFriend"
.......>
....
<receiver android:name="package name.Alarm"/>
....
</application>

You're creating a new instance of your Application subclass, so none of those member variables will be set.
Instead, you can use the approach from this question and store an easy to access static variable of your Application. Use something like this instead of creating a new instance.

Related

getViewBinding() method does not override method from its superclass BaseActivity

getViewBinding() method does not override method from its superclass BaseActivity<T extends ViewBinding>
MentorChatActivity.java
package com.ocr.firebaseoc.ui.chat;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.Query;
import com.ocr.firebaseoc.databinding.ActivityMentorChatBinding;
import com.ocr.firebaseoc.manager.ChatManager;
import com.ocr.firebaseoc.manager.UserManager;
import com.ocr.firebaseoc.model.Message;
import com.ocr.firebaseoc.ui.BaseActivity;
public class MentorChatActivity extends BaseActivity<ActivityMentorChatBinding> implements MentorChatAdapter.Listener {
private MentorChatAdapter mentorChatAdapter;
private String currentChatName;
private static final String CHAT_NAME_ANDROID = "android";
private static final String CHAT_NAME_BUG = "bug";
private static final String CHAT_NAME_FIREBASE = "firebase";
private UserManager userManager = UserManager.getInstance();
private ChatManager chatManager = ChatManager.getInstance();
#Override
protected ActivityMentorChatBinding getViewBinding() {
return ActivityMentorChatBinding.inflate(getLayoutInflater());
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configureRecyclerView(CHAT_NAME_ANDROID);
setupListeners();
}
private void setupListeners(){
// Chat buttons
binding.androidChatButton.setOnClickListener(view -> { this.configureRecyclerView(CHAT_NAME_ANDROID); });
binding.firebaseChatButton.setOnClickListener(view -> { this.configureRecyclerView(CHAT_NAME_FIREBASE); });
binding.bugChatButton.setOnClickListener(view -> { this.configureRecyclerView(CHAT_NAME_BUG); });
}
// Configure RecyclerView
private void configureRecyclerView(String chatName){
//Track current chat name
this.currentChatName = chatName;
//Configure Adapter & RecyclerView
this.mentorChatAdapter = new MentorChatAdapter(
generateOptionsForAdapter(chatManager.getAllMessageForChat(this.currentChatName)),
Glide.with(this), this);
mentorChatAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
binding.chatRecyclerView.smoothScrollToPosition(mentorChatAdapter.getItemCount()); // Scroll to bottom on new messages
}
});
binding.chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
binding.chatRecyclerView.setAdapter(this.mentorChatAdapter);
}
// Create options for RecyclerView from a Query
private FirestoreRecyclerOptions<Message> generateOptionsForAdapter(Query query){
return new FirestoreRecyclerOptions.Builder<Message>()
.setQuery(query, Message.class)
.setLifecycleOwner(this)
.build();
}
public void onDataChanged() {
// Show TextView in case RecyclerView is empty
binding.emptyRecyclerView.setVisibility(this.mentorChatAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
}
BaseActivity.java
package com.ocr.firebaseoc.ui;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;
import com.ocr.firebaseoc.databinding.ActivityMentorChatBinding;
/**
* Base Activity class that allow to manage all the common code for the activities
* #param <T> Should be the type of the viewBinding of your activity see more here
*/
public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity {
abstract T getViewBinding();
protected T binding;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initBinding();
}
/**
* Initialise the binding object and the layout of the activity
*/
private void initBinding(){
binding = getViewBinding();
View view = binding.getRoot();
setContentView(view);
}
}
Error message:
Class 'MentorChatActivity' must either be declared abstract or implement abstract method 'getViewBinding()' in 'BaseActivity'
Method does not override method from its superclass
Can someone please explain what went wrong ?
here's my project's github link
abstract T getViewBinding() is a package private, you can't override in other package. MentorChatActivity is in other package that's why its throwing error.
Make your abstract method public,
abstract public T getViewBinding(), or move all classes to same package.

Method from the library should not be called before declaring a particular variable

I have created an android project and converted it into a AAR(Android Resource) File. I have imported the file in a new project.
So there is one class called CollectSensorData which is a singleton class.
the class is as shown below:
package com.example.android.sensordata.Main;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.example.android.sensordata.localdatabase.DatabaseHelper;
import static android.content.Context.MODE_PRIVATE;
public class CollectSensorData {
#SuppressLint("StaticFieldLeak")
private static CollectSensorData instance;
static boolean flag;
private static Context mContext;
public static int freqlocaldb, freqserver;
public static SharedPreferences sharedpreferences;
public static String URL;
private CollectSensorData() {
}
public static CollectSensorData getInstance(Context context) {
if(instance==null) {
instance = new CollectSensorData();
}
mContext = context;
return instance;
}
public void onStartTrip(String Job_id, String Cab_Number, String Driver_ID, long time) {
String deviceModel = android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL;
sharedpreferences = mContext.getSharedPreferences("trip", MODE_PRIVATE);
flag = true;
DatabaseHelper.tripinfo(Job_id, time, Cab_Number, Driver_ID, deviceModel);
Intent intent = new Intent(mContext, MyService.class);
mContext.startService(intent);
}
public void onEndTrip() {
flag = false;
Intent intent = new Intent(mContext, MyService.class);
mContext.stopService(intent);
}
public void setFreqency(int FrequencyforLocalDB, int FrequencyforServer) {
freqlocaldb = FrequencyforLocalDB;
freqserver = FrequencyforServer;
}
}
There is a string that is to be specified by the user. If the string is not specified the methods mentioned above - onStartTrip, onEndTrip and setFrequency should not work.
How do I ensure that the string is specified before any of the methods are called?

Android - pass data between from an Activity class to an Adapter class

I have 3 classes: LoginActivity,MapsActivity and MatchAdapter
The first 2 extends AppCompactActivity, the last one ArrayAdapter.
When i make login (if correct, matching on mySQLiteDB) i used to get ID_contact of current user and pass it to MapsActivity with intent in such way:
On my LoginActivity:
String contact=databaseHelper.searchID_Contact(username,password);
Intent intent=new Intent(LoginActivity.this,MapsActivity.class);
intent.putExtra("ID_CONTACT",contact);
startActivity(intent);
On MapsActivity i can easily retrieve this data in such way:
public String getId_contact(String conct){
return conct;
}
#Override
public void onMapReady(GoogleMap googleMap) {
String id_contact1=getIntent().getStringExtra("ID_CONTACT");
String contact=getId_contact(id_contact1);
Toast.makeText(MapsActivity.this, contact, Toast.LENGTH_LONG).show();
}
Till now everything works fine, it appears the id of the current user.
My problem is to pass this data (with intent i don't know how) even to another class named MatchAdapter that extends ArrayAdapter.
I tried this way on MapsActivity:
public class MapsActivity extends AppCompatActivity implements ...{
public String getId_contact(){
String contact=getIntent().getStringExtra("ID_CONTACT");
return contact;
}
So on MatchAdaper trying to retrieve such way:
MapsActivity mapsActivity=new MapsActivity();
String text=mapsActivity.getId_contact().toString();
But nothing..i get NULLPOINTEREXCEPTION...Can someone help me?
Ok...found the solution...On MatchAdapter extends ArrayAdapter
DatabaseHelper databaseHelper=new DatabaseHelper(getContext());
...than OnClick function....
databaseHelper.myfunction();
Well you can access method of activity from an adapter by following way, Call this method from constructor of adapter or anywhere you want.
((ActivityName)context).methodName();
When you create a new instance of MapsActivity, that isn't the same Activity instance you got when you called startActivity(). This is basically why you have a null pointer exception.
More importantly, you should never be manually creating Activity instances using "new". Generally the system creates Activity objects for you via mechanisms like startActivity(), and that is how you should obtain them.
Himanshu's suggestion can work, if your activity does happen to be "hosting" your adapter, but this isn't always guaranteed. A better approach is to pass the ID to your MatchAdapter directly, either in the constructor or as a direct setter function. At the least, you should perform a "instanceof" check to make sure your adapter context is really of type MapsActivity.
That's my MatchAdapter `package vincenzo.futsal4you;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.MatchResult;
public class MatchAdapter extends ArrayAdapter{
List list=new ArrayList();
String text1=null;
MatchAdapter matchAdapter;
static String id_contatto3="";
String fatto3="";
Player player=new Player();
public MatchAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Match object) {
list.add(object);
super.add(object);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
final Context context = null;
final MatchHolder matchHolder;
final String cc=null;
if (row==null){
LayoutInflater layoutInflater=(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=layoutInflater.inflate(R.layout.display_match_row,parent,false);
matchHolder=new MatchHolder();
matchHolder.id_match=(TextView)row.findViewById(R.id.id_partita);
matchHolder.id_contact=(TextView)row.findViewById(R.id.id_contatto);
matchHolder.nome_partita=(TextView)row.findViewById(R.id.nome_partita);
matchHolder.citta=(TextView)row.findViewById(R.id.citta);
matchHolder.indirizzo=(TextView)row.findViewById(R.id.indirizzo);
matchHolder.data=(TextView)row.findViewById(R.id.data);
matchHolder.ora=(TextView)row.findViewById(R.id.ora);
// matchHolder.id_contact=row.findViewById()
matchHolder.join_us = (Button) row.findViewById(R.id.join_us);
row.setTag(matchHolder);
}
else {
matchHolder=(MatchHolder)row.getTag();
}
final Match match=(Match)getItem(position);
// matchHolder.id_contact.setText(mapsActivity.getId_partita().toString());
matchHolder.id_match.setText(match.getId().toString());
matchHolder.nome_partita.setText(match.getName().toString());
matchHolder.citta.setText(match.getCitta().toString());
matchHolder.indirizzo.setText(match.getIndirizzo().toString());
matchHolder.data.setText(match.getData().toString());
matchHolder.ora.setText(match.getOra().toString());
// assert ((MapsActivity) context) != null;
// ((MapsActivity) context).getId_partita();
// final String contact=matchHolder.getId_contatto();
Log.e("BOOOOOO", matchHolder.getId_contatto2());
final String fatto=matchHolder.getId_contatto2();
fatto3=matchHolder.getId_contatto2();
matchHolder.join_us.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//
String fatto2=matchHolder.getId_contatto2();
// final String text3=mapsActivity.getId_partita(cc).toString();
RelativeLayout rl = (RelativeLayout) v.getParent();
RelativeLayout r2 = (RelativeLayout) v.getParent();
// TextView tv = (TextView)rl.findViewById(R.id.nome_partita);
TextView tv = (TextView) rl.findViewById(R.id.id_partita);
TextView tv2 = (TextView) r2.findViewById(R.id.id_contatto);
String id_partita = tv.getText().toString();
String text2 = tv2.getText().toString();
Toast.makeText(getContext(), id_partita, Toast.LENGTH_SHORT).show();
// Toast.makeText(getContext(), matchHolder.setId_contatto(contact), Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),matchHolder.getId_contatto2(),Toast.LENGTH_SHORT).show();
player.setId_contatto(fatto3);
player.setId_partita(id_partita);
// databaseHelper=new DatabaseHelper(context);
// databaseHelper.insertPlayer2(player);
((MapsActivity)context).getJoinPlayer(player);
Toast pass1=Toast.makeText(getContext(), "One Row JOIN US created !", Toast.LENGTH_SHORT);
pass1.show();
}
});
return row;
}
static class MatchHolder{
TextView id_match,nome_partita,citta,indirizzo,data,ora,id_contact;
Button join_us;
public MatchHolder(){}
public String getId_contatto(String id_contatto) {
return id_contatto;
}
public String getId_contatto2() {
return id_contatto3;
}
public void setId_contatto(String id_contatto) {
id_contatto3 = id_contatto;
}
public MatchHolder(String id_contatto){
id_contatto3=id_contatto;
}
}
}
` So the problem was that i declared a String (id_contatto3) inside a static (inner) class (MatchHolder).Declaring it up to MatchAdapter i solve it somehow, but now i wanna call inside onClick a method that is inside another class (DatabaseHelper that extends SQLiteOpenhelper)..
I can't do ((DatabaseHelper)context).mymethod() So i've done the following "trick"...inside class MapsActivity where i've created a method (JoinPlayer) in such way:
public void JoinPlayer(Player player){
databaseHelper.insertPlayer(player);
}
where insertPlayer(Player) in DatabaseHelper is:
public void insertPlayer(Player player){
try{
db=this.getWritableDatabase();
}
catch(Exception e){
Log.e("ERROR","ERROR");
}
ContentValues contentValues=new ContentValues();
String query="select * from player";
Cursor cursor=db.rawQuery(query,null);
int count=cursor.getCount();
contentValues.put(COLUMN_ID_PLAYER,count);
contentValues.put(COLUMN_ID_MATCH_PLAYER,player.getId_partita());
contentValues.put(COLUMN_ID_CONTACT_PLAYER,player.getId_contatto());
db.insert(TABLE_PLAYER, null, contentValues);
db.close();
}
But Android suggest me to add a null condition(if ((MapsActivity)context)!=null) than ((MapsActivity)context).JoinPlayer(player) but it advise me it will be Always null and that's exactly what I get... I think is the context the main problem but have no clue right now how to solve it. Any Idea?

Access defaultSharedPreferences in class from service

Long story short, I have a class that handles my app shared preferences.
I call it from various other classes without issues, but when I try to call it from my service (from the same APK) I get a null exception. I am guessing that it's getting called from the wrong context or something like that. Here is the relevant code.
MainActivity.java
package com.deskwizard.audiomanager;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.deskwizard.audiomanager.DataSaveRestore;
public class MainActivity extends FragmentActivity {
public static Context contextOfApplication;
final FragmentManager fm = getFragmentManager();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contextOfApplication = getApplicationContext();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_settings, new FadeBalanceFragment());
ft.commit();
// TODO: Load previously saved settings for all values
DataSaveRestore.restore_all();
// TODO: init I2C
}
public static Context getContextOfApplication() {
return contextOfApplication;
}
}
DataSaveRestore.java (defaultpreferences class)
package com.deskwizard.audiomanager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class DataSaveRestore extends Application {
// Data variables
public static int Bass_level, Bass_CFreq, Bass_Qfact, Sub_level,
Sub_Lowpass, Treble_level, Treble_CFreq, Mid_level, Mid_CFreq,
Mid_Qfact, Fade, Balance, Loudness_level, Loudness_freq,
Loudness_boost;
static boolean Bass_DCMode, Loudness_state;
static Context applicationContext = MainActivity.getContextOfApplication();
public static void restore_all() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(applicationContext);
if (prefs.getInt("data_saved", 0) == 0) {
set_defaults();
load_defaults();
} else {
load_defaults();
}
//TODO: send settings to TDA7418
DS3903.set_lowpass(DataSaveRestore.Sub_Lowpass);
};
Service code snippet:
public class AudioManagerService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO do something useful
Log.d("com.deskwizard.audiomanager", "starting service...");
DataSaveRestore.restore_all(); // restore settings to TDA7418/DS3903
start();
return Service.START_STICKY;
}
The Null Exception error refers to this line, only when called from the service, it works properly from the main application and other classes:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(applicationContext);
Let me know if any further code can help narrow it down.
Thanks,
DW
Because, In your service when you call, DataSaveRestore.restore_all(); It make reference on, (As there is no MainActivity context available from Servce)
static Context applicationContext = MainActivity.getContextOfApplication();
on this line, applicationContext will be null as it can't find MainActivity initialization
Simply, Just change your restore_all() method from Application class.
First remove static and and use getApplicationContext() of Android application class method to get application context as in Service,
public void restore_all() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
if (prefs.getInt("data_saved", 0) == 0) {
set_defaults();
load_defaults();
} else {
load_defaults();
}
//TODO: send settings to TDA7418
DS3903.set_lowpass(DataSaveRestore.Sub_Lowpass);
};
Now call, restore_all(); by initializing object of Application class not a static way.
Like,
DataSaveRestore dataSaveRestore = (DataSaveRestore) getApplicationContext();
dataSaveRestore.restore_all();

Android: Register for another activity's onstop

Anyone know if I can receive my main Activity's onStop, onPause and onResume callbacks inside another class / object?
I've got a broadcast receiver that lives inside another class (a WebView). I use the receiver to detect when the network goes down and switch to a local copy of my page with some useful content. I need to un-register the broadcast receiver when onStop/onPause are called and re-register it during onResume.
I can do this by hand (I added a couple public methods to a class that extends WebView to do just that) , but it'd be nice to have Android just call it for me.
edit: Sure, here's the class, I'd like it to be able to receive get a callback from Android when my main activity's onStop gets called without having to call startInternetMonitoring() / stopInternetMonitoring():
package com.glimmersoft.spent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* #author Jer
*
*/
public class OfflineWebView extends WebView {
private BroadcastReceiver receiver;
private IntentFilter filter;
private Context myContext;
public OfflineWebView(Context context,AttributeSet attrs) {
super(context, attrs);
WebSettings webSettings = this.getSettings();
webSettings.setJavaScriptEnabled(true);
myContext = context;
}//END CLASS CONSTRUCTTOR
/**
* #param internetOn The URL to display in this OfflineWebView when there is an active Internet connection.
* #param internetOff The URL to display in this OfflineWebView if there is no active Internet connection.
*/
public void setPages(final String internetOn, final String internetOff){
final OfflineWebView finalThisRef = this;
filter = new IntentFilter();
filter.addAction(SpendConstants.ANDROID_CONNECTIVITY_CHANGED);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo()!=null&&cm.getActiveNetworkInfo().isConnected()){// TODO: THIS FAILES IF
finalThisRef.loadUrl(internetOn);
}else{
finalThisRef.loadUrl(internetOff);
}
}//END IF/ELSE
};
myContext.registerReceiver(receiver, filter);
}//END FUNCTION SETPAGES
public void startInternetMonitoring(){
myContext.registerReceiver(receiver, filter);
}//END METHOD STARTINTERNETMONITORING
public void stopInternetMonitoring(){
myContext.unregisterReceiver(receiver);
}//END METHOD STOPINTERNETMONITORING
}//END CLASS OfflineWebView
Thanks all!
Instead of putting your BroadcastReceiver inside your OfflineWebView, make it a static class you register maybe in a base Activity and have it a hold a reference to your OfflineWebView. When onReceive is called, you can then reference your OfflineWebView to load your online/offline content.
file: MyBaseActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.webkit.WebView;
public class MyBaseActivity extends Activity {
private static final String ANDROID_CONNECTIVITY_CHANGED = "android.net.conn.CONNECTIVITY_CHANGE";
protected static final ConnectivityBroadcastReceiver sReceiver = new ConnectivityBroadcastReceiver();
private static final IntentFilter sFilter = new IntentFilter(ANDROID_CONNECTIVITY_CHANGED);
static class ConnectivityBroadcastReceiver extends BroadcastReceiver {
private String internetOnUrl = "your online url";
private String internetOffUrl = "your offline url";
WebView offlineWebView;
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// only do your online/offline loading if we have a webview set
if (offlineWebView != null) {
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnected()) {
offlineWebView.loadUrl(internetOnUrl);
} else {
offlineWebView.loadUrl(internetOffUrl);
}
}
}
}
#Override
public void onStart() {
super.onStart();
// register receiver
registerReceiver(sReceiver, sFilter);
}
#Override
public void onStop() {
super.onStop();
// unregister receiver
unregisterReceiver(sReceiver);
}
}
file: MyActivity.java
import android.R;
import android.os.Bundle;
import android.webkit.WebView;
public class MyActivity extends MyBaseActivity {
private WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load your content root
setContentView(R.layout.main_layout);
// find your webview
mWebView = (WebView)findViewById(R.id.webView);
}
#Override
public void onStart() {
super.onStart();
// set your webview in the OfflineBroadcastReceiver
sReceiver.offlineWebView = mWebView;
}
#Override
public void onStop() {
super.onStop();
// clear your webview from the OfflineBroadcastReceiver
sReceiver.offlineWebView = null;
}
}

Categories

Resources