btn.performClick() is not helping in triggerring button automatically - java

I want to trigger a button as soon as an OTP arrives and gets set in a edittext area field. OTP gets successfully set but submit button is not getting triggered itself. Where i am going wrong? Here is my code.
OTP.java
package com.nrb.app.nrb.otp;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.nrb.app.nrb.HomeScreen;
import com.nrb.app.nrb.QRresponse.MyDBHelper;
import com.nrb.app.nrb.QRresponse.ServiceCalls;
import com.nrb.app.nrb.QRscanapi.RM;
import com.nrb.app.nrb.R;
import com.nrb.app.nrb.intera.AsyncResponseActivity;
import com.nrb.app.nrb.intera.ConnectionDetectorActivity;
import com.nrb.app.nrb.login.RegisterValidation;
import com.nrb.app.nrb.login.SignInActivity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class OTP extends FragmentActivity implements View.OnClickListener {
private Hashtable<String, String> verifiedResponseKeyValue = new Hashtable<String, String>();
private Hashtable<String, String> verifiedNestedResponseKeyValue = new Hashtable<String, String>();
private String userMobValue;
private String otpVerUrl;
private String userNameValue;
private String userEmailValue;
private String userCountryValue;
private String userId;
private MyDBHelper myDBHelper;
private String userCountryCode;
private boolean timeOut;
static EditText OtpNumber;
private ConnectionDetectorActivity cd;
private String user_exist;
private Button OTP;
Context cntx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cntx=this;
OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
cd = new ConnectionDetectorActivity(OTP.this);
Bundle bundle = getIntent().getExtras();
userId=bundle.getString("id");
userEmailValue = bundle.getString("userEmailValue");
userMobValue = bundle.getString("userMobValue");
userNameValue = bundle.getString("userNameValue");
userCountryValue = bundle.getString("userCountryValue");
userCountryCode = bundle.getString("userCountryCode");
user_exist = bundle.getString("user_exist");
registerViews();
}
public void registerViews() {
OtpNumber = (EditText) findViewById(R.id.etOTPVerifaction);
// TextWatcher would let us check validation error on the fly
OtpNumber.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
RegisterValidation.isName(OtpNumber, false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
/* OtpNumber.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
OTP.performClick();
return true;
}
return false;
}
});*/
}
private boolean checkValidation() {
boolean ret = true;
if (!RegisterValidation.isName(OtpNumber, true))
ret = false;
return ret;
}
#SuppressLint("InflateParams")
private void popUpDialog(String result1, final boolean newuser) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.otp_verification_dialog, null);
TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
tv.setText(result1);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
if (newuser) {
Bundle bundle = new Bundle();
bundle.putString("defaultFrag", "newUserFrag");
Intent i = new Intent(OTP.this, HomeScreen.class);
i.putExtras(bundle);
startActivity(i);
setResult(10);
finish();
}
else{
Toast.makeText(cntx, "Please enter Valid OTP", Toast.LENGTH_LONG).show();
OtpNumber.setText("");
}
}
});
}
#SuppressLint("InflateParams")
private void popUpDialogSuccess(Spannable result1) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.otp_verification_dialog, null);
TextView tv = (TextView) content.findViewById(R.id.otpAlertMessage1);
tv.setText(result1);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
content.findViewById(R.id.btnOTPAlertOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
insertUserPfref();
}
});
}
public void verifyOTPKEY(View v) {
if (checkValidation()){
EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
RM.OTP_MOB_VALUE = userMobValue;
if (user_exist.compareTo("true") == 0)
RM.OTP_USER_EXIST_VALUE = "true";
else
RM.OTP_USER_EXIST_VALUE = "false";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
jsonObject.put(RM.USER_Id_KEY,userId);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("==", "========= FAIL TO CREATE JSON ==========");
}
ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {
#Override
public void myAsyncResponse(String result) {
// TODO Auto-generated method stub
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
Log.d("====>>>>", result);
parseOTPRsponseJason(result);
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
}
});
if (cd.isConnectingToInternet()) {
Login.execute(1);
} else {
showNetworFailDialog(RM.NO_INTERNET_MSG);
}
}
else{
Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
}
class MyOTPAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(OTP.this);
dialog.setMessage("Authenticating...");
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(otpVerUrl);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} catch (Exception e) {
timeOut = true;
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// popUpDialog(result);
if (!timeOut)
parseOTPRsponseJason(result);
else
showNetworFailDialog(RM.REQ_TIMEOUT_MSG);
Log.d("----->", " Response " + result);
}
}
private void parseOTPRsponseJason(String result) {
// TODO Auto-generated method stub
JSONObject json;
JSONObject nestedJson;
try {
json = new JSONObject(result);
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = json.get(key);
if (user_exist.compareTo("true") == 0) {
if (key.compareTo("responseHash") == 0) {
nestedJson = new JSONObject(json.get(key).toString());
Iterator<String> nestedIter = nestedJson.keys();
while (nestedIter.hasNext()) {
String nestedKey = nestedIter.next();
Object nestedValue = nestedJson.get(nestedKey);
verifiedNestedResponseKeyValue.put(nestedKey,
nestedValue.toString());
}
}
}
verifiedResponseKeyValue.put(key, value.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Set<String> hKeys2 = verifiedResponseKeyValue.keySet();
for (String string : hKeys2) {
Log.d("====>",
string + " ==>" + verifiedResponseKeyValue.get(string));
}
String x = verifiedResponseKeyValue.get("success");
if (x.compareTo("true") == 0) {
if (user_exist.compareTo("true") == 0) {
userNameValue = verifiedNestedResponseKeyValue.get("name");
Spannable wordtoSpan = new SpannableString("HI "
+ userNameValue + " , Welcome back to Onspot");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 3,
3 + userNameValue.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
popUpDialogSuccess(wordtoSpan);
} else {
Spannable wordtoSpan = new SpannableString(
"Congratulations! " + userNameValue
+ " , you are successfully registered.");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.RED), 17,
17 + userNameValue.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
popUpDialogSuccess(wordtoSpan);
}
} else
popUpDialog(
verifiedResponseKeyValue.get("responseMessage"), false);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("====>", "Exception");
popUpDialog(RM.CrashError, false);
}
}
private void insertUserPfref() {
// TODO Auto-generated method stub
myDBHelper = new MyDBHelper(OTP.this);
myDBHelper.getWritableDatabase();
if (user_exist.compareTo("true") == 0) {
try {
myDBHelper.insertRegisteredUser(
verifiedNestedResponseKeyValue.get("email"), //
verifiedNestedResponseKeyValue.get("mobile_number"),//
verifiedNestedResponseKeyValue.get("name"), //
verifiedNestedResponseKeyValue.get("country"),
//
verifiedNestedResponseKeyValue.get("country_code"));
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("====>", "Exception");
popUpDialog(RM.CrashError, false);
}
Log.d("------>", "Existing USER");
Log.d("------>", "Existing USER" + user_exist);
} else {
myDBHelper.insertRegisteredUser(userEmailValue,//
userMobValue,//
userNameValue, //
userCountryValue,//
userCountryCode);
Log.d("------>", "New User");
Log.d("------>", "New User" + user_exist);
}
Log.d("------>", user_exist);
startActivity(new Intent(OTP.this, HomeScreen.class));
setResult(10);
finish();
}
#SuppressLint("InflateParams")
private void showNetworFailDialog(String msg) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(OTP.this);
// Get the layout inflater
LayoutInflater inflater = OTP.this.getLayoutInflater();
View content = inflater.inflate(R.layout.network_failure_dialog, null);
builder.setView(content);
builder.setCancelable(false);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
TextView tvMsg = (TextView) content.findViewById(R.id.networkFailMsg);
tvMsg.setText(msg);
content.findViewById(R.id.btnNetworkFailureOK).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
alertDialog.dismiss();
setResult(10);
finish();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(OTP.this, SignInActivity.class);
startActivity(i);
setResult(10);
finish();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
public void recivedSms(String message)
{
try
{
int pos=message.indexOf(':');
String msg = message.substring(pos + 2);
OtpNumber.setText(msg);
OTP = (Button) findViewById(R.id.btnOTPVerify);
OTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
OTP.performClick();
OTP.setPressed(true);
/* if(OtpNumber!=null) {
if (checkValidation()) {
EditText etOTPVerification = (EditText) findViewById(R.id.etOTPVerifaction);
RM.OTP_VER_VALUE = etOTPVerification.getText().toString();
RM.OTP_MOB_VALUE = userMobValue;
if (user_exist.compareTo("true") == 0)
RM.OTP_USER_EXIST_VALUE = "true";
else
RM.OTP_USER_EXIST_VALUE = "false";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put(RM.OTP_VER_KEY, RM.OTP_VER_VALUE);
jsonObject.put(RM.OTP_MOB_KEY, RM.OTP_MOB_VALUE);
jsonObject.put(RM.OTP_USER_EXIST_KEY, RM.OTP_USER_EXIST_VALUE);
jsonObject.put(RM.USER_Id_KEY, userId);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("==", "========= FAIL TO CREATE JSON ==========");
}
ServiceCalls Login = new ServiceCalls(this, RM.OTP_HOST,
jsonObject.toString(), "Verifying", 0, new AsyncResponseActivity() {
#Override
public void myAsyncResponse(String result) {
// TODO Auto-generated method stub
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
Log.d("====>>>>", result);
parseOTPRsponseJason(result);
Log.d("==", "vvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
}
});
if (cd.isConnectingToInternet()) {
Login.execute(1);
} else {
showNetworFailDialog(RM.NO_INTERNET_MSG);
}
} else {
Toast.makeText(this, "Please enter OTP", Toast.LENGTH_LONG).show();
}
}*/
}
catch (Exception e)
{
}
}
}
IncomingMsg.java
package com.nrb.app.nrb.otp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
/**
* Created by Neha on 07-03-2016.
*/
public class IncomingMsg extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
final Bundle bundle = intent.getExtras();
try {
if (bundle != null)
{
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++)
{
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber ;
String message = currentMessage.getDisplayMessageBody();
try
{
if (senderNum.equals("DZ-Onspot"))
{
OTP Sms = new OTP();
Sms.recivedSms(message );
}
}
catch(Exception e){}
}
}
} catch (Exception e)
{
}
}
}
activity_otp.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ripple="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="25dp"
android:gravity="center"
android:orientation="vertical"
android:background="#fff"
android:padding="10dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/onspot" />
<EditText
android:id="#+id/etOTPVerifaction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:inputType="textCapCharacters"
android:ems="10"
android:hint="Enter Verification Key"
android:maxLength="10"
android:singleLine="true">
</EditText>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:padding="5dp"
android:onClick="verifyOTPKEY">
<com.andexert.library.RippleView
android:id="#+id/ripple1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:rv_rippleDuration="200"
app:rv_type="rectangle" >
<Button
android:id="#+id/btnOTPVerify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/button_shadow"
android:text="SUBMIT"
android:onClick="verifyOTPKEY"
android:textColor="#color/white" />
</com.andexert.library.RippleView>
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="verifyOTP"
android:text="Enter Verification key For Login"
android:textAppearance="?android:attr/textAppearanceSmall" />

You're setting it to do nothing. You should comment out these line
OTP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});

Have you tried putting performClick inside Runnable like this,
OTP.post(new Runnable(){
#Override
public void run() {
OTP.performClick();
}
});
OR
Use view tree observer which is used to register listeners that can be notified of global changes in the view tree like here which is efficient in higher level of api than 16
ViewTreeObserver vt = OTP.getViewTreeObserver();
vt.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
vt.removeOnGlobalLayoutListener(this);
OTP.performClick();
}
});

Related

Changing String from buffer to int

So another one from the same code with another problem.
here is the code
package com.test.aplikasirevisi;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import static com.test.aplikasirevisi.Information.Highest;
import static com.test.aplikasirevisi.Information.Lowest;
import static com.test.aplikasirevisi.Information.mypreference;
public class MonitoringScreen extends Activity {
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
TextView highest;
TextView lowest;
private boolean mIsUserInitiatedDisconnect = false;
private TextView mTxtReceive;
private Button mBtnClearInput;
private Button mBtnGetBPM;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private boolean mIsBluetoothConnected = false;
private BluetoothDevice mDevice;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_screen);
ActivityHelper.initialize(this);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
mTxtReceive = (TextView) findViewById(R.id.txtReceive);
chkScroll = (CheckBox) findViewById(R.id.chkScroll);
chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
scrollView = (ScrollView) findViewById(R.id.viewScroll);
mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
mBtnGetBPM = (Button) findViewById(R.id.mBtnGetBPM);
mTxtReceive.setMovementMethod(new ScrollingMovementMethod());
highest = (TextView) findViewById(R.id.etHighest);
lowest = (TextView) findViewById(R.id.etLowest);
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
mBtnClearInput.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mTxtReceive.setText("");
}
});
}
private class ReadInput implements Runnable{
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
String getHi = null;
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Highest)) {
highest.setText(sharedpreferences.getString(Highest, ""));
getHi=highest.getText().toString();
}
if (sharedpreferences.contains(Lowest)) {
lowest.setText(sharedpreferences.getString(Lowest, ""));
}
int hi = Integer.parseInt(getHi);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
if (chkReceiveText.isChecked()) {
mTxtReceive.post(new Runnable() {
#Override
public void run() {
mTxtReceive.append(strInput);
System.out.println(strInput);
if(data < hi){
Log.d(TAG, "succes");
}
int txtLength = mTxtReceive.getEditableText().length();
if(txtLength > mMaxChars){
mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
Log.d(TAG, "text longer than allowed:" + mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars));
}
if (chkScroll.isChecked()) { // Scroll only if this is checked
scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
#Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
}
});
}
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to device");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
}
i want to change the String to int from this part:
final String strInput = new String(buffer, 0, i);
so i can use it on this part :
if(data < hi){
Log.d(TAG, "succes");
}
i tried to use
int data = Integer.parseInt(strInput);
but well of course it span error because its string buffer and only the first one is changed
so how do i solve this prob?if any one can help
I already tried using arraylist but still error
Here is the error code :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.aplikasirevisi, PID: 21905
java.lang.NumberFormatException: For input string: "40
"
at java.lang.Integer.parseInt(Integer.java:615)
at java.lang.Integer.parseInt(Integer.java:650)
at com.test.aplikasirevisi.MonitoringScreen$ReadInput$1.run(MonitoringScreen.java:152)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
I/Process: Sending signal. PID: 21905 SIG: 9
The error message is telling you what is wrong. Your input appears to be "40 and " is not a numeric character. You need make sure your inputted strings are numeric OR you need to extract the numeric component from the string BEFORE attempting to convert it into an integer. You could try new String(buffer, 1, i) if the character at index 0 is always the double quote character.
UPDATE:
Based on your last comment posted here, you need to initialize your strInput as follows (This is an example):
byte[] bytes = new byte[5];
bytes[0] = 49; // this is the ASCII value of the number "1"
bytes[1] = '\u0000'; // These are null characters
bytes[2] = '\u0000';
bytes[3] = '\u0000';
bytes[4] = '\u0000';
String temp = new String(bytes); // convert the byte array to String
String str = temp.substring(0, temp.indexOf('\u0000')); // parse the numeric contents
System.out.println(str); // You should see "1" printed out
int number = Integer.parseInt(str); // Because I parsed the numeric contents, it is safe to convert the String to a number.

AsyncTask and RecyclerView Don't Display the Contents Obtained from JSON on the Internet

I'm making a simple program where I can get a content from JSON in this url
https://www.haliminfo.com/feeds/posts/summary/?max-results=10&start-index=1&alt=json
and make it a list Using RecyclerView on Android.
I have made several necessary components such as Model, Adapter, Post Row Item and HttpHandler
when I try RecyclerView with a method like this it works.
private void addData () {
    postsArrayList = new ArrayList <> ();
    postsArrayList.add (new Posts ("TITLE", "SUMMARY"));
}
but when I apply the method below nothing appears in the activity
private class getContent extends AsyncTask <Void, Void, Void> {
        # Override
        protected Void doInBackground (Void ... voids) {
            HttpHandler sh = new HttpHandler ();
            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall (URL_FIX);
            if (jsonStr! = null) {
                try {
                    JSONObject jsonObj = new JSONObject (jsonStr);
                    JSONObject feed = jsonObj.getJSONObject ("feed");
                    JSONArray entry = feed.getJSONArray ("entry");
                    Posts postsModel = new Posts ();
                    for (int i = 0; i <entry.length (); i ++) {
                        postsModel.setTitle (entry.getJSONObject (i) .getJSONObject ("title"). getString ("$ t"));
                        postsModel.setSummary (entry.getJSONObject (i) .getJSONObject ("summary"). getString ("$ t"));
                        postsArrayList.add (postsModel);
                    }
                } catch (final JSONException e) {
                    Log.e ("RESPONSE", "Json parsing error:" + e.getMessage ());
                    runOnUiThread (new Runnable () {
                        # Override
                        public void run () {
                            Toast.makeText (getApplicationContext (),
                                    "Json parsing error:" + e.getMessage (),
                                    Toast.LENGTH_LONG)
                                    .show ();
                        }
                    });
                }
            } else {
                Log.e ("RESPONSE", "Couldn't get json from server.");
                runOnUiThread (new Runnable () {
                    # Override
                    public void run () {
                        Toast.makeText (getApplicationContext (),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show ();
                    }
                });
            }
            return null;
        }
    }
this is a full file of some important files in my project
MainActivity.java
package com.badjing.bloggercoba.activities;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.badjing.bloggercoba.R;
import com.badjing.bloggercoba.adapter.PostRecyclerViewAdapter;
import com.badjing.bloggercoba.config.Config;
import com.badjing.bloggercoba.handler.HttpHandler;
import com.badjing.bloggercoba.model.Posts;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private PostRecyclerViewAdapter postAdapter;
private ArrayList<Posts> postsArrayList;
private ProgressDialog pDialog;
private Config config = new Config();
String URL_FIX = Config.BLOG_URL + Config.BLOG_URL_MAX_RESULT + Config.MAX_RESULT + config.BLOG_URL_START_INDEX + config.START_INDEX + config.BLOG_URL_ALT_TYPE;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postsArrayList = new ArrayList<>();
new getContent().execute();
recyclerView = (RecyclerView) findViewById(R.id.post_recycle_view);
postAdapter = new PostRecyclerViewAdapter(postsArrayList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(postAdapter);
}
// private void addData() {
//
// postsArrayList = new ArrayList<>();
// postsArrayList.add(new Posts("JUDUL", "SUMMARY"));
//
// }
private class getContent extends AsyncTask<Void, Void, Void> {
// #Override
// protected void onPreExecute() {
// super.onPreExecute();
// // Showing progress dialog
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
// pDialog.show();
// }
#Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL_FIX);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject feed = jsonObj.getJSONObject("feed");
JSONArray entry = feed.getJSONArray("entry");
Posts postsModel = new Posts();
for (int i = 0; i < entry.length(); i++) {
postsModel.setTitle(entry.getJSONObject(i).getJSONObject("title").getString("$t"));
postsModel.setSummary(entry.getJSONObject(i).getJSONObject("summary").getString("$t"));
postsArrayList.add(postsModel);
}
} catch (final JSONException e) {
Log.e("RESPONSE", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e("RESPONSE", "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
}
private void urlBuilder() {
URL_FIX = Config.BLOG_URL + Config.BLOG_URL_MAX_RESULT + 10 + config.BLOG_URL_START_INDEX + 1 + config.BLOG_URL_ALT_TYPE;
}
}
Post.java (post model)
package com.badjing.bloggercoba.model;
public class Posts {
String title;
String summary;
public Posts() {
}
public Posts(String title, String summary) {
this.title = title;
this.summary = summary;
}
public String getTitle() {
return title;
}
public String getSummary() {
return summary;
}
public void setTitle(String title) {
this.title = title;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
PostRecyclerViewAdapter.java
package com.badjing.bloggercoba.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.badjing.bloggercoba.R;
import com.badjing.bloggercoba.model.Posts;
import java.util.ArrayList;
public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostRecyclerViewAdapter.MyViewHolder> {
private ArrayList<Posts> postsList;
public PostRecyclerViewAdapter(ArrayList<Posts> postsArrayList) {
this.postsList = postsArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.post_row_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.blog_post_title.setText(postsList.get(position).getTitle());
holder.blog_post_sumary.setText(postsList.get(position).getSummary());
}
#Override
public int getItemCount() {
return (postsList!= null) ? postsList.size() : 0;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView blog_post_title, blog_post_sumary, blog_post_author;
ImageView img_thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
blog_post_title = itemView.findViewById(R.id.blog_post_title);
blog_post_sumary = itemView.findViewById(R.id.blog_post_sumary);
// blog_post_author = itemView.findViewById(R.id.blog_post_author);
// img_thumbnail = itemView.findViewById(R.id.post_thumbnail);
}
}
}
post_row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="5dp"
android:padding="8dp"
android:background="#fff">
<ImageView
android:id="#+id/post_thumbnail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/loading_shape"></ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="230dp"
android:orientation="vertical"
android:layout_margin="8dp" >
<TextView
android:id="#+id/blog_post_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blog post title"
android:textSize="20dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/blog_post_sumary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blog post summary"/>
<TextView
android:id="#+id/blog_post_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="~ author"/>
</LinearLayout>
</LinearLayout>
thank you for your attention and help.

Google translation API problems on Android

I'm trying to use Google Translation API but I'm getting not null pointer error, this is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.speakingtranslator.GoogleTranslateActivity.translte(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.speakingtranslator.MainActivity.translated(MainActivity.java:332)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:310)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:271)
Here is the code
public void translated() {
String translatetotagalog = editText.getText().toString();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
Log.v("translated text", text);
editTranslate.setText(text);
}
Here is the translte
String translte(String text, String from, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String urlStr = "https://www.googleapis.com/language/translate/v2?key="+ key +"&q=" + encodedText + "&target=" + to + "&source=" + from;
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream stream;
if (conn.getResponseCode() == 200) //success
{
stream = conn.getInputStream();
} else
stream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
String translatedText = obj.get("data").getAsJsonObject().
get("translations").getAsJsonArray().
get(0).getAsJsonObject().
get("translatedText").getAsString();
return translatedText;
}
}
if (conn.getResponseCode() != 200) {
System.err.println(result);
}
} catch (IOException | JsonSyntaxException ex) {
System.err.println(ex.getMessage());
}
return null;
}
Complete MainActivity.java
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
GoogleTranslateActivity translator;
private TextToSpeech textToSpeech;
private Button btn, button2, trans;
String soundName;
MediaPlayer mp = null;
String text2speak;
private boolean connected;
private static final String API_KEY = "API_KEY";
private EditText editText, editTranslate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
btn = findViewById(R.id.material_icon_button);
button2 = findViewById(R.id.material_icon_yoruba);
trans = findViewById(R.id.material_icon_translate);
checkPermission();
editText = findViewById(R.id.editText);
editTranslate = findViewById(R.id.editTranslate);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int ttsLang = textToSpeech.setLanguage(Locale.US);
if (ttsLang == TextToSpeech.LANG_MISSING_DATA
|| ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "The Language is not supported!");
} else {
Log.i("TTS", "Language Supported.");
}
Log.i("TTS", "Initialization success.");
} else {
Toast.makeText(getApplicationContext(), "TTS Initialization failed!", Toast.LENGTH_SHORT).show();
}
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = editText.getText().toString();
Log.i("TTS", "button clicked: " + data);
int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);
if (speechStatus == TextToSpeech.ERROR) {
Log.e("TTS", "Error in converting Text to Speech!");
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
soundName = editTranslate.getText().toString();
soundName = soundName.replaceAll("\\s+", "_").toLowerCase();
SoundManager(soundName);
Toast.makeText(getApplicationContext(), soundName, Toast.LENGTH_LONG).show();
}
});
trans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
text2speak = editText.getText().toString();
new EnglishToTagalog().execute();
}
});
mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null)
editText.setText(matches.get(0));
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.material_icon_mic).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
editText.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
editText.setText("");
editText.setHint("Listening...");
break;
}
return false;
}
});
//Initialize and Assign Variable
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//Set Home Selected
bottomNavigationView.setSelectedItemId(R.id.home);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.messages:
startActivity(new Intent(getApplicationContext(),Messages.class));
overridePendingTransition(0,0);
return true;
case R.id.home:
return true;
case R.id.info:
startActivity(new Intent(getApplicationContext(),Info.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
}
private class EnglishToTagalog extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
protected void onError(Exception ex) {
Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
try {
translator = new GoogleTranslateActivity(API_KEY);
Thread.sleep(15000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
// start the progress dialog
progress = ProgressDialog.show(MainActivity.this, null,
"Translating...");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
translated();
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void translated() {
String translatetotagalog = editText.getText().toString();
Toast.makeText(getApplicationContext(), translatetotagalog, Toast.LENGTH_LONG).show();
Log.v("raw text",translatetotagalog);
String text = translator.translte(translatetotagalog, "en", "yo");
//translatabletext = (TextView) findViewById(R.id.translatabletext);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
Log.v("translated text", text);
editTranslate.setText(text);
}
protected void SoundManager(String sn){
if (mp != null){
mp.reset();
mp.release();
}
switch (sn){
case "e_kaaro":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaaro);
break;
case "e_kaasan":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaasan);
break;
case "e_kaale":
mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaale);
break;
case "bawo_ni_o_se_n_se":
mp = MediaPlayer.create(getApplicationContext(), R.raw.bawo_ni_o_se_n_se);
break;
case "mo_nife_re":
mp = MediaPlayer.create(getApplicationContext(), R.raw.mo_nife_re);
break;
default:
mp = MediaPlayer.create(getApplicationContext(), R.raw.crowd);
}
//Toast.makeText(getApplicationContext(), "clicked " + sn, Toast.LENGTH_LONG).show();
mp.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
public boolean checkInternetConnection() {
//Check internet connection:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//Means that we are connected to a network (mobile or wi-fi)
connected = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
return connected;
}
}

When I trying to Click on Paired device list of bluetooth then it will unfortunately , MyApp has stopped message display and my application is closed

When I click on paired device list of Bluetooth, application crashes , and I get a message saying 'MyApp has stopped
When I start my application first time it doesn't show my Paired devices in paired devices list but when i switch off the display and switch it on again it shows.
package com.example.bluetoothapp;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch, buttonOn, buttonDesc, buttonOff;
ArrayAdapter<String> adapter, detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth
* devices; this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
adapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
TextView txt = (TextView) arg1;
Toast.makeText(MainActivity.this,
"" + txt.getText().toString(), 1000).show();
}
});
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if (pairedDevice.size() > 0) {
for (BluetoothDevice device : pairedDevice) {
arrayListpaired.add(device.getName() + "\n"
+ device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
}
class ListItemClicked implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
// bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : " + bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we
* can directly call the connect(). but for the safer side we must
* usethe threading object.
*/
// callThread();
// connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if (isBonded) {
// arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
getPairedDevices();
}
} catch (Exception e) {
e.printStackTrace();
}// connect(bdDevice);
Log.i("Log", "The bond is created: " + isBonded);
}
}
class ListItemClickedonPaired implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBonding = removeBond(bdDevice);
if (removeBonding) {
arrayListpaired.remove(position);
}
Log.i("Log", "Removed" + removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* private void callThread() { new Thread(){ public void run() { Boolean
* isBonded = false; try { isBonded = createBond(bdDevice); if(isBonded) {
* arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
* adapter.notifyDataSetChanged(); } } catch (Exception e) { // TODO
* Auto-generated catch block e.printStackTrace(); }//connect(bdDevice);
* Log.i("Log", "The bond is created: "+isBonded); } }.start(); }
*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);// , args);// this invoke
// creates the detected
// devices paired.
// Log.i("Log", "This is: "+bool.booleanValue());
// Log.i("Log", "devicesss: "+bdDevice.getName());
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice) throws Exception {
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice) throws Exception {
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT)
.show();
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
// device.getClass().getMethod("setPairingConfirmation",
// boolean.class).invoke(device, true);
// device.getClass().getMethod("cancelPairingUserInput",
// boolean.class).invoke(device);
} catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if (arrayListBluetoothDevices.size() < 1) // this checks if the
// size of bluetooth
// device is 0,then
// add the
{ // device to the arraylist.
detectedAdapter.add(device.getName() + "\n"
+ device.getAddress());
arrayListBluetoothDevices.add(device);
} else {
boolean flag = true; // flag to indicate that particular
// device is already in the arlist
// or not
for (int i = 0; i < arrayListBluetoothDevices.size(); i++) {
if (device.getAddress().equals(
arrayListBluetoothDevices.get(i).getAddress())) {
flag = false;
}
}
if (flag == true) {
detectedAdapter.add(device.getName() + "\n"
+ device.getAddress());
arrayListBluetoothDevices.add(device);
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
MainActivity.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
}

Updating the UI upon receiving an android push notification

I have a query regarding android push notification and i had asked it in another stackoverflow post and i did not get much help out of it [Query regarding Android push notifications. So i am posting it again, and it is as follows:
I have an android app that receives push notifications from Google push notification service. When i tap on the received notification, it opens an UI which displays this message, it is a list view. Now, when the user receives the push notification, and assuming that this screen is open, the UI should be refreshed automatically, such that it displays the latest notification. Could anybody let me know how i can solve this?
Below is my code that i have implemented:
Java code to receive the notification:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import com.example.foodu.R;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCM ::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "53340195486";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
#Override
protected void onMessage(Context context, Intent data) {
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, com.example.foodu.Notification.class);
// Pass data to the new activity
intent.putExtra("message", message);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setWhen(System.currentTimeMillis())
.setContentTitle("Deals")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}
#Override
protected void onUnregistered(Context arg0, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
}
The code for the corresponding activity that would be launched when the user taps on the notification:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import com.example.foodu.R;
import com.example.foodu.R.drawable;
import com.example.foodu.R.id;
import com.example.foodu.R.layout;
import com.example.foodu.R.menu;
import com.google.android.gcm.GCMRegistrar;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Notification extends ActionBarActivity {
LinkedList<NotificationData> notificationList = new LinkedList<NotificationData>();
ListView listView = null;
NotificationListAdapter adaptor;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
listView = (ListView) findViewById(R.id.listView1);
// Retrive the data from GCMIntentService.java
Intent i = getIntent();
String message = i.getStringExtra("message");
//getDataForDisplay();
if(message!=null)
{
parseData(message);
}else{
getDataToDisplay();
}
adaptor = new NotificationListAdapter(getApplicationContext(), notificationList);
listView.setAdapter(adaptor);
TextView emptyText = (TextView) findViewById(R.id.empty);
emptyText.setText("No Events Yet!");
listView.setEmptyView(emptyText);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
onListitemSelect(position);
view.setSelected(true);
return true;
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
adaptor.notifyDataSetChanged();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
void writeToFile(){
FileOutputStream fos;
try {
fos = openFileOutput("varun", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(notificationList);
oos.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void readFromFile(){
try{
FileInputStream fis = openFileInput("varun");
ObjectInputStream ois = new ObjectInputStream(fis);
LinkedList<NotificationData> local = (LinkedList<NotificationData>) ois.readObject();
ois.close();
for (int i = 0; i < local.size(); i++) {
notificationList.add(local.get(i));
}
}catch(Exception e){
e.printStackTrace();
}
}
private void getDataToDisplay() {
// TODO Auto-generated method stub
readFromFile();
}
private void parseData(String message) {
try {
int len = 0;
String[] stringArr = new String[100];
StringTokenizer st = new StringTokenizer(message, ".");
len = st.countTokens();
for (int i = 0; i < len; i++) {
if (st.hasMoreTokens()) {
stringArr[i] = st.nextToken();
}
}
NotificationData data = new NotificationData();
data.title = stringArr[0];
data.venue = stringArr[1];
data.date = stringArr[2];
data.time = stringArr[3];
notificationList.add(data);
readFromFile();
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDateToDisplay() {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
writeToFile();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notificationmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_register){
registerDevice();
return true;
}
return super.onOptionsItemSelected(item);
}
private void registerDevice() {
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
GCMRegistrar
.register(Notification.this, GCMIntentService.SENDER_ID);
} catch (Exception e) {
e.printStackTrace();
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.notificationcontext, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_calender:
addToCalender();
mode.finish();
return true;
case R.id.menu_delete:
//deleteData();
showAlertBox();
return false;
case R.id.menu_share:
shareDate();
mode.finish();
return true;
case R.id.menu_copy:
copyToClip();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
adaptor.removeSelection();
}
};
void onListitemSelect(int position) {
adaptor.toggleSelection(position);
boolean hasCheckedItems = adaptor.getSelectedCount() > 0;
if (hasCheckedItems && mActionMode == null) {
mActionMode = startActionMode((Callback) mActionModeCallback);
} else if (!hasCheckedItems && mActionMode != null) {
mActionMode.finish();
}
if (mActionMode != null)
mActionMode.setTitle(String.valueOf(adaptor.getSelectedCount()));
}
protected void showAlertBox() {
// TODO Auto-generated method stub
AlertDialog.Builder builder1 = new AlertDialog.Builder(Notification.this);
builder1.setMessage("Delete " + adaptor.getSelectedIds().size()+ " events?");
builder1.setCancelable(true);
builder1.setIcon(R.drawable.alert);
builder1.setTitle("Caution");
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteData();
mActionMode.finish();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
protected void copyToClip() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Notification App", shareText);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Data copied to ClipBoard",
Toast.LENGTH_LONG).show();
}
protected void shareDate() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
String share = shareText.toString();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, share);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
protected void deleteData() {
int count = 0;
int startPoint = adaptor.getSelectedIds().keyAt(0);
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
adaptor.remove(notificationList.get(startPoint));
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message+" deleted", Toast.LENGTH_LONG)
.show();
}
private void addToCalender() {
try {
int count = 0;
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
ContentResolver cr = getApplicationContext()
.getContentResolver();
ContentValues values = new ContentValues();
String myDate = data.date + " " + data.time;
String timeArr[] = data.time.split("to");
SimpleDateFormat sfd = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy 'Time: 'hh a", Locale.getDefault());
long time = sfd.parse(myDate).getTime();
values.put(CalendarContract.Events.DTSTART, time);
if (timeArr.length > 0) {
String endTime = timeArr[1];
SimpleDateFormat timeFormat = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy hh a", Locale.getDefault());
long endtime = timeFormat.parse(data.date + " " + endTime)
.getTime();
values.put(CalendarContract.Events.DTEND, endtime);
}
values.put(CalendarContract.Events.TITLE, data.title);
values.put(CalendarContract.Events.DESCRIPTION, data.venue);
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE,
timeZone.getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1);
Uri uri = cr
.insert(CalendarContract.Events.CONTENT_URI, values);
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message + " added to Calender", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use LocalBroadcastManager
Check following code / steps
1) Add in your activity (UI refresh Activity)
private BroadcastReceiver mMyBroadcastReceiver;
Then ,
2) In onResume
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
// Here you can refresh your listview or other UI
Toast.makeText(getApplicationContext(), "Receiver", 2000).show();
}
};
try {
LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new IntentFilter("your_action"));
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}}
// and your other code
3) Then unregister in onPause
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyBroadcastReceiver);
}
4) Finally add in your GCM reciver class.
first check your activity is Visible or not using static variable
if visible add
Intent gcm_rec = new Intent("your_action"); LocalBroadcastManager.getInstance(arg0).sendBroadcast(gcm_rec);
else
use Notification Manager for notification.
I think this is easy and best way to refresh your listview UI / call Fetching method.

Categories