In my application there are two class one is InternetActivity which only extends Activity and sets contentview to main. and MyClass that extends broadcast receiver.
I have 2 TextView and 2 ImageView of WIFI and GPRS in main.xml file.
When changes in connectivities are happening,brodcast receiver is getting called and according to what is enabled and what is not i want to set visibility of TextView and ImageView. But it is only showing both the images and not the changes.
here is MyClass.java file. how can i do it??
public class MyClass extends BroadcastReceiver {
private static ImageView wifi_image, gprs_image;
private static TextView wifi_text, gprs_text;
#Override
public void onReceive(Context context, Intent intent) {
Log.i("IntrntActivity", "Broadcast message receivved");
LinearLayout layout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
View view = View.inflate(context, R.layout.main, layout);
wifi_image = (ImageView) view.findViewById(R.id.wifi_image);
gprs_image = (ImageView) view.findViewById(R.id.gprs_image);
wifi_text = (TextView) view.findViewById(R.id.wifi_text);
gprs_text = (TextView) view.findViewById(R.id.gprs_text);
wifi_image.setVisibility(View.GONE);
wifi_text.setVisibility(View.GONE);
gprs_image.setVisibility(View.GONE);
gprs_text.setVisibility(View.GONE);
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo WIFI = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo Mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (!WIFI.isConnected() && WIFI.isAvailable()) {
Toast.makeText(context, "WIFI is available but not connected",
Toast.LENGTH_LONG).show();
}
if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isAvailable()) {
wifi_image.setVisibility(View.VISIBLE);
wifi_text.setVisibility(View.VISIBLE);
}
if (Mobile.isConnected()) {
gprs_image.setVisibility(View.VISIBLE);
gprs_text.setVisibility(View.VISIBLE);
Log.i("IntrntActivity", "Mobile isConnected");
// Toast.makeText(context,"GPRS is available",
// Toast.LENGTH_LONG).show();
}
if (!Mobile.isConnected()) {
gprs_image.setVisibility(View.GONE);
gprs_text.setVisibility(View.GONE);
Log.i("IntrntActivity", "Mobile is Not Connected");
// Toast.makeText(context,"GPRS is available",
// Toast.LENGTH_LONG).show();
}
}
}
P.S : It is correctly going in Mobile.isConnected() and !Mobile.isConnected() and showing it in Log file but its Visibility is not changing.Am i not setting the view correctly? and is it possible to call setContentView(view) from this broadcast receiver?
You need to put your reciever into InternetActivity class, register it there and use already defined local variables. You need not to create separate public BroadcastReceiver implementation, just do a local one.
Like this:
import android.content.BroadcastReceiver;
import android.content.Context;
public class InternetActivity extends Activity {
private ImageView image;
private TextView text;
private BroadcastReceiver reciever = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
// do all the checking
// interact with image and text
}
};
#Override
public void onCreate(Bundle state) {
setContentView(R.layout.....);
// fill in image and text variables
}
#Override
public void onStart() {
registerReceiver(receiver, /* your intent filter here */);
}
#Override
public void onStop() {
unregisterReceiver(receiver);
}
}
You are nowhere adding the inflated view to your activity content view?!
You should have everything inflated and set as the content view in the onCreate method. Then your broadcast receiver should only be setting the visibility of the selected views.
class MyActivity extends Activity {
private ImageView wifiIcon;
public void onCreate() {
setContentView(...);
wifiIcon = (ImageView) findViewById(...);
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// ...
wifiIcon.setVisibility( isWifiEnabled ? View.VISIBLE : View.GONE);
}
};
}
Related
I am working on a budget app and am having trouble getting my expenses to the class that will create a graph. The user will be able to input an expense along with a check box indicating what they spent money on. When I send the value to MainActivity, it reads the expense and shows the updated budget, however, when I try to read it in my class that will make a graph, the graph shows up empty and is not reading the values. Here is my Expense Activity (Screen 2):
public class ExpensesActivity extends AppCompatActivity {
EditText editTextExpense;
Expenses expenses;
String selectedCheckBox;
CheckBox personalCheckBox;
CheckBox commuteCheckBox;
CheckBox billsCheckBox;
CheckBox funCheckBox;
CheckBox workCheckBox;
CheckBox foodCheckBox;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expenses);
editTextExpense = (EditText)findViewById(R.id.moneySpent);
personalCheckBox = (CheckBox)findViewById(R.id.personalCheckBox);
commuteCheckBox = (CheckBox)findViewById(R.id.commuteCheckBox);
billsCheckBox = (CheckBox)findViewById(R.id.billsCheckBox);
funCheckBox = (CheckBox)findViewById(R.id.funCheckBox);
workCheckBox = (CheckBox)findViewById(R.id.workCheckBox);
foodCheckBox = (CheckBox)findViewById(R.id.foodCheckBox);
backToMainMenu();
}
public void backToMainMenu() {
final Button expenseButton = (Button)findViewById(R.id.addExpenseSecondScreen);
expenseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (personalCheckBox.isChecked()) {
selectedCheckBox = personalCheckBox.getText().toString();
}
if (commuteCheckBox.isChecked()) {
selectedCheckBox = commuteCheckBox.getText().toString();
}
if (billsCheckBox.isChecked()) {
selectedCheckBox = billsCheckBox.getText().toString();
}
if (funCheckBox.isChecked()) {
selectedCheckBox = funCheckBox.getText().toString();
}
if (workCheckBox.isChecked()) {
selectedCheckBox = workCheckBox.getText().toString();
}
if (foodCheckBox.isChecked()) {
selectedCheckBox = foodCheckBox.getText().toString();
}
float expense = Float.parseFloat(editTextExpense.getText().toString());
Intent intent = getIntent();
intent.putExtra("expense", expense);
intent.putExtra("checkBoxText", selectedCheckBox);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
I am not sure what you are expecting here but onActivityResult is used to get the result from starting an Activity using startActivityForResult and will only be called in the activity which called startActivityForResult.
Since activities are only active one at a time (unless you are targeting the N preview) you would have to pass the result data using the start intent to the other activity.
Use BroadcastReceiver register the BroadcastReceiver to both activity and fire the BroadcastReceiver when you want to send the data. Use LocalBroadcastManager
sample code to create BroadcastReceiver
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
registerReceiver(receiver, filter);
and unregister in onDestroy()
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
I don't know exactly what you want,are you tried "static" for expense and
selectedCheckBox variables.Then you easily get the values from any where or use
shared preference.
I know this question has been asked many times but still i am unable to solve my problem.I want to get the OTP from the SMS in the editText of the Activity.For this i am using broadcast receiver.
Code for broadcast receiver:
private static final String TAG = ReceiveSms.class.getSimpleName();
private SmsReceivedListner smsReceived = null;
#Override
public void onReceive(Context context, Intent intent) {
//code to get sms....
Log.e(TAG, "OTP received: " + verificationCode);
if (smsReceived != null) {
smsReceived.onSmsReceived(verificationCode);
} else {
if (Constants.isLoggingEnable) {
Logger.logError(TAG, "Sms listner is null");
}
}
}
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
public void setOnSmsReceivedListener(Context context) {
this.smsReceived = (SmsReceivedListner) context;
}
Activity Code
public class EnterOtp extends MasterActivity implements View.OnClickListener, OnTaskComplete, SmsReceivedListner {
private static final String TAG = EnterOtp.class.getSimpleName();
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otp);
context = this;
init();
}
private void init() {
setUpToolbar();
receiveSms = new ReceiveSms();
receiveSms.setOnSmsReceivedListener(this);
}
I have used interface but always i am getting it as null.So what can i do to get the otp.
P.S-
I dont want to start new Activity via intent because the activity is running only, so if via Intent can i pass the otp without starting new Activity and also maintaing the back stack as well?
If you want receive sms only when activity is running use this code:
private void init()
{
receiveSms = new ReceiveSms();
receiveSms.setOnSmsReceivedListener(this);
registerReceiver(receiveSms, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
And remove this receiver from AndroidManifest.xml
I hope it helped you.
EDIT:
In onDestroy you must use this code:
protected void onDestroy()
{
super.onDestroy();
// ...
unregisterReceiver(receiveSms);
}
I am having a "Receiver no registered exception" in OnDestroy method of my app using fragments.
I have a MainActiviy class where I check if the user registered an account.
If not account created, I load the register account class fragment to allow the user create an account.
After the user create the account clicking a button I restart the MainActivity class.
I need to register a broadcastreceiver only after the user create an account.
But, after the restart the MainActivity class from Frgamnent Class, I am getting an exception of receiver not registered in event OnDestroy of Main Activity.
Any help to solve it will be appreciated.
Thanks in Advance, Luiz
My MainActivity Class
public class MainActivity extends Activity {
// if run on phone, isSinglePane = true
// if run on tablet, isSinglePane = false
static boolean isSinglePane;
private GcmUtil gcmUtil;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v = findViewById(R.id.phone_container);
if (!AccountRegisterCreated()){
//this fragmment register an account to user, and save in Preferences
RegisterFragment myListFragment= new RegisterFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.phone_container, myListFragment);
fragmentTransaction.commit();
return;
}
registerReceiver(registrationStatusReceiver, new IntentFilter(Common.ACTION_REGISTER));
}
private BroadcastReceiver registrationStatusReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && Common.ACTION_REGISTER.equals(intent.getAction())) {
switch (intent.getIntExtra(Common.EXTRA_STATUS, 100)) {
case Common.STATUS_SUCCESS:
getActionBar().setSubtitle("online");
break;
case Common.STATUS_FAILED:
getActionBar().setSubtitle("offline");
break;
}
}
}
};
#Override
protected void onPause() {
ContentValues values = new ContentValues(1);
super.onPause();
}
#Override
protected void onDestroy() {
unregisterReceiver(registrationStatusReceiver);
super.onDestroy();
}
private boolean AccountRegisterCreated(){
SharedPreferences prefs;
prefs= PreferenceManager.getDefaultSharedPreferences(this);
String fullname = prefs.getString(DataProvider.COL_EMAIL,"");
if (!fullname.isEmpty()) {
return true;
}
return false;
}
}
My Fragment Class:
public class RegisterFragment extends Fragment {
private static SharedPreferences prefs;
static final String TAG = "pushabout";
TextView name;
TextView email;
TextView password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.register, null);
name = (TextView) view.findViewById(R.id.reg_fullname);
email = (TextView) view.findViewById(R.id.reg_email);
password = (TextView) view.findViewById(R.id.reg_password);
if (email.getText().toString().isEmpty()){
email.setText(Common.getPreferredEmail());
}
Button mButton = (Button) view.findViewById(R.id.btnRegister);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//checa email e reg e salva pref e registra gcm
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = prefs.edit();
editor.putString(DataProvider.COL_NAME, sname);
editor.putString(DataProvider.COL_EMAIL, semail);
editor.putString(DataProvider.COL_PWD, spassword);
editor.commit();
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
return view;
}
}
The problem is not with the Fragment. It's the BroadcastReceiver in your Activity.
Try declaring your BroadcastReceiver as a class field:
public class MainActivity extends Activity {
...
BroadcastReceiver mBroadcastReceiver;
...
Then, you should change how you're creating and registering the receiver. The way I've done it is by registering during the activity's onResume instead of onCreate(). If you do this, you'll also need to unregister during onPause() instead of onDestroy(). It will look something like this:
#Override
public void onResume() {
super.onResume();
// Create and register your receiver here.
if (AccountRegisterCreated) {
mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
....
}
}
registerReceiver(mBroadcastReceiver, new IntentFilter(Common.ACTION_REGISTER));
}
...
}
#Override
public void onPause() {
super.onPause();
// Unregister your receiver here
if (mBroadcastReceiver != null) {
unregisterReceiver(mBroadcastReceiver);
}
}
Just declare a member variable of type boolean. When you register the BroadcastReceiver, set that variable to true. In onDestroy() only call unregisterReceiver() if the variable is true.
I have an adapter used to display messages on the list view alike messages in chat application . I am able to display the content flawlessly once the activity is created , but when I go back and create activity again , adapter don't work as usual .
What I found in debugging is follows:
function receives() is called when message is received and update the
register , as I mentioned above there is no problem to display the
data in list view once the activity is created , but once I go back
and relauch the activity I am not able to display received messages .
Is there something I am missing in onResume() onPause or onStart() method with respect to custom adapter such as registering or decalring the custom adapter again? Thanks for help.
Following is the code of my activity class which uses custom adapter to display sent and received messages:
public class hotListener extends ListActivity {
private XMPPConnection connection;
private IBinder binder;
private Handler mHandler = new Handler();
private ArrayList<String> messages = new ArrayList<String>();
ArrayList<ChatMessage> messagex= new ArrayList<ChatMessage>();;
ChattingAdapter adaptex;
Intent mIntent ;
private ListView listview;
EditText sender_message ;
String msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listener);
//messagex.add(new ChatMessage("Hello", false));
adaptex = new ChattingAdapter(getApplicationContext(),messagex);
setListAdapter(adaptex);
Button send_button = (Button) findViewById(R.id.chat_send_message);
sender_message = (EditText) findViewById(R.id.chat_input);
send_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg = sender_message.getText().toString();
sender_message.setText("");
if(!(msg.length()==0)){
messagex.add(new ChatMessage(msg, true));
//addNewMessage(new ChatMessage(msg, true));
adaptex.notifyDataSetChanged();
getListView().setSelection(messagex.size()-1);
}
}
});
if(!isMyServiceRunning()){
System.out.println("seems like service not running");
startService(new Intent(this,xService.class));
System.out.print(" now started ");
}
}
#Override
protected void onStart(){
super.onStart();
Boolean kuch = bindService(new Intent(this,xService.class), mConnection,Context.BIND_AUTO_CREATE);
//System.out.println(kuch);
System.out.println("bind done");
}
private void receives(XMPPConnection connection2) {
//ChatManager chatmanager = connection.getChatManager();
connection2.getChatManager().addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat arg0, boolean arg1) {
arg0.addMessageListener(new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
final String from = message.getFrom();
final String body = message.getBody();
mHandler.post(new Runnable() {
ChatMessage kudi = new ChatMessage(body, false);
#Override
public void run() {
messagex.add(kudi);
adaptex.notifyDataSetChanged();
getListView().setSelection(messagex.size()-1);
Toast.makeText(hotListener.this,body,Toast.LENGTH_SHORT).show(); }
});
}
});
}
});
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
if(xService.class.getName().equals(service.service.getClassName())){
return true;
}
}
//System.out.print("false");
return false;
}
#Override
protected void onResume() {
bindService(new Intent(this, xService.class), mConnection, Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
protected void onPause() {
unbindService(mConnection);
super.onPause();
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
connection = null;
service = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
//System.out.println("binding in hot listener");
service = ((xService.MyBinder)binder).getService();
connection = service.getConnection();
receives(connection);
Log.wtf("Service","connected");
}
};
void addNewMessage(ChatMessage m)
{
System.out.println("1");
messagex.add(m);
System.out.println("2");
adaptex.notifyDataSetChanged();
System.out.println("3");
getListView().setSelection(messagex.size()-1);
}
}
Here is my custom adapter (there is no problem in custom adapter but adding to make things clear) :
public class ChattingAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<ChatMessage> mMessages;
public ChattingAdapter(Context context, ArrayList<ChatMessage> messages) {
super();
this.mContext = context;
this.mMessages = messages;
}
#Override
public int getCount() {
return mMessages.size();
}
#Override
public Object getItem(int position) {
return mMessages.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage message = (ChatMessage) this.getItem(position);
ViewHolder holder;
if(convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem, parent, false);
holder.message = (TextView) convertView.findViewById(R.id.text1);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.message.setText(message.getMessage());
LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();
//Check whether message is mine to show green background and align to right
if(message.isMine())
{ holder.message.setBackgroundResource(R.drawable.msgbox_new_selected_go_up);
lp.gravity = Gravity.RIGHT;
}
//If not mine then it is from sender to show orange background and align to left
else
{
holder.message.setBackgroundResource(R.drawable.msgbox_other_go_up);
lp.gravity = Gravity.LEFT;
}
holder.message.setLayoutParams(lp);
//holder.message.setTextColor(R.color.textColor);
return convertView;
}
private static class ViewHolder
{
TextView message;
}
#Override
public long getItemId(int position) {
//Unimplemented, because we aren't using Sqlite.
return position;
}
}
p.s: I am not storing any messages in sqlite as I dont want to restore messages for now, but I want new messages to be displayed at least onresume of activty. I can display sent messages after pressing send button but no received messages which works fine for the first time activity is created.
EDIT: I did more debugging , it turns out problem is not in resume activity , if I dont use receives() function for first time , and resume activity after going back , then receives() will work , that means , function inside receives() : getListView().setSelection(messagex.size()-1); works only once .
Either first time on receiving message or next time if and only if its not called first time on activity .
I think problem lies when you try to resume activity , you are still running the previous mHandler running and thus your instance of message is not destroyed and when you resume your activity it creates a problem . Make sure your mhandler destroys all instance of objects when unstop is called.
There's no place in your code where you save your messagex ArrayList. When you quit your activity by hitting back, your array get's distroyed (Garbage Collection takes care of it).
When you relaunch your activity your messagex ArrayList is created again, it's a brand new variable.
In fact, you're not relaunching your activity, you're creating a new instance.
EDIT:
I've never worked with the XMPPConnection objects before, but something else worth trying is the following:
When binding to the service, you're calling connection2.getChatManager().addChatListener and also arg0.addMessageListener but when unbinding you're not calling any removeXXX methods. I could be that since you're not removing your listeners, the whole XMPPConnection object still have references to the listeners that live in a dead Activity, and they are not being garbage collected.
Let's say that I've the following main activity:
public class MwConsoleActivity extends Activity {
private classChild child = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
child = new classChild();
}
}
Then consider the implementation of the class "classChild":
public class MwBondingAgent extends SapereAgent {
MwBondingAgent(){}
public void AddEventListener(childAddedEvent event) {
//Send the data of event back to the main activity
}
}
I've tried to use IntentServices but was not able to receive the values back to the main activity. What would be the approach I've to take?
Cheers
Ali
You can use and intentFilter to listen for broadcasts.
Add this to the activity:
IntentFilter intentFilter = new IntentFilter(
"com.unique.name");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
String msg_for_me = intent.getStringExtra("some_msg");
}
};
//registering our receiver
this.registerReceiver(mReceiver, intentFilter);
In your class add this to the part you want to notify the activity:
Intent i = new Intent("com.unique.name").putExtra("some_msg", "I have been updated!");
this.sendBroadcast(i);
You should use the observer / listener pattern.
http://www.vogella.com/articles/DesignPatternObserver/article.html
It is one of the most used design patterns when using MVC architecture pattern.
Your question is quite unclear but I think what you are wanting is to implement a callback to your activity. You can do this using an interface.
public class MwConsoleActivity extends Activity implements MwBondingAgent{
private classChild child = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
child = new classChild();
}
#Override
public void gotEventData(EventData myEventData) {
//to whatever you want with myEventData
}
}
And in your other class.
public class MwBondingAgent extends SapereAgent {
private MwBondingAgentCallback activityCallback;
MwBondingAgent(Activity callback){
activityCallback = callback;
}
public void AddEventListener(childAddedEvent event) {
//Send the data of event back to the main activity
EventData myEventData = //got some event data;
//Send it back to activity
activityCallback.gotEventData(myEventData);
}
public interface MwBondingAgentCallback {
public void gotEventData(EventData myEventData);
}
}