User Sign Up Null Pointer Exception - android

I am building a chat application in Android with backend MySQL, PHP nand running on local network with Apache. However, as a uses attempts to sign up, the LogCat displays a Nullpoint error on line 112, at "public void run()".
I have reviewed the code multiple times but cannot locate why a null point error persists...any siuggestions?
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.baidar.androidChatter.interfacer.Manager;
import com.baidar.androidChatter.serve.MessagingService;
public class SigningUp extends Activity {
private static final int FILL_ALL_FIELDS = 0;
protected static final int TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS = 1;
private static final int SIGN_UP_FAILED = 9;
private static final int SIGN_UP_USERNAME_CRASHED = 3;
private static final int SIGN_UP_SUCCESSFULL = 4;
protected static final int USERNAME_AND_PASSWORD_LENGTH_SHORT = 5;
//private static final String SERVER_RES_SIGN_UP_FAILED = "0";
private static final String SERVER_RES_RES_SIGN_UP_SUCCESFULL = "1";
private static final String SERVER_RES_SIGN_UP_USERNAME_CRASHED = "2";
private EditText usernameText;
private EditText passwordText;
private EditText eMailText;
private EditText passwordAgainText;
private Manager imService;
private Handler handler = new Handler();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
imService = ((MessagingService.IMBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
imService = null;
Toast.makeText(SigningUp.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signingup);
setTitle("Sign up");
Button signUpButton = (Button) findViewById(R.id.signUp);
Button cancelButton = (Button) findViewById(R.id.cancel_signUp);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
passwordAgainText = (EditText) findViewById(R.id.passwordAgain);
eMailText = (EditText) findViewById(R.id.email);
signUpButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
if (usernameText.length() > 0 &&
passwordText.length() > 0 &&
passwordAgainText.length() > 0 &&
eMailText.length() > 0
)
{
//TODO check email address is valid
if (passwordText.getText().toString().equals(passwordAgainText.getText().toString())){
if (usernameText.length() >= 5 && passwordText.length() >= 5) {
Thread thread = new Thread(){
String result = new String();
#Override
public void run() {
result = imService.signUpUser(usernameText.getText().toString(),
passwordText.getText().toString(),
eMailText.getText().toString());
handler.post(new Runnable(){
public void run() {
if (result.equals(SERVER_RES_RES_SIGN_UP_SUCCESFULL)) {
Toast.makeText(getApplicationContext(),R.string.signup_successfull, Toast.LENGTH_LONG).show();
//showDialog(SIGN_UP_SUCCESSFULL);
}
else if (result.equals(SERVER_RES_SIGN_UP_USERNAME_CRASHED)){
Toast.makeText(getApplicationContext(),R.string.signup_username_crashed, Toast.LENGTH_LONG).show();
//showDialog(SIGN_UP_USERNAME_CRASHED);
}
else //if (result.equals(SERVER_RES_SIGN_UP_FAILED))
{
Toast.makeText(getApplicationContext(),R.string.signup_failed, Toast.LENGTH_LONG).show();
//showDialog(SIGN_UP_FAILED);
}
}
});
}
};
thread.start();
}
else{
Toast.makeText(getApplicationContext(),R.string.username_and_password_length_short, Toast.LENGTH_LONG).show();
//showDialog(USERNAME_AND_PASSWORD_LENGTH_SHORT);
}
}
else {
Toast.makeText(getApplicationContext(),R.string.signup_type_same_password_in_password_fields, Toast.LENGTH_LONG).show();
//showDialog(TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS);
}
}
else {
Toast.makeText(getApplicationContext(),R.string.signup_fill_all_fields, Toast.LENGTH_LONG).show();
//showDialog(FILL_ALL_FIELDS);
}
}
});
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
finish();
}
});
}
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case TYPE_SAME_PASSWORD_IN_PASSWORD_FIELDS:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_type_same_password_in_password_fields)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case FILL_ALL_FIELDS:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_fill_all_fields)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case SIGN_UP_FAILED:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_failed)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case SIGN_UP_USERNAME_CRASHED:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_username_crashed)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
case SIGN_UP_SUCCESSFULL:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.signup_successfull)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
})
.create();
case USERNAME_AND_PASSWORD_LENGTH_SHORT:
return new AlertDialog.Builder(SigningUp.this)
.setMessage(R.string.username_and_password_length_short)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
}
})
.create();
default:
return null;
}
}
#Override
protected void onResume() {
bindService(new Intent(SigningUp.this, MessagingService.class), mConnection , Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
protected void onPause()
{
unbindService(mConnection);
super.onPause();
}
}

hey your problem is because of ImService object. its declaration in onResume method just move it to your onCreate because oncreate call before onresume method and your imService object use in oncreate.
bindService(new Intent(SigningUp.this, MessagingService.class), mConnection , Context.BIND_AUTO_CREATE);
put this line before buttononclicklistner.

Related

Service not stopping

I am creating an application which run a service where a function is called repeatedly in 5 seconds. I am able to start the service by clicking a button but cant stop when another button is clicked!
My code is:
public class LocationService extends Service implements LocationListener {
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String TAG = "MyServiceTag";
Timer t;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.scheduleAtFixedRate(
new TimerTask()
{
public void run()
{
startJob();
}
},
0, // run first occurrence immediatetly
5000); // run every 60 seconds
return START_STICKY;
}
#Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
t.cancel();
t.cancel();
return super.stopService(name);
}
Starting and stopping is done in another activity.
public void popupstart() {
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(this);
alertDialog.setTitle("Enable Location Sharing");
alertDialog.setMessage("Enable location sharing will broadcast your location to clients applications. This is a battery draining process and kindly turn off " +
"location sharing after use");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("shareLocation", "yes");
editor.commit();
liveStatus = "1";
mFab = (FloatingActionButton)findViewById(R.id.fab);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mFab.setImageDrawable(ContextCompat.getDrawable(gnavigationActivity.this, R.drawable.locationon));
}
else{
mFab.setImageDrawable(getResources().getDrawable(R.drawable.locationon));
}
if(!isMyServiceRunning(LocationService.class)) {
Toast.makeText(gnavigationActivity.this, "Location Sharing started", Toast.LENGTH_LONG).show();
processStartService(LocationService.TAG);
}
else{
Toast.makeText(gnavigationActivity.this, "Location Sharing already started", Toast.LENGTH_LONG).show();
}
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void popupstop() {
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(this);
alertDialog.setTitle("Stop Location Sharing");
alertDialog.setMessage("You are about to stop location sharing which now will not broadcast location to client users. Are you sure?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
processStopService(LocationService.TAG);
Toast.makeText(gnavigationActivity.this, "Location Sharing Stoped", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("shareLocation", "no");
editor.commit();
liveStatus = "0";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mFab.setImageDrawable(ContextCompat.getDrawable(gnavigationActivity.this, R.drawable.locationoff));
}
else{
mFab.setImageDrawable(getResources().getDrawable(R.drawable.locationoff));
}
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private void processStartService(final String tag) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.addCategory(tag);
startService(intent);
}
private void processStopService(final String tag) {
Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.addCategory(tag);
stopService(intent);
}
on calling stopService(intent);
the override method onDestroy will start
try to do this
#Override
public void onDestroy(){
super.onDestroy();
t.cancel();
t.cancel();
}

How to tell if button was not clicked in android?

I have a count down timer and if the user does not click this button on an even number I need to perform a certain method which will end my game. So basically if the user stops tapping I need the gameOver() method called.
import android.app.Activity;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class GameScreen extends Activity {
private TextView time;
private Button start;
private Button cancel;
private Button gameButton;
private CountDownTimer countDownTimer;
public static int count = 0;
int foo = Integer.parseInt(time.getText().toString());
private View.OnClickListener btnClickListener = new View.OnClickListener(){
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.start_ID :
start();
break;
case R.id.cancel :
cancel();
break;
case R.id.gameButton_ID :
gameButton();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
start = (Button) findViewById(R.id.start_ID);
start.setOnClickListener(btnClickListener);
cancel = (Button) findViewById(R.id.cancel);
cancel.setOnClickListener(btnClickListener);
time = (TextView) findViewById(R.id.time);
gameButton = (Button) findViewById(R.id.gameButton_ID);
gameButton.setOnClickListener(btnClickListener);
}
public void start(){
time.setText("15");
countDownTimer = new CountDownTimer(15 * 1000, 1000) {
#Override
public void onTick(long millsUntilFinished){
time.setText("" + millsUntilFinished / 1000);
//this doesnt work and makes app crash when you hit start button
if((gameButton.isPressed() != true) && foo % 2 == 0){
gameOver();
}
}
public void onFinish(){
time.setText("Done !");
}
};
countDownTimer.start();
}
private void cancel(){
if(countDownTimer != null){
countDownTimer.cancel();
countDownTimer = null;
}
}
private void gameOver(){
Toast.makeText(getApplicationContext(), "You scored " + count, Toast.LENGTH_SHORT).show();
count = 0;
cancel();
}
private void gameButton(){
if(foo % 2 == 0 ) {
Toast.makeText(getApplicationContext(), "PASS", Toast.LENGTH_SHORT).show();
++count;
}
else{
gameOver();
}
}
}
What you can do is take one boolean called isClickedOnEvenNumber. Now when you press the button when even-number set isClickedOnEvenNumber as
isClickedOnEvenNumber = true;
Now check on every tick check that
if(isClickedOnEvenNumber)
//continue game
else
//end game
EDIT :
You can use a TimerTask that periodically verifies wether or not the Button was clicked. You do not need the counterBTnnotclicked variable any more.
So you can do something like this : (Am trying to write this quickly, so be aware of that)
class BtnClickIntegerHolder{
public int counterBtnClicked = 0;
}
class BtnClicksCheckerIntegerHolder{
public int btnClicks = 0;
}
final BtnClickIntegerHolder btnClickCounter = new BtnClickIntegerHolder();
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnClickCounter.counterBtnClicked = btnClickCounter.counterBtnClicked + 1;
}
});
int period = 10000; // repeat every 10 secs.
final BtnClicksCheckerIntegerHolder btnClicksHolder = new BtnClicksCheckerIntegerHolder();
btnClicksHolder.btnClicks = btnClickCounter.counterBtnClicked;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if(btnClickCounter.counterBtnClicked == btnClicksHolder.btnClicks ){
//Button was not clicked
}
else{
//Button was clicked
}
btnClicksHolder.btnClicks = btnClickCounter.counterBtnClicked;
}
}, period, period);

Update Android Service TextView from Activity/ Static Method

Background:
I've created a custom service as:
public class FloatingViewService extends Service {
public static FloatingViewService self;
onCreate() {
self = this;
addView(....)
}
...
...
public void updateText ( String newText) { this.textView.setText(newText) };
}
OnCreate event of this service, it sets a view using WindowManager.addView(...) and also set an instance pointer in self variable for future use.
Now this view is just a textview, that stays on the top of activities, regardless.
What I want to achieve:
I want to send some data from a static method that runs using ExecutorService instance, which should update textview text.
How I use this service:
Inside of an activity, I make a call to a static method that logs some values:
public class MyActivity: Activity
{
public void log() {
LogUtil.log(new Runnable() {
#Override
public void run() {
//log api call
FloatingViewService.self.updateText("New Text");
}
}) ;
}
}
Now you can see that I am making a call to an updateText method present in service, from different thread.
Here is how the LogUtil is:
public class LogUtil {
private static ExecutorService taskExecutorService = ThreadUtils.createTimedExecutorService(TASK_POOL_SIZE, TASK_POOL_IDLE_ALIVE_SECONDS,
TimeUnit.SECONDS, new LowPriorityThreadFactory());
public static log(Runnable runnable) {
taskExecutorService.submit(new Runnable() {
#Override
public void run() {
try {
runnable.run();
} catch (Exception ex) {
../
}
}
});
Now the problem is, it cannot update textview text. I can understand it is due to thread. But I have no clue on how to achieve it - is there any UIthread for service ?
Here is my code for example .. you shuold be able to pick the necesary parts from it. as Selvin said you have to create an Incoming handler on both sides to send information from one thread to the other...
Here is my service code
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.pekam.myandroidtheme.*;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
public class MyService extends Service {
private NotificationManager nm;
private Timer timer = new Timer();
private int counter = 0, incrementby = 1;
private static boolean isRunning = false;
ArrayList<Messenger> mClients = new ArrayList<Messenger>(); // Keeps track of all current registered clients.
int mValue = 0; // Holds last value set by a client.
static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_INT_VALUE = 3;
static final int MSG_SET_STRING_VALUE = 4;
final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler { // Handler of incoming messages from clients.
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REGISTER_CLIENT:
mClients.add(msg.replyTo);
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_INT_VALUE:
incrementby = msg.arg1;
break;
default:
super.handleMessage(msg);
}
}
}
private void sendMessageToUI(int intvaluetosend) {
for (int i=mClients.size()-1; i>=0; i--) {
try {
// Send data as an Integer
mClients.get(i).send(Message.obtain(null, MSG_SET_INT_VALUE, intvaluetosend, 0));
//Send data as a String
Bundle b = new Bundle();
b.putString("str1", "ab" + intvaluetosend + "cd");
Message msg = Message.obtain(null, MSG_SET_STRING_VALUE);
msg.setData(b);
mClients.get(i).send(msg);
} catch (RemoteException e) {
// The client is dead. Remove it from the list; we are going through the list from back to front so this is safe to do inside the loop.
mClients.remove(i);
}
}
}
#Override
public void onCreate() {
super.onCreate();
Log.i("MyService", "Service Started.");
showNotification();
timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);
isRunning = true;
}
private void showNotification() {
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TabBarActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
nm.notify(R.string.service_started, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("MyService", "Received start id " + startId + ": " + intent);
return START_STICKY; // run until explicitly stopped.
}
public static boolean isRunning()
{
return isRunning;
}
private void onTimerTick() {
Log.i("TimerTick", "Timer doing work." + counter);
try {
counter += incrementby;
sendMessageToUI(counter);
} catch (Throwable t) { //you should always ultimately catch all exceptions in timer tasks.
Log.e("TimerTick", "Timer Tick Failed.", t);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (timer != null) {timer.cancel();}
counter=0;
nm.cancel(R.string.service_started); // Cancel the persistent notification.
Log.i("MyService", "Service Stopped.");
isRunning = false;
}
}
here is my android form app code
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.pekam.myandroidtheme.*;
public class MyServiceControllerActivity extends Activity {
Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
TextView textStatus, textIntValue, textStrValue;
Messenger mService = null;
boolean mIsBound;
final Messenger mMessenger = new Messenger(new IncomingHandler());
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyService.MSG_SET_INT_VALUE:
textIntValue.setText("Int Message: " + msg.arg1);
break;
case MyService.MSG_SET_STRING_VALUE:
String str1 = msg.getData().getString("str1");
textStrValue.setText("Str Message: " + str1);
break;
default:
super.handleMessage(msg);
}
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
textStatus.setText("Attached.");
try {
Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even do anything with it
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been unexpectedly disconnected - process crashed.
mService = null;
textStatus.setText("Disconnected.");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exampleservice);
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
btnBind = (Button)findViewById(R.id.btnBind);
btnUnbind = (Button)findViewById(R.id.btnUnbind);
textStatus = (TextView)findViewById(R.id.textStatus);
textIntValue = (TextView)findViewById(R.id.textIntValue);
textStrValue = (TextView)findViewById(R.id.textStrValue);
btnUpby1 = (Button)findViewById(R.id.btnUpby1);
btnUpby10 = (Button)findViewById(R.id.btnUpby10);
btnStart.setOnClickListener(btnStartListener);
btnStop.setOnClickListener(btnStopListener);
btnBind.setOnClickListener(btnBindListener);
btnUnbind.setOnClickListener(btnUnbindListener);
btnUpby1.setOnClickListener(btnUpby1Listener);
btnUpby10.setOnClickListener(btnUpby10Listener);
restoreMe(savedInstanceState);
CheckIfServiceIsRunning();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("textStatus", textStatus.getText().toString());
outState.putString("textIntValue", textIntValue.getText().toString());
outState.putString("textStrValue", textStrValue.getText().toString());
}
private void restoreMe(Bundle state) {
if (state!=null) {
textStatus.setText(state.getString("textStatus"));
textIntValue.setText(state.getString("textIntValue"));
textStrValue.setText(state.getString("textStrValue"));
}
}
private void CheckIfServiceIsRunning() {
//If the service is running when the activity starts, we want to automatically bind to it.
if (MyService.isRunning()) {
doBindService();
}
}
private OnClickListener btnStartListener = new OnClickListener() {
public void onClick(View v){
startService(new Intent(MyServiceControllerActivity.this, MyService.class));
}
};
private OnClickListener btnStopListener = new OnClickListener() {
public void onClick(View v){
doUnbindService();
stopService(new Intent(MyServiceControllerActivity.this, MyService.class));
}
};
private OnClickListener btnBindListener = new OnClickListener() {
public void onClick(View v){
doBindService();
}
};
private OnClickListener btnUnbindListener = new OnClickListener() {
public void onClick(View v){
doUnbindService();
}
};
private OnClickListener btnUpby1Listener = new OnClickListener() {
public void onClick(View v){
sendMessageToService(1);
}
};
private OnClickListener btnUpby10Listener = new OnClickListener() {
public void onClick(View v){
sendMessageToService(10);
}
};
private void sendMessageToService(int intvaluetosend) {
if (mIsBound) {
if (mService != null) {
try {
Message msg = Message.obtain(null, MyService.MSG_SET_INT_VALUE, intvaluetosend, 0);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
}
}
}
}
void doBindService() {
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
textStatus.setText("Binding.");
}
void doUnbindService() {
if (mIsBound) {
// If we have received the service, and hence registered with it, then now is the time to unregister.
if (mService != null) {
try {
Message msg = Message.obtain(null, MyService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// There is nothing special we need to do if the service has crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
textStatus.setText("Unbinding.");
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
doUnbindService();
} catch (Throwable t) {
Log.e("TabBarActivity", "Failed to unbind from the service", t);
}
}
}
You need to stay on UIThread to update UI. A solution may be:
Create a static reference of activity. Remember to set it on resume method of activity and to unset it on pause method.
On the service side you can invoke a method of activiy to update UI.
Translating those operations in pseudocode. The activity will become :
public class MainActivity extends Activity {
public static MainActivity reference;
...
public onResume() {
reference=this;
}
public onPause() {
reference=null;
}
public void needToUpdateText(final String text)
{
runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread with text "+text);
});
}
}
}
And the service class:
public class FloatingViewService extends Service {
...
public void updateText ( String newText)
{
if (MainActivity.reference!=null)
{
MainActivity.reference.needUpdateText(newText);
}
};
}

Not Showing dialoag when there is no internet

Hi in the below code After clicking login button with internet working fine.suppose there is no internet connection it's not working I want to show diaglog there is no internet connection.
Can any one help me from this issue.
Login1.java
public class Login1 extends Activity {
protected static final int NOT_CONNECTED_TO_SERVICE = 0;
protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
public static final String AUTHENTICATION_FAILED = "0";
public static final String FRIEND_LIST = "FRIEND_LIST";
protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2 ;
protected static final int NOT_CONNECTED_TO_NETWORK = 3;
private EditText usernameText;
private EditText passwordText;
private Button cancelButton;
private IAppManager imService;
public static final int SIGN_UP_ID = Menu.FIRST;
public static final int EXIT_APP_ID = Menu.FIRST + 1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
if (imService.isUserAuthenticated() == true)
{
Intent i = new Intent(Login1.this, FriendList.class);
startActivity(i);
Login1.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(Login1.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
Boolean isInternetPresent = false;
ConnectionDetector cd;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(Login1.this, IMService.class));
setContentView(R.layout.login_screen);
setTitle("Login");
Button loginButton = (Button) findViewById(R.id.login);
cancelButton = (Button) findViewById(R.id.cancel_login);
usernameText = (EditText) findViewById(R.id.userName);
passwordText = (EditText) findViewById(R.id.password);
loginButton.setOnClickListener(new OnClickListener(){
#SuppressWarnings("deprecation")
public void onClick(View arg0)
{
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login1.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
if (imService == null) {
Toast.makeText(getApplicationContext(),R.string.not_connected_to_service, Toast.LENGTH_LONG).show();
return;
}
else if (imService.isNetworkConnected() == false)
{
Toast.makeText(getApplicationContext(),R.string.not_connected_to_network, Toast.LENGTH_LONG).show();
showDialog(NOT_CONNECTED_TO_NETWORK);
}
else if (usernameText.length() > 0 &&
passwordText.length() > 0)
{
Thread loginThread = new Thread(){
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(usernameText.getText().toString(), passwordText.getText().toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null || result.equals(AUTHENTICATION_FAILED))
{
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),R.string.make_sure_username_and_password_correct, Toast.LENGTH_LONG).show();
}
});
}
else {
handler.post(new Runnable(){
public void run() {
Intent i = new Intent(Login1.this, FriendList.class);
startActivity(i);
Login1.this.finish();
}
});
}
}
};
loginThread.start();
}
else {
Toast.makeText(getApplicationContext(),R.string.fill_both_username_and_password, Toast.LENGTH_LONG).show();
}
}
});
cancelButton.setOnClickListener(new OnClickListener(){
public void onClick(View arg0)
{
imService.exit();
finish();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
int message = -1;
switch (id)
{
case NOT_CONNECTED_TO_SERVICE:
message = R.string.not_connected_to_service;
break;
case FILL_BOTH_USERNAME_AND_PASSWORD:
message = R.string.fill_both_username_and_password;
break;
case MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT:
message = R.string.make_sure_username_and_password_correct;
break;
case NOT_CONNECTED_TO_NETWORK:
message = R.string.not_connected_to_network;
break;
default:
break;
}
if (message == -1)
{
return null;
}
else
{
return new AlertDialog.Builder(Login1.this)
.setMessage(message)
.setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.create();
}
}
#Override
protected void onPause()
{
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
bindService(new Intent(Login1.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, SIGN_UP_ID, 0, R.string.sign_up);
menu.add(0, EXIT_APP_ID, 0, R.string.exit_application);
return result;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId())
{
case SIGN_UP_ID:
Intent i = new Intent(Login1.this, SignUp.class);
startActivity(i);
return true;
case EXIT_APP_ID:
cancelButton.performClick();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login1.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Add this function
public static boolean CheckInternet(Context context) {
ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return wifi.isConnected() || mobile.isConnected();
}
This function check the wifi or the mobile network if available and return true if yes false if no
and replace this:
if (!isInternetPresent) {
showAlertDialog(Login1.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
By this code:
if (!CheckInternet(this)) {
new AlertDialog.Builder(this)
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
return;
}
as you said :
I want to show diaglog there is no internet connection.
Use this function :
public static boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
and in your code check internet connection :
if (!isNetworkAvailable()) {
// show your dialog here
}

Android catch unhandled exception and show the dialog

I want to handle unhandled exception in my app without any third-party libraries.
So i write a code.
Activity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(new ReportHelper(this));
throw new NullPointerException();
}
My crash handler :
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.widget.Toast;
/**
* Created by S-Shustikov on 08.06.14.
*/
public class ReportHelper implements Thread.UncaughtExceptionHandler {
private final AlertDialog dialog;
private Context context;
public ReportHelper(Context context) {
this.context = context;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Application was stopped...")
.setPositiveButton("Report to developer about this problem.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Not worked!
dialog.dismiss();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
dialog = builder.create();
}
#Override
public void uncaughtException(Thread thread, Throwable ex) {
showToastInThread("OOPS!");
}
public void showToastInThread(final String str){
new Thread() {
#Override
public void run() {
Looper.prepare();
Toast.makeText(context, "OOPS! Application crashed", Toast.LENGTH_SHORT).show();
if(!dialog.isShowing())
dialog.show();
Looper.loop();
}
}.start();
}
}
When i start app as you see i throwed NullPointerException. Toast in my handling logic was showed, and dialog was showed too. BUT! Dialog clicks was not handling correct. I mean logic in onClick method was not worked. What the problem and how i can fix that?
In my case, I moved AlertDialog.Builder in thread run function like this:
public void showToastInThread(final String str){
new Thread() {
#Override
public void run() {
Looper.prepare();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Application was stopped...")
.setPositiveButton("Report to developer about this problem.", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Not worked!
dialog.dismiss();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
dialog = builder.create();
Toast.makeText(context, "OOPS! Application crashed", Toast.LENGTH_SHORT).show();
if(!dialog.isShowing())
dialog.show();
Looper.loop();
}
}.start();
}
and all thing work perfectly.
Hope this help you.
According this post, the state of the application is unknown, when setDefaultUncaughtExceptionHandler is called. This means that your onClick listeners may not be active anymore.
Why not use this method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(new ReportHelper(this));
throw new NullPointerException();
} catch (NullPointerException e) {
new ReportHelper(this);
}
}
and remove ReportHelper implementing the Thread.UncaughtExceptionHandler interface.
Your method of not explicitly catching exceptions can be seen as an anti-pattern.
Since an exception occurs on the UI-Thread: the state of this thread is probably unexpected
So try simply this in your click handler :
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
android.os.Process.killProcess(android.os.Process.myPid());
}
});

Categories

Resources