use and show progress dialog while send data - android

I'm new on android and I want to show a progress bar whenever user do tap on sndbtn and while sending data to my API and when the app finish to sending the data the progress bar have to dismiss.
I'm not sure how to implement the progress with the code that I have. Please some help?
sndbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (networkInfo != null && networkInfo.isConnected()) {
Request data = helper.sndData(Integer.parseInt(id));
request = new Request(Activity.this, API.POST, data);
try {
String response = request.execute("url").get();
Response response = new Response(response);
if (responseListModel.isSuccess()) {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Activity.this, NewActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplication(), "Internet Error.", Toast.LENGTH_SHORT).show();
}
}
});

I would suggest using AsyncTask and show dialog in onPreExecute and close dialog in onPostExecute.
/**
* Check holiday schedule
*/
class CheckHolidayNoteAsync(context: Activity) : AsyncTask<Void, Void, HolidayScheduleInfo>() {
override fun doInBackground(vararg params: Void?): HolidayScheduleInfo {
//do network stuff here
return HolidayScheduleInfo(result)
}
override fun onPostExecute(result: HolidayScheduleInfo) {
//close dialog
}
/**
* Runs on the UI thread before [.doInBackground].
*
* #see .onPostExecute
*
* #see .doInBackground
*/
override fun onPreExecute() {
//show progress dialog
}
}

Use this code :
public ProgressDialog dialog;
public void showDialog() {
if (dialog == null) {
dialog = new ProgressDialog(getContext());
}
dialog.setMessage("Searching");
dialog.show();
}
public void hideDialog(){
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
Use these methods in your code :
sndbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (networkInfo != null && networkInfo.isConnected()) {
showDialog();
Request data = helper.sndData(Integer.parseInt(id));
request = new Request(Activity.this, API.POST, data);
try {
new Thread(new Runnable() {
#Override
public void run() {
String response = request.execute("url").get();
Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
hideDialog();
Response response = new Response(response);
if (responseListModel.isSuccess()) {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Activity.this, NewActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplication(), responseListModel.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplication(), "Internet Error.", Toast.LENGTH_SHORT).show();
}
}
});

Related

Flashlight function crashes after returning from activity

I have this android app which connects to an mqtt broker and listens for instructions to play/pause a ringtone or open/close the flashlight.
It runs as supposed to until i change my settings and call the function flashOnOff after this. Then i get a null pointer exception but i can not understand why.
This is my code (i did not include my imports to save some space):
public class MainActivity extends AppCompatActivity {
// Layout related parameters
Toolbar myToolbar;
Spinner mySpinner;
ImageButton flashlightButton;
Button ringtone;
EditText message;
// Camera/flashlight related parameters
Camera camera;
Camera.Parameters parameters;
// MQTT related parameters
private String BrokerIp = "tcp://192.168.1.3:1883";
private int qos = 2;
static String Username = "user1";
static String Password = "user1";
String topicStr = "commands";
String clientId = "AndroidClient";
MqttConnectOptions options;
MqttAndroidClient client;
Vibrator vibrator;
// Ringtone related parameters
Ringtone myRingtone;
MediaPlayer ringtoneMP ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
myRingtone = RingtoneManager.getRingtone(getApplicationContext(),uri);
myToolbar = (Toolbar) findViewById(R.id.toolbar);
mySpinner = (Spinner) findViewById(R.id.spinner);
flashlightButton = (ImageButton) findViewById(R.id.image);
myToolbar.setLogo(R.drawable.twoguyswatchmrrobot);
myToolbar.setTitle(getResources().getString(R.string.app_name));
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_itam,
getResources().getStringArray(R.array.Toolbar_dropdown_entries));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(myAdapter);
ringtoneMP = MediaPlayer.create(this,R.raw.games_of_thrones);
ringtone = (Button) this.findViewById(R.id.ringtone);
message = (EditText)findViewById(R.id.messagePublish);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,
mySpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT)
.show();
if (mySpinner.getSelectedItem().toString().equals("Exit App")){
exit();
}else if(mySpinner.getSelectedItem().toString().equals("Settings"))
{
Intent intent;
intent = new Intent(MainActivity.this, SettingsActivity.class);
intent.putExtra("CURRENT_IP",client.getServerURI());
intent.putExtra("CURRENT_QOS", Integer.toString(qos));
intent.putExtra("CURRENT_TOPIC",topicStr);
startActivityForResult(intent,1); // this is so we can take the results back to mainActivity later
}else{
System.out.println("ara3e, den exw diale3ei tipota");
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
//Flashlight on Create start
if(isFlashAvailable()) // check if flash is available on this device, if it is open camera (module) and make button clickable
{
camera = Camera.open();
parameters = camera.getParameters();
}else
{ // if flashlight is not supported dont let the user click the button
flashlightButton.setEnabled(false);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error.");
builder.setMessage("Flashlight not available on this device. \nExit?"); // inform the user and let him choose how to continue
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
exit();
}
});
builder.setNegativeButton("Stay without flashlight", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
flashlightButton.setOnClickListener(new View.OnClickListener() { // listen for flash button clicks
#Override
public void onClick(View view) {
flashOnOff();
}
});
ringtone.setOnClickListener(new View.OnClickListener() { // Ringtone listener
#Override
public void onClick(View view) {
ringtoneOnOff(ringtoneMP);
}
});
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
// client = pahoMqttClient.getMqttClient(MainActivity.this,BrokerIp,clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
Log.d("Connection:"," Lost");
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.d("Delivery"," completed with iMqttDeliveryToken: " + iMqttDeliveryToken);
}
});
}
//Flashlight start
#Override
protected void onStop() {
super.onStop();
if(camera!=null)
{
camera.release();
camera = null;
}
}
//Flashlight end
//Backkey exit confirmation
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit application?")
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
// when yes is clicked exit the application
public void onClick(DialogInterface arg0, int arg1) {
exit();
}
})
.setNegativeButton("No", new
DialogInterface.OnClickListener() {
// when no is clicked do nothing
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
//Backkey end
// PUBLISH MESSAGE
private void setSubscription(MqttAndroidClient client, String topic, int qos){
try{
client.subscribe(topic, qos);
}
catch (MqttException e){
e.printStackTrace();
}
}
private void unsetSubscription(MqttAndroidClient client,String topic){
try{
client.unsubscribe(topic);
}catch (MqttException e){
e.printStackTrace();
}
}
public void conn(View v){
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
setSubscription(client,topicStr,qos);
// pub();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "not connected", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
public void disconn(View v){
if (client.isConnected()) {
try {
IMqttToken token = client.disconnect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(MainActivity.this, "could not disconnect", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}else {
Toast.makeText(MainActivity.this, "Client is already disconnected", Toast.LENGTH_LONG).show();
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void pub(View v) {
String topic = topicStr;
try {
client.publish(topic, String.valueOf(message.getText()).getBytes(),qos,false);
} catch (MqttException e) {
e.printStackTrace();
}
}
private void ringtoneOnOff(MediaPlayer ringtoneMP){
if (ringtoneMP.isPlaying()){
ringtoneMP.pause();
}else{
ringtoneMP.start();
}
}
private void myMessageArrived(String s,MqttMessage mqttMessage){
if ((mqttMessage.toString()).equals("Flash on")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Flashlight already on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Turning flashlight on", Toast.LENGTH_SHORT).show();
flashOnOff();
}
} else if ((mqttMessage.toString()).equals("Flash off")) {
if (isFlashOn()) {
Toast.makeText(MainActivity.this, "Turning flashlight off", Toast.LENGTH_SHORT).show();
flashOnOff();
} else {
Toast.makeText(MainActivity.this, "Flashlight already off", Toast.LENGTH_SHORT).show();
}
} else if ((mqttMessage.toString()).equals("Ringtone on")) {
if (ringtoneMP.isPlaying()) {
Toast.makeText(MainActivity.this, "Ringtone already playing", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Playing ringtone", Toast.LENGTH_SHORT).show();
ringtoneMP.start();
}
} else if ((mqttMessage.toString()).equals("Ringtone off")) {
if (ringtoneMP.isPlaying()) {
ringtoneMP.pause();
} else {
Toast.makeText(MainActivity.this, "Ringtone already not being played", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("INFO:", "This Command does not exist");
}
vibrator.vibrate(500);
myRingtone.play();
}
public void exit(){
finish();
System.exit(0);
}
public boolean isFlashAvailable(){ // boolean function that returns true if flash is supported on this device
return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
public void flashOnOff(){ // self explanatory
if (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH)){ // if the flash is on torch mode
Log.d("BHKE","408");
this.flashlightButton.setImageResource(R.drawable.off);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); // turn it off
}else{
Log.d("BHKE","412");
this.flashlightButton.setImageResource(R.drawable.on);
this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); // else turn it on
}
this.camera.setParameters(this.parameters);
this.camera.startPreview();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
String tempBrokerIp;
String temptopic="";
Integer tempqos;
Boolean BrokerIpChanged = true;
Boolean qosChanged = true;
Boolean topicChanged = true;
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (1) : {
if (resultCode == Activity.RESULT_OK) {
tempBrokerIp = data.getStringExtra("CURRENT_IP");
tempqos = Integer.parseInt(data.getStringExtra("CURRENT_QOS"));
temptopic = data.getStringExtra("CURRENT_TOPIC");
Log.d("Info BROKER, TOPIC, QOS", ":"+ tempBrokerIp+ " " + temptopic+ " " + tempqos);
if (tempBrokerIp.equals(BrokerIp)) {
BrokerIpChanged=false;
Log.i("BrokerIpChanged =", BrokerIpChanged.toString());
}
if (tempqos.equals(qos)) {
qosChanged=false;
Log.i("qosChanged =", qosChanged.toString());
}else {
qos = tempqos;
}
if (temptopic.equals(topicStr)){
topicChanged=false;
Log.i("topicChanged =", topicChanged.toString());
}else{
topicStr = temptopic;
}
if (!BrokerIpChanged && !qosChanged && !topicChanged) return;
if (BrokerIpChanged){
try {
client.disconnect();
BrokerIp = tempBrokerIp;
topicStr = temptopic;
qos = tempqos;
// final String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
options = new MqttConnectOptions();
options.setUserName(Username);
options.setPassword(Password.toCharArray());
// options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1); // to user the latest mqtt version
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
Log.w("Mqtt","Connected to:"+ BrokerIp);
try{
Log.v("INFO 11111:", "about to subscribe with: "+ topicStr + qos);
client.subscribe(topicStr,qos);
}catch (MqttException e){
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
}
});
System.out.println(client.isConnected());
// if (client.isConnected()){
// Log.v("INFO 22222:", "about to subscribe with: "+ temptopic + tempqos);
// client.subscribe(temptopic,tempqos);
// }
} catch (MqttException e) {
e.printStackTrace();
}
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
myMessageArrived(s,mqttMessage);
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}catch (MqttException e){
e.printStackTrace();
}
}else
{
try {
client.unsubscribe(topicStr);
client.subscribe(temptopic,tempqos);
topicStr = temptopic;
qos = tempqos;
} catch (MqttException e) {
e.printStackTrace();
}
}
}
break;
}
}
}
public boolean isFlashOn(){
return (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH));
}
I can provide the settings activity code too is needed
It seems that the two variables needed for the flashOnOff where not initiallized after i returned from the settings activity.
Ι added :
if (isFlashAvailable()){
camera = Camera.open();
parameters = camera.getParameters();
}
at the onActivityResult start and it works like a charm.

Android AlertDialog freezes when saving data in database

In my App my I am using AlertDialog in Async. But it freezes at a point when data is saving in database. what can I do to keep it running? It runs perfectly for sometime but stops after certain time when database is accessed.
Here's my code:
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
return null;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
CheckInternetConnection internet = new CheckInternetConnection(
getApplicationContext());
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
return;
} else {
setUpdatedBarcodes();
}
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here after
data is saved in DB
}
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
DB operations should be done in the background thread. Put it in doInBackground() method too.
I modify your code. may it helps..
class BackGroundTasks extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
CheckInternetConnection internet = new CheckInternetConnection(
mActivity);
if (!internet.HaveNetworkConnection()) {
showToast("No Internet Connection.");
} else {
setUpdatedBarcodes();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss(); // cancelling Async dialog here
}
}
}
private boolean setUpdatedBarcodes(
ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
int i = 0;
BarcodeDatabase barcodeDatabase = new
BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
showToast("Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}
when saving data in database don't do it on main thread do it on background thread. try code
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your work
}
},0);
or
new Thread(new Runnable() {
public void run() {
// do your work here
}
}).start();

Android updating ui in thread getting null pointer exception

When user login i will get user id and i will get device id and i will check in database(server end) and if the response is SUCCESS the ui need to update. But i am getting null pointer exception. I am updating ui in thread. Whats is the issues in this.
public class MainActivity extends AppCompatActivity {
final String LOG_TAG="TESTOPENAPP";
OpenAppLock mSelectedLock;
String email,devid;
ArrayList<OpenAppLock> scanList;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
AlertDialogManager alert = new AlertDialogManager();
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
Button mScan,mConnect,mUnlock,mDisconnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = getIntent();
// Receiving the Data
// String name = i.getStringExtra("name");
email = i.getStringExtra("email");
System.out.println("user mail id" + email);
mScan=(Button)findViewById(R.id.scan);
mConnect=(Button)findViewById(R.id.connect);
mUnlock=(Button)findViewById(R.id.unlock);
mDisconnect=(Button)findViewById(R.id.disconnect);
OpenApp.initialize(this);
mScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mScan.setText("Scanning ...");
OpenApp.scanForLocks(new ScanFinishedCallback() {
#Override
public void onScanFinished(ArrayList<OpenAppLock> scanList) {
Log.d(LOG_TAG, "OnScanFinishedCallback");
for (int i = 0; i < scanList.size(); i++) {
Log.d(LOG_TAG, "Available Lock " + i + " - " + scanList.get(i).getLockName());
devid = scanList.get(i).getLockName();
}
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
});
mConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mConnect.setText("Connecting ...");
mSelectedLock.connect(new ConnectionCallback() {
#Override
public void onFinishedTrying(boolean success) {
if(success){
mConnect.setVisibility(View.GONE);
mUnlock.setVisibility(View.VISIBLE);
//mDisconnect.setVisibility(View.VISIBLE);
}else{
mConnect.setText("Connect");
Toast.makeText(MainActivity.this, "Unable to connect to lock.", Toast.LENGTH_LONG).show();
}
}
});
}
});
mUnlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//It should be already ensured that this mSelectedLock is something user is authorized to access
if(mSelectedLock.unlock("RANDOM")){
mUnlock.setVisibility(View.INVISIBLE);
mUnlock.postDelayed(new Runnable() {
public void run() {
mUnlock.setVisibility(View.VISIBLE);
mUnlock.performClick();
Toast.makeText(getApplicationContext(),"Button Clicked",Toast.LENGTH_SHORT).show();
}
}, 6000);
}else{
Toast.makeText(MainActivity.this, "Unable to unlock.", Toast.LENGTH_LONG).show();
}
}
});
}
void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.25.107:8080/ActCFWeb/login"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("email", email)); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("pass", devid));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
System.out.println("Response : " + response);
}
});
if (response.contains("success")) {
runOnUiThread(new Runnable() {
public void run() {
if (scanList.size() > 0) {
Toast.makeText(MainActivity.this, "Scanning finished. Lock Found.", Toast.LENGTH_LONG).show();
mScan.setVisibility(View.GONE);
mConnect.setVisibility(View.VISIBLE);
mSelectedLock = scanList.get(0);
dialog.dismiss();
} else {
mScan.setText("Scan");
Toast.makeText(MainActivity.this, "No Lock Found while scanning. Please scan again.", Toast.LENGTH_LONG).show();
}
}
});
}
else {
showAlert();
}
} catch (Exception e) {
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert() {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
protected void onStop() {
OpenApp.destroy();
if(mSelectedLock!=null)
mSelectedLock.destroy();
super.onStop();
}
Hey I found your solution.
I check your code and found that when your response is null and you check about response.contains("success"), you will get NullPointerException.
Just add one If condition more.
Check code below.
if(response != null){
if (response.contains("success")) {
runOnUiThread(new Runnable() {
public void run() {
if (scanList.size() > 0)
{
try
{
Toast.makeText(MainActivity.this, "Scanning finished. Lock Found.", Toast.LENGTH_LONG).show();
mScan.setVisibility(View.GONE);
mConnect.setVisibility(View.VISIBLE);
mSelectedLock = scanList.get(0);
}
catch (NullPointerException e) {
e.printStackTrace();
}
} else {
mScan.setText("Scan");
Toast.makeText(MainActivity.this, "No Lock Found while scanning. Please scan again.", Toast.LENGTH_LONG).show();
}
}
});
}
else {
showAlert();
}
}
I just add if(response != null) for check response is null or not.
if (response.contains("success")) {
runOnUiThread(new Runnable() {
public void run() {
if (scanList.size() > 0)
{
try
{
Toast.makeText(MainActivity.this, "Scanning finished. Lock Found.", Toast.LENGTH_LONG).show();
mScan.setVisibility(View.GONE);
mConnect.setVisibility(View.VISIBLE);
mSelectedLock = scanList.get(0);
}
catch (NullPointerException e) {
e.printStackTrace();
}
} else {
mScan.setText("Scan");
Toast.makeText(MainActivity.this, "No Lock Found while scanning. Please scan again.", Toast.LENGTH_LONG).show();
}
}
});
}
else {
showAlert();
}

Splash screen doesn't display logo : thread.execute.get()

My splash screen syncronize my app :
When I use :
sd.execute("init_sync", null).get();
My logo (defined in xml) disappear. If I quit .get(), it appears.
Here is my code :
public class SplashScreen extends Activity {
private Context ctx = null;
private Usuario mUser = null;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ctx = this;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
new Handler().post(new Runnable() {
#Override
public void run() {
// Check if user exists
Gson gson = new Gson();
String jsonUser = prefs.getString("usuario", "");
mUser = gson.fromJson(jsonUser, Usuario.class);
if (NetworkUtils.isOnline(ctx)) {
if (mUser != null) {
SyncData sd = new SyncData(ctx);
try {
sd.execute("init_sync", null).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Intent i = new Intent(SplashScreen.this, LoginActivity.class);
startActivity(i);
}
} else {
if (mUser != null) {
Intent i = new Intent(SplashScreen.this, DashBoard.class);
startActivity(i);
} else {
Toast.makeText(ctx, "Necesita Internet para loguearse", Toast.LENGTH_LONG).show();
finish();
}
}
}
});
}
}
I have several asyncTask that I use to upload pics, and sync MySQL database with my SQLite database. So, I need to wait till all the processes end to know if there is any error.
The thing is I put it in a thread, so that it would not affect UI. Where am I wrong?
When you use get() it causes the UI thread to wait. Don't use get(). You need to override the onPostExecute method in AsyncTask.
private Boolean task1Finished = false;
private Boolean task2Finished = false;
private Boolean task3Finished = false;
//...
SyncData sd1 = new SyncData(ctx) {
#Override
protected void onPostExecute(Object result) {
task1Finished = true;
goToNextActivity();
}
};
SyncData sd2 = new SyncData(ctx) {
#Override
protected void onPostExecute(Object result) {
task2Finished = true;
goToNextActivity();
}
};
SyncData sd3 = new SyncData(ctx) {
#Override
protected void onPostExecute(Object result) {
task3Finished = true;
goToNextActivity();
}
};
try {
sd1.execute();
sd2.execute();
sd3.execute();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
//...
private void goToNextActivity() {
if (task1Finished && task2Finished && task3Finished)
// all tasks complete
}
Like #ashishduh says, I was in UI Thread. So I changed:
new Handler().post(new Runnable() {
#Override
public void run() {
....
}
}
by
Runnable sync = new Runnable() {
#Override
public void run() {
....
}
};
Thread t = new Thread(sync);
t.start();
And it solved my problem!

Android: Async Task, how to handle efficiently?

I am using this Asnc class my application, but at times when i quit the application. It crashes. "window leaked error : at line progDialog.show();" - Guess the ProgressDialog is causing the issue as it is still referencing to the activity(context), but i cant use getApplicationContext(), if i use getApplicationContext(), then the ProgressDialog wont work. How can i fix this issue ?
protected void executeSLPWebserviceTask(double latitude, double longitude,
String progressStr) {
WebserviceTask task = new WebserviceTask(this, progressStr);
task.execute(latitude, longitude);
}
class WebserviceTask extends AsyncTask<Double, Void, Float> implements OnDismissListener{
Context context;
ProgressDialog progDialog;
String progressString;
public WebserviceTask(Context context, String progressStr) {
this.context = context;
this.progressString = progressStr;
initProgDialog();
}
void initProgDialog(){
if(!isCancelled()){
try {
progDialog = new ProgressDialog(context);
progDialog.setCanceledOnTouchOutside(false);
progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.btn_cancel),new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
progDialog.dismiss();
}
});
progDialog.setMessage(progressString);
progDialog.setOnDismissListener(this);
progDialog.show();
} catch (Exception e) {
Log.e("Web&RemoteServiceActivity", "Failed to add window for web service task");
}
}
}
#Override
protected void onPreExecute() {
addTask(this);
super.onPreExecute();
}
protected Float doInBackground(Double... latLong) {
Float slpFloat = 0f;
if(!isCancelled()){
if(internetServiceBound)
{
try {
slpFloat = internetSLPService.getSLPFromInternet(latLong[0].floatValue(),latLong[1].floatValue());
} catch (RemoteException e) {
Log.e("Webservice task", "Failed to get slp - Remote exception");
this.cancel(true);
}
catch (NullPointerException e) {
Log.e("Webservice task", "Failed to get slp - Null pointer exception");
this.cancel(true);
}
}
}
return slpFloat;
}
protected void onPostExecute(Float slpFloat) {
if (!isCancelled()) {
if(slpFloat >= 300 && slpFloat<=1100){
//seaLevelPressure = slpFloat;
setReferenceSeaLevelPressure(slpFloat);
updateSeaLevelPressureFromWeb(slpFloat);
Toast toast = Toast.makeText(getApplicationContext(), getString(R.string.msg_slp_updated_from_internet) + " : " + slpFloat, Toast.LENGTH_LONG);
toast.show();
addToastJob(toast);
progDialog.dismiss();
//lastCalibratedTime = System.currentTimeMillis();
}else if(slpFloat==0){
//If SLP value returned is 0, notify slp fetch fail and cancel progress dialog
Toast toast = Toast.makeText(getApplicationContext(),getString(R.string.msg_slp_fetch_fail), Toast.LENGTH_SHORT);
toast.show();
addToastJob(toast);
progDialog.dismiss();
}else{
//Notify invalid SLP and cancel progress dialog
Toast toast = Toast.makeText(getApplicationContext(),getString(R.string.msg_internet_slp_invalid), Toast.LENGTH_SHORT);
toast.show();
addToastJob(toast);
progDialog.dismiss();
}
}
this.cancel(true);
}
public void onDismiss(DialogInterface dialog) {
this.cancel(true);
}
#Override
protected void onCancelled() {
if(progDialog != null){
if(progDialog.isShowing())
progDialog.dismiss();
}
super.onCancelled();
}
}
Create progressDialog by overriding onCreateDialog(int id) in your activity. In your task in onPreExecute() method use showDialog(PROGRESS_DIALOG_ID); and in onPostExecute() method use dismissDialog(PROGRESS_DIALOG_ID);

Categories

Resources