Android updating ui in thread getting null pointer exception - android

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();
}

Related

use and show progress dialog while send data

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();
}
}
});

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 print "connection timeout" when timeout in loopj

android I finding more but none of get solution..
when occur time out in loopj , I want print Time-out message..
Follow code for time-out which I used.
private static final int DEFAULT_TIMEOUT = 15 * 1000;
private static AsyncHttpClient client = new AsyncHttpClient();
public static void setTimeOutTime() {
client.setTimeout(DEFAULT_TIMEOUT);
System.out.println("timeout");
}
try {
response = client.newCall(request).execute();
jsonObj = new JSONObject(response.body().string());
} catch (IOException e) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (getStatus() == Status.RUNNING) {
cancel(true);
if(!hiddenDialog) {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle("Timeout error")
.setMessage("Sorry server doesn't response!\nCheck your internet connection and try again.")
.setCancelable(true)
.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Log.d(TAG, "load again");
}
}).setIcon(R.drawable.ic_dialog_alert_dark);
AlertDialog alert = builder.create();
alert.show();
}
});
} catch (JSONException e) {}
EDIT
for your case it should be the same way
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// make toast
}
});

How to get the endpoint ARN after the user re-install the android app for Amazon SNS?

Currently I am using Amazon SNS for managing the google GCM , which is to push the notification.
The problem is , I can only get the endpoint ARN after create the end point like this,
but how can I check whether the user has register before? So I do not need to create one more record
and just use that old record. Thanks
The code below is a button for the user to turn on (register) / off (delete) the SNS in amazon
notify.setOnClickListener(new OnClickListener() {
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void onClick(View v) {
if (prefs.getString("endpoint_arn", "").equals("")) {
new AsyncTask() {
#Override
protected Object doInBackground(final Object... params) {
try {
((Activity) ctx).runOnUiThread(new Runnable() {
public void run() {
if (!pDialog.isShowing())
pDialog.show();
}
});
String token = gcm.register(Constant.projectID);
CreatePlatformEndpointRequest per = new CreatePlatformEndpointRequest();
per.setToken(token);
per.setPlatformApplicationArn(Constant.platformARN);
CreatePlatformEndpointResult result = asnsc.createPlatformEndpoint(per);
editor.putString("endpoint_arn", result.getEndpointArn());
editor.commit();
((Activity) ctx).runOnUiThread(new Runnable() {
public void run() {
notify_txt.setText(ctx.getResources().getString(R.string.on));
if (pDialog.isShowing())
pDialog.dismiss();
}
});
} catch (final Exception e) {
((Activity) ctx).runOnUiThread(new Runnable() {
public void run() {
Log.d("test1","Registration Error:" + e.getMessage());
Toast.makeText(ctx, getResources().getString(R.string.error), Toast.LENGTH_LONG).show();
if (pDialog.isShowing())
pDialog.dismiss();
}
});
}
return true;
}
}.execute(null, null, null);
} else {
new AsyncTask() {
#Override
protected Object doInBackground(final Object... params) {
try {
((Activity) ctx).runOnUiThread(new Runnable() {
public void run() {
if (!pDialog.isShowing())
pDialog.show();
}
});
DeleteEndpointRequest dPer = new DeleteEndpointRequest();
dPer.setEndpointArn(prefs.getString("endpoint_arn", ""));
asnsc.deleteEndpoint(dPer);
gcm.unregister();
editor.remove("endpoint_arn").commit();
((Activity) ctx).runOnUiThread(new Runnable() {
public void run() {
notify_txt.setText(ctx.getResources().getString(R.string.off));
if (pDialog.isShowing())
pDialog.dismiss();
}
});
} catch (final Exception e) {
((Activity) ctx).runOnUiThread(new Runnable() {
public void run() {
Log.d("test1","Delete Error:" + e.getMessage());
Toast.makeText(ctx, getResources().getString(R.string.error), Toast.LENGTH_LONG).show();
if (pDialog.isShowing())
pDialog.dismiss();
}
});
}
return true;
}
}.execute(null, null, null);
}
}
});
To my knowledge, even when user re-installs the app on the same device, device token generated by GCM will be same. If you've already registered the device with the token then SNS wont insert another record , instead it refers to the same. So no need to worry about registering user again to SNS with the device token.

How can I post on a friend's Facebook wall with Android

I make an application in which I make an EditText and a button. I want to be post that message which is written on EditText on the Facebook friends wall after clicked on the button. Please give me some idea how we can perform this task using Facebook sdk.
The code is below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.post_wall);
share = (Button) findViewById(R.id.share);
friend_name = (TextView) findViewById(R.id.wall_to);
wall = (EditText) findViewById(R.id.wall);
savedInstanceState = new Bundle();
savedInstanceState.getString("to");
onComplete(savedInstanceState);
}
#Override public void onComplete(Bundle values)
{
Utility.currentPermissions.clear();
if (values.isEmpty())
{
//"skip" clicked ?
return;
}
// if facebookClient.authorize(...) was successful, this runs
// this also runs after successful post
// after posting, "to"(which is the id of friend) is added to the values bundle
// I use that to differentiate between a call from
// faceBook.authorize(...) and a call from a successful post
// is there a better way of doing this?
if (!values.containsKey("to"))
{
try
{
Log.d("Wall try", "Click successfully");
for (String key : parameters.keySet()) {
if (parameters.getByteArray(key) != null) {
parameters.putByteArray(key, parameters.getByteArray(key));
Log.d("key", parameters.getByteArray(key).toString());
}
}
mHandler.post(new Runnable() {
#Override
public void run() {
performActivityInfo();
}
});
}
catch (Exception e)
{
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
protected void performActivityInfo() {
Log.d("perform wall", "Perform Activity");
mHandler.sendEmptyMessage(FRIEND_WALL);
parameters.putString("message", wall.getText().toString());
facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
Log.d("Wall post", "Click successfully");
}
public Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FRIEND_WALL:
Log.d("Handler WALL", "Handler");
postOnWall(wall.getText().toString());
break;
}
super.handleMessage(msg);
}
};
#Override
public void onError(DialogError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onCancel()
{
}
#Override
public void onClick(View v)
{
facebookClient = new Facebook(APP_ID);
// replace APP_API_ID with your own
Log.d("Wall click", "Click successfully");
facebookClient.authorize(this,
new String[] {"publish_stream", "read_stream", "offline_access"}, this);
}
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebookClient.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = facebookClient.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}
Thanks in Advance.
For getting the value from Edit Text just use :
EditText edittext;
edittext.getEditableText().toString();
Inside Button click Listener use this code then
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
String entered_value=edittext.getEditableText().toString();
try{
parameters.putString("message", entered_value);
parameters.putString("target_id", "XXXXX"); // target Id in which you need to Post
parameters.putString("method", "stream.publish");
String response = authenticatedFacebook.request(parameters);
Log.v("response", response);
}
catch(Exception e){}
}
});
where button is your button Object.

Categories

Resources