Theres edit text field. It has to work like this:
1) if it is empty - nothing happen
2) if user put some NEW text starts method of TextWatcher with HTTP request which takes JSON object. Also the value of String will put in sharedpreference
3) if user open activity when sharedpreference already have value of previous string it has to just set text from that string and don't start method of TextWatcher with HTTP request.
So there are three conditions and progrmm has to make request only in case when value of string is not tha same as in shared pref. Now it sends request even if person just open app. I want to avoid wrong requests and make request only after new value of string.
THE MAIN QUESTION: How to launch HTTP request code ONLY in case if value in textfield is not the same as in sharedpref?
P.S. If you think my question is bad. Please tell me in notes NOT JUST MAKE -1 please. Teach new programmers
Here is the code
public class MainActivity extends AppCompatActivity {
AppCompatButton chooseLanguageButton;
AppCompatButton cleanButton;
AppCompatEditText translatedTextOutput;
AppCompatEditText translatedTextInput;
String translatedInputString;
RequestQueue requestQueue;
final String TAG = "myTag";
String language;
SharedPreferences mSettings;
SharedPreferences textReference;
SharedPreferences translateReference;
SharedPreferences longLangReference;
SharedPreferences shortLangReference;
final String SAVED_TEXT = "text";
final String SAVED_TRANSLATION = "translation";
final String LANGUAGE_LONG = "lang_long";
final String LANGUAGE_SHORT = "lang_short";
public static final String APP_PREFERENCES = "mysettings";
private ProgressBar progressBar;
private Timer timer;
private TextWatcher searchTextWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
Log.v(TAG, "in afterTextChanged");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (translatedTextInput.getText().length() != 0){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
requestQueue = Volley.newRequestQueue(MainActivity.this);
sendJsonRequest();
}
});
}
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(translatedTextInput.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 600);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (timer != null) {
timer.cancel();
}
saveText();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "in Oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseLanguageButton = (AppCompatButton) findViewById(R.id.choose_language_button);
cleanButton = (AppCompatButton) findViewById(R.id.clean_button);
translatedTextOutput = (AppCompatEditText) findViewById(R.id.translated_text_field);
translatedTextInput = (AppCompatEditText) findViewById(R.id.translation_input_edit);
int textLength = translatedTextInput.getText().length();
translatedTextInput.setSelection(textLength);
translatedTextInput.addTextChangedListener(searchTextWatcher);
chooseLanguageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v(TAG, "in chooseLanguageListener");
Intent intent = new Intent(MainActivity.this, ChooseLanguageList.class);
startActivity(intent);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
translatedTextInput.setText("");
translatedTextOutput.setText("");
}
});
mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
if (mSettings.contains(LANGUAGE_LONG)){
Log.v(TAG, "here");
chooseLanguageButton.setText(mSettings.getString(LANGUAGE_LONG,""));
} else {
Log.v(TAG, "THERE");
chooseLanguageButton.setText("Choose language");
}
if (mSettings.contains(SAVED_TEXT)){
Log.v(TAG, "here");
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
} else {
Log.v(TAG, "boooooom");
}
if (mSettings.contains(SAVED_TRANSLATION)){
Log.v(TAG, "here in TRANSLATION FIELD" + mSettings.getString(SAVED_TRANSLATION,""));
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
} else {
Log.v(TAG, "boooooom");
}
}
#Override
protected void onResume() {
super.onResume();
translatedTextInput.post(new Runnable() {
#Override
public void run() {
Selection.setSelection(translatedTextInput, );
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mSettings = null;
}
void saveText() {
// mSettings = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
SharedPreferences.Editor ed = mSettings.edit();
ed.putString(SAVED_TEXT, translatedTextInput.getText().toString());
ed.putString(SAVED_TRANSLATION, translatedTextOutput.getText().toString());
ed.apply();
Log.v(TAG, "Text saved==========>" + translatedTextInput.getText().toString());
Toast.makeText(this, "Text saved", Toast.LENGTH_SHORT).show();
}
void loadText() {
textReference = getSharedPreferences(SAVED_TEXT, MODE_PRIVATE);
translatedTextInput.setText(mSettings.getString(SAVED_TEXT,""));
translateReference = getSharedPreferences(SAVED_TRANSLATION, MODE_PRIVATE);
translatedTextOutput.setText(mSettings.getString(SAVED_TRANSLATION,""));
Log.v(TAG, "IN LOAD TEXT METHOD" + mSettings.getString(SAVED_TEXT,""));
Log.v(TAG, "IN LOAD TRANSLATION METHOD" + mSettings.getString(SAVED_TRANSLATION,""));
}
public void sendJsonRequest() {
Log.v(TAG, "in sendJsonObject");
Intent myIntent = getIntent();
// language = myIntent.getStringExtra("short");
shortLangReference = getSharedPreferences(LANGUAGE_SHORT, MODE_PRIVATE);
language = mSettings.getString(LANGUAGE_SHORT,"");
Log.v(getClass().getSimpleName(), "language short = " + language);
translatedInputString = translatedTextInput.getText().toString().replace(" ","+");
String url = String.format(getApplicationContext().getResources().getString(R.string.request_template),
String.format(getApplicationContext().getResources().getString(R.string.query_Template), translatedInputString, language ));
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.v(TAG, "Inside OnResponse" + response.toString());
JSONArray results = null;
try {
results = response.getJSONObject("data").getJSONArray("translations");
for (int i=0,j=results.length();i<j;i++) {
String webTitle = results.getJSONObject(i).getString("translatedText");
translatedTextOutput.setText(webTitle);
}
} catch (JSONException e) {
Log.e(TAG, "Error :" + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Log.e(TAG, "NetworkError");
} else if (error instanceof ServerError) {
Log.e(TAG, "The server could not be found. Please try again after some time!!");
} else if (error instanceof AuthFailureError) {
Log.e(TAG, "AuthFailureError");
} else if (error instanceof ParseError) {
Log.e(TAG, "Parsing error! Please try again after some time!!");
} else if (error instanceof NoConnectionError) {
Log.e(TAG, "NoConnectionError!");
} else if (error instanceof TimeoutError) {
Log.e(TAG, "Connection TimeOut! Please check your internet connection.");
}
}
});
requestQueue.add(jsObjRequest);
}
}
Related
I have a problem with a volley to send multiple JSON with StringRequest, I think the problem is in the hashmap un getParms()
public class MainActivity extends AppCompatActivity {
private static final String TAG = "ENCUESTA";
private static final String VERSION = "2.0.0.3";
private int totalEncuestas=0;
private Encuestador encuestador;
Button btnRutEncuestador;
Button btnEmisivo;
Button btnReceptivo;
Button btnEnvioData;
EditText txtRut;
EditText txtDV;
EditText txtDebug;
TextView lblVersion;
private JSONObject itemEnviar;
private int contador;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
encuestador = new Encuestador();
btnRutEncuestador = (Button) findViewById(R.id.btnRutEncuestador);
btnEmisivo = (Button) findViewById(R.id.btnEmisivo);
btnReceptivo = (Button) findViewById(R.id.btnReceptivo);
btnEnvioData = (Button) findViewById(R.id.btnEnvioData);
txtRut = (EditText) findViewById(R.id.txtRut);
txtDV = (EditText) findViewById(R.id.txtDV);
lblVersion = (TextView) findViewById(R.id.lblVersion);
//DEBUG
//btnReceptivo.setEnabled(true);
//btnEmisivo.setEnabled(true);
lblVersion.setText(Util.getVersion());
//region SIN USO
/*ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
if(!Util.leerArchivo(MainActivity.this, "data.txt").isEmpty()) {
if(Util.verificaConexion(MainActivity.this)) {
Log.d(TAG, "Enviando información");
RequestQueue MyRequestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.inicial.cl/android/set.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.isEmpty() && response.equalsIgnoreCase("success")) {
Log.d(TAG, "success, elimina data local");
Util.vaciarEncuesta(MainActivity.this);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onError: " + error);
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
try {
MyData.put("data", Util.leerArchivo(MainActivity.this, "data.txt"));
} catch (Exception e) {
Log.e(TAG, "Error al enviar: " + e.getMessage());
}
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
}else{
Log.d(TAG, "Sin internet");
}
}else{
Log.d(TAG, "Sin data");
}
}
}, 0, 5, TimeUnit.MINUTES);*/
/*txtRut.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
String txt = Util.getTextFromEditText(txtRut);
if(!txt.isEmpty() && txt.equalsIgnoreCase("123123"))
{
txtDebug.setVisibility(View.VISIBLE);
txtDebug.setText(Util.leerArchivo(MainActivity.this, "data.txt"));
}else
{
txtDebug.setVisibility(View.GONE);
txtDebug.setText("");
}
}
});*/
//endregion
//region btnRutEncuestador
btnRutEncuestador.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strRut = txtRut.getText().toString();
String strDV = txtDV.getText().toString();
if (strRut.isEmpty()) {
Toast.makeText(getApplicationContext(), "Debe ingresar rut", Toast.LENGTH_SHORT).show();
return;
}
if (strDV.isEmpty()) {
Toast.makeText(getApplicationContext(), "Debe ingresar DV", Toast.LENGTH_SHORT).show();
return;
}
Boolean existeEncuestador = false;
for (Encuestador e : Encuestador.getAllEncuestadores()) {
Log.d(TAG, "RutIngresado=" + strRut + "-" + strDV + " RutBase:" + e.getRut() + "-" + e.getDv());
if (strRut.equalsIgnoreCase(e.getRut()) && strDV.equalsIgnoreCase(e.getDv())) {
encuestador = new Encuestador();
encuestador.setRut(strRut);
encuestador.setDv(strDV);
btnReceptivo.setEnabled(true);
btnEmisivo.setEnabled(true);
existeEncuestador = true;
break;
} else {
existeEncuestador = false;
}
}
if (!existeEncuestador) {
Util.alertDialog(MainActivity.this, "El Rut ingresado no esta habilitado para realizar encuestas",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
}
});
//endregion
//region btnEmisivo
btnEmisivo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), EmisivoActivity.class);
intent.putExtra("ENCUESTADOR", encuestador);
startActivity(intent);
}
});
//endregion
//region btnReceptivo
btnReceptivo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), ReceptivoActivity.class);
intent.putExtra("ENCUESTADOR", encuestador);
startActivity(intent);
}
});
//endregion
//region btnEnvioData
btnEnvioData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnEnvioData.setEnabled(false);
if (!Util.leerArchivo(MainActivity.this, "data.txt").isEmpty()) {
if (Util.verificaConexion(MainActivity.this)) {
Log.d(TAG, "Enviando información");
try {
JSONArray list = new JSONArray(Util.leerArchivo(MainActivity.this, "data.txt"));
totalEncuestas = list.length();
setContador(0);
for (int i = 0; i < list.length(); i++) {
Log.d(TAG, "DATA:"+list.getJSONObject(i));
setItemEnviar(list.getJSONObject(i));
sendRequest();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Sin internet");
Util.alertDialog(MainActivity.this, "Error, no hay conexión a internet",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
}
} else {
Log.d(TAG, "Sin data");
Util.alertDialog(MainActivity.this, "Sin encuestas que enviar",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
}
}
});
//endregion
}
public void sendRequest()
{
RequestQueue MyRequestQueue = Volley.newRequestQueue(MainActivity.this);
String url = "http://www.inicial.cl/android/set.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (!response.isEmpty() && response.equalsIgnoreCase("success")) {
setContador(getContador() + 1);
if(getContador() == totalEncuestas) {
Util.alertDialog(MainActivity.this, "Encuestas enviadas exitosamente!",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
btnEnvioData.setEnabled(true);
Util.vaciarEncuesta(MainActivity.this);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onError: " + error);
btnEnvioData.setEnabled(true);
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
try {
MyData.put("data"+Integer.toString(getContador()), getItemEnviar().toString().replaceAll("\n", ""));
Log.e(TAG, "enviados: " + getItemEnviar().toString());
} catch (Exception e) {
Log.e(TAG, "Error al enviar: " + e.getMessage());
btnEnvioData.setEnabled(true);
}
return MyData;
}
};
MyRequestQueue.add(MyStringRequest);
MyRequestQueue.getCache().clear();
}
public JSONObject getItemEnviar() {
return itemEnviar;
}
public void setItemEnviar(JSONObject itemEnviar) {
this.itemEnviar = itemEnviar;
}
public int getContador() {
return contador;
}
public void setContador(int contador) {
this.contador = contador;
}
}
The problem is when I get the data to send, in the for the JSON for send are ok, but in the getparms() this only set the last JSON for send, and send many times of the total array
I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.
Hey I have some problem with Gcm intent service at calling `subscribeToTopicP class, that always getting null pointer exception.
Here is my code:
GcmIntentService.java
private static final String TAG = GcmIntentService.class.getSimpleName();
public GcmIntentService() {
super(TAG);
}
public static final String KEY = "key";
public static final String TOPIC = "topic";
public static final String SUBSCRIBE = "subscribe";
public static final String UNSUBSCRIBE = "unsubscribe";
public SessionManager session;
#Override
protected void onHandleIntent(Intent intent) {
session = new SessionManager(getApplicationContext());
String key = intent.getStringExtra(KEY);
switch (key) {
case SUBSCRIBE:
// subscribe to a topic
String topic = intent.getStringExtra(TOPIC);
subscribeToTopic(topic);
break;
case UNSUBSCRIBE:
break;
default:
// if key is specified, register with GCM
registerGCM();
}
}
/**
* Registering with GCM and obtaining the gcm registration id
*/
private void registerGCM() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Log.e(TAG, "GCM Registration Token: " + token);
// sending the registration id to our server
sendRegistrationToServer(token);
sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, true).apply();
} catch (Exception e) {
Log.e(TAG, "Failed to complete token refresh", e);
sharedPreferences.edit().putBoolean(Config.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Config.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
private void sendRegistrationToServer(final String token) {
// checking for valid login session
session.isLoggedIn();
HashMap<String, String> user = session.getUserDetails();
String UserId = user.get(SessionManager.KEY_ID);
String endPoint = EndPoints.UPDATE_USER_GCM.replace("_ID_", UserId);
Log.e(TAG, "endpoint: " + endPoint);
StringRequest strReq = new StringRequest(Request.Method.PUT, endPoint, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
// check for error
if (obj.getBoolean("error") == false) {
// broadcasting token sent to server
Intent registrationComplete = new Intent(Config.SENT_TOKEN_TO_SERVER);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
} else {
Toast.makeText(getApplicationContext(), "Unable to send gcm registration id to our sever. " + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("UserGcmRegistrationId", token);
Log.e(TAG, "params: " + params.toString());
return params;
}
};
//Adding request to request queue
Volley.newRequestQueue(getApplicationContext()).add(strReq);
}
/**
* Subscribe to a topic
*/
public static void subscribeToTopic(String topic) {
GcmPubSub pubSub = GcmPubSub.getInstance(MyApplication.getInstance().getApplicationContext());
InstanceID instanceID = InstanceID.getInstance(MyApplication.getInstance().getApplicationContext());
String token = null;
try {
token = instanceID.getToken(MyApplication.getInstance().getApplicationContext().getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
if (token != null) {
pubSub.subscribe(token, "/topics/" + topic, null);
Log.e(TAG, "Subscribed to topic: " + topic);
} else {
Log.e(TAG, "error: gcm registration id is null");
}
} catch (IOException e) {
Log.e(TAG, "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage());
Toast.makeText(MyApplication.getInstance().getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void unsubscribeFromTopic(String topic) {
GcmPubSub pubSub = GcmPubSub.getInstance(getApplicationContext());
InstanceID instanceID = InstanceID.getInstance(getApplicationContext());
String token = null;
try {
token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
if (token != null) {
pubSub.unsubscribe(token, "");
Log.e(TAG, "Unsubscribed from topic: " + topic);
} else {
Log.e(TAG, "error: gcm registration id is null");
}
} catch (IOException e) {
Log.e(TAG, "Topic unsubscribe error. Topic: " + topic + ", error: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Topic subscribe error. Topic: " + topic + ", error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
My LogCat Error :
E/AndroidRuntime: FATAL EXCEPTION: IntentService[GcmIntentService]
Process: com.nvitek.www.aspirasirakyat, PID: 25962
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107)
at com.nvitek.www.aspirasirakyat.gcm.GcmIntentService.subscribeToTopic(GcmIntentService.java:155)
at com.nvitek.www.aspirasirakyat.gcm.GcmIntentService.onHandleIntent(GcmIntentService.java:56)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
MyApplication.java
public static final String TAG = MyApplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
private SessionManager pref;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
if(mInstance==null)
{
mInstance=new MyApplication();
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public SessionManager getPrefManager() {
if (pref == null) {
pref = new SessionManager(this);
}
return pref;
}
And here my ActivityDashboard.java
//JSON TAGS
public static final String TAG_IMAGE_URL = "image";
public static final String TAG_TITLE = "title";
public static final String TAG_FNAME = "fname";
public static final String TAG_LNAME = "lname";
public static final String TAG_CONTENT = "content";
public static final String TAG_DATE = "date";
public static final String TAG_ID = "id";
private String TAG = ActivityDashboard.class.getSimpleName();
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private List<ListItem> listItems;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
//Volley Request Queue
private RequestQueue requestQueue;
private Boolean exit = false;
SessionManager session;
JSONArray users = null;
DrawerLayout drawerLayout;
NavigationView mNavigationView;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
session = new SessionManager(getApplicationContext());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_menu_white);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
Intent intent;
switch (menuItem.getItemId()) {
case R.id.navigation_item_1:
intent = new Intent(ActivityDashboard.this, ActivityDashboard.class);
startActivity(intent);
return true;
/* case R.id.navigation_item_2:
intent = new Intent(ActivityDashboard.this, ActivityDashboard.class);
startActivity(intent);
return true; */
case R.id.navigation_item_3:
intent = new Intent(ActivityDashboard.this, ActivityStatistic.class);
startActivity(intent);
return true;
case R.id.navigation_item_4:
intent = new Intent(ActivityDashboard.this, ActivityProfile.class);
startActivity(intent);
return true;
case R.id.navigation_item_5:
session.logoutUser();
return true;
default:
return true;
}
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Loading...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
gotoAdd(view);
}
});
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
// gcm successfully registered
// now subscribe to `global` topic to receive app wide notifications
subscribeToGlobalTopic();
} else if (intent.getAction().equals(Config.SENT_TOKEN_TO_SERVER)) {
// gcm registration id is stored in our server's MySQL
Log.e(TAG, "GCM registration id is sent to our server");
} else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
// new push notification is received
handlePushNotification(intent);
}
}
};
}
#Override
public void onStart() {
super.onStart();
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(ActivityDashboard.this, recyclerView, new ClickListener() {
#Override
public void onListClick(View v, int position) {
Intent intent = new Intent(ActivityDashboard.this, ActivityPreviewPost.class);
intent.putExtra("Url_Key", EndPoints.COMMENTS + "?id=" + listItems.get(position).getId());
intent.putExtra("Id_Key", listItems.get(position).getId());
intent.putExtra("Photo_Key", listItems.get(position).getImageUrl());
intent.putExtra("Title_Key", listItems.get(position).getTitle());
intent.putExtra("FName_Key", listItems.get(position).getFName());
intent.putExtra("LName_Key", listItems.get(position).getLName());
intent.putExtra("Date_Key", listItems.get(position).getDate());
intent.putExtra("Content_Key", listItems.get(position).getContent());
startActivity(intent);
}
#Override
public void onListLongClick(View v, int position) {
}
}));
//Initializing our list
listItems = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
//Calling method to get data to fetch data
if (checkPlayServices()) {
registerGCM();
getData();
}
//initializing our adapter
adapter = new CardAdapter(listItems, this);
//Adding adapter to recyclerview
recyclerView.setAdapter(adapter);
}
/**
* Handles new push notification
*/
private void handlePushNotification(Intent intent) {
int type = intent.getIntExtra("type", -1);
// if the push is of chat room message
// simply update the UI unread messages count
if (type == Config.PUSH_TYPE_CHATROOM) {
ListComment listComment = (ListComment) intent.getSerializableExtra("CommentContent");
String chatRoomId = intent.getStringExtra("TimelineId");
if (listComment != null && chatRoomId != null) {
updateRow(chatRoomId, listComment);
}
} else if (type == Config.PUSH_TYPE_USER) {
// push belongs to user alone
// just showing the message in a toast
ListComment listComment = (ListComment) intent.getSerializableExtra("CommentContent");
Toast.makeText(getApplicationContext(), "New push: " + listComment.getCommentContent(), Toast.LENGTH_LONG).show();
}
}
private void updateRow(String chatRoomId, ListComment listComment) {
for (ListItem cr : listItems) {
if (cr.getId().equals(chatRoomId)) {
int index = listItems.indexOf(cr);
cr.setLastMessage(listComment.getCommentContent());
cr.setUnreadCount(cr.getUnreadCount() + 1);
listItems.remove(index);
listItems.add(index, cr);
break;
}
}
adapter.notifyDataSetChanged();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private JsonArrayRequest getDataFromServer() {
//JsonArrayRequest of volley
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(EndPoints.TIMELINES,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Calling method parseData to parse the json response
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ActivityDashboard.this, "No More Items Available", Toast.LENGTH_SHORT).show();
}
});
return jsonArrayRequest;
}
//This method will get data from the web api
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
requestQueue.add(getDataFromServer());
}
//This method will parse json data
private void parseData(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
//Creating the superhero object
ListItem listItem = new ListItem();
JSONObject json = null;
try {
//Getting json
json = array.getJSONObject(i);
//Adding data to the superhero object
listItem.setId(json.getString(TAG_ID));
listItem.setImageUrl(json.getString(TAG_IMAGE_URL));
listItem.setTitle(json.getString(TAG_TITLE));
listItem.setFName(json.getString(TAG_FNAME));
listItem.setLName(json.getString(TAG_LNAME));
listItem.setContent(json.getString(TAG_CONTENT));
listItem.setDate(json.getString(TAG_DATE));
} catch (JSONException e) {
e.printStackTrace();
}
//Adding the superhero object to the list
listItems.add(listItem);
}
//Notifying the adapter that data has been added or changed
adapter.notifyDataSetChanged();
subscribeToAllTopics();
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector mGestureDetector;
private ClickListener mClickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.mClickListener = clickListener;
mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
if (child!=null && clickListener!=null){
clickListener.onListLongClick(child, recyclerView.getChildAdapterPosition(child));
}
super.onLongPress(e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
mClickListener.onListClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public void gotoAdd(View view) {
Intent intent = new Intent(this, ActivityAddPost.class);
Log.e("aspirasi", "change activity");
startActivity(intent);
}
// subscribing to global topic
private void subscribeToGlobalTopic() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, Config.TOPIC_GLOBAL);
startService(intent);
}
// Subscribing to all chat room topics
// each topic name starts with `topic_` followed by the ID of the chat room
// Ex: topic_1, topic_2
private void subscribeToAllTopics() {
for (ListItem cr : listItems) {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra(GcmIntentService.KEY, GcmIntentService.SUBSCRIBE);
intent.putExtra(GcmIntentService.TOPIC, "topic_" + cr.getId());
startService(intent);
}
}
#Override
protected void onResume() {
super.onResume();
// register GCM registration complete receiver
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.REGISTRATION_COMPLETE));
// register new push message receiver
// by doing this, the activity will be notified each time a new message arrives
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Config.PUSH_NOTIFICATION));
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
// starting the service to register with GCM
private void registerGCM() {
Intent intent = new Intent(this, GcmIntentService.class);
intent.putExtra("key", "register");
startService(intent);
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.i(TAG, "This device is not supported. Google Play Services not installed!");
Toast.makeText(getApplicationContext(), "This device is not supported. Google Play Services not installed!", Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
#Override
public void onStop() {
super.onStop();
}
public static interface ClickListener{
public void onListClick(View v, int position);
public void onListLongClick(View v, int position);
}
#Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
// Before 2.0
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
return true;
}
return super.onKeyUp(keyCode, event);
}
This issue is due to variable not being instantiated. You are using the activity as a Context too early. You need to wait until onCreate() or later in the activity lifecycle. You can't call getApplicationContext() until after onCreate() is called. The Activity is not fully initialized until then.
I am trying to validate the Nymi band asynchronously . But when I try to do that, I get the following exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
I have all the toasts in the following method as you can see:
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
But Still I get the exception. The method works fine when run normally in the onCreate() method,but fails to run asynchronously .
Edit: Even after removing all the toasts, I still get the exception.
Here is my Thread class,where I am calling the validate() asynchronously :
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
TestBluetooth tb=new TestBluetooth();
tb.startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
Here is the main class where I have the validate methods:
public class TestBluetooth extends Activity implements OnClickListener,ProvisionController.ProvisionProcessListener,
ValidationController.ValidationProcessListener {
boolean isBluetoothEnabled = false;
static boolean nclInitialized = false;
static final String LOG_TAG = "AndroidExample";
SharedPreferences prefs;
Button checkBlue,proviNymi,validateNymi,disconnectNymi;
ProvisionController provisionController;
ValidationController valiationController;
boolean connectNymi = true;
int nymiHandle = Ncl.NYMI_HANDLE_ANY;
NclProvision provision;
//NclProvision provisionmid;
String temp_ID,temp_Key;
public String keyuse;
public String iduse;
public LinearLayout progressbar;
public ProgressBar pbHeaderProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testbluetooth);
// I tried this too final Handler timedThread= new Handler(Looper.getMainLooper());
final Handler timedThread=new Handler();
timedThread.postDelayed(new Runnable() {
#Override
public void run() {
NymiAsync task=new NymiAsync();
task.execute(1,1,1);
}
},10000);
}
public void startValidatingNymi(){
progressbar = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
pbHeaderProgress=(ProgressBar) findViewById(R.id.pbHeaderProgress);
pbHeaderProgress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#1109EE"), android.graphics.PorterDuff.Mode.SRC_ATOP);
// prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
// prefs.edit().clear().commit();
prefs=getSharedPreferences(Util.SharedPrefKey,MODE_PRIVATE);
temp_ID = prefs.getString(Util.provID, null);
temp_Key = prefs.getString(Util.provKey, null);
if ((temp_ID!=null) || (temp_Key!=null)){
// SHOW THE SPINNER WHILE LOADING FEEDS
progressbar.setVisibility(View.VISIBLE);
//Toast.makeText(getBaseContext(), "Nymi band is already provisined" , Toast.LENGTH_SHORT ).show();
initializeNcl();
provision = new NclProvision();
load();
if (valiationController == null) {
valiationController = new ValidationController(TestBluetooth.this);
}
else {
valiationController.stop();
}
valiationController.startValidation(TestBluetooth.this, provision);
proviNymi = (Button) findViewById(R.id.provisionNymi);
proviNymi.setOnClickListener(this);
proviNymi.setEnabled(false);
validateNymi = (Button) findViewById(R.id.validateNymi);
validateNymi.setOnClickListener(this);
validateNymi.setEnabled(false);
disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
disconnectNymi.setOnClickListener(this);
disconnectNymi.setEnabled(false);
}else {
// Toast.makeText(getBaseContext(), "provision key is null!" , Toast.LENGTH_SHORT ).show();
checkBlue = (Button) findViewById(R.id.testBLuetooth);
checkBlue.setOnClickListener(this);
proviNymi = (Button) findViewById(R.id.provisionNymi);
proviNymi.setOnClickListener(this);
validateNymi = (Button) findViewById(R.id.validateNymi);
validateNymi.setOnClickListener(this);
validateNymi.setEnabled(false);
disconnectNymi = (Button) findViewById(R.id.disconnectNymi);
disconnectNymi.setOnClickListener(this);
disconnectNymi.setEnabled(false);
}
}
public void load(){
iduse = prefs.getString(Util.provID,null);
Toast.makeText(getBaseContext(), iduse , Toast.LENGTH_SHORT ).show();
keyuse = prefs.getString(Util.provKey,null);
if ((iduse!=null)||(keyuse!=null)) {
provision.id = new NclProvisionId();
provision.id.v = Base64.decode(iduse, Base64.DEFAULT);
provision.key = new NclProvisionKey();
provision.key.v = Base64.decode(keyuse, Base64.DEFAULT);
final String temp= keyuse.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "the temp provision key is " +temp , Toast.LENGTH_SHORT ).show();
}
});
}else {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getBaseContext(), "Provision key is null!" , Toast.LENGTH_SHORT ).show();
}
});
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == checkBlue.getId()){
// Toast.makeText(getBaseContext(), "Checking bluetooth is enabled or not!" , Toast.LENGTH_SHORT ).show();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
} else {
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enable :)
// Toast.makeText(getBaseContext(), " bluetooth is not enabled !" , Toast.LENGTH_SHORT ).show();
isBluetoothEnabled=false;
}else {
// Toast.makeText(getBaseContext(), " bluetooth is enabled !" , Toast.LENGTH_SHORT ).show();
isBluetoothEnabled=true;
Log.d("is nabled", "blue is enalble");
}
}
}
if (v.getId()==proviNymi.getId()){
connectNymi = true;
initializeNcl();
nymiHandle = -1;
if (provisionController == null) {
provisionController = new ProvisionController(TestBluetooth.this);
}
else {
provisionController.stop();
}
provisionController.startProvision(TestBluetooth.this);
}
if (v.getId()==validateNymi.getId()){
proviNymi.setEnabled(false);
if (valiationController == null) {
valiationController = new ValidationController(TestBluetooth.this);
}
else {
valiationController.stop();
}
valiationController.startValidation(TestBluetooth.this, provisionController.getProvision());
}
if (v.getId()==disconnectNymi.getId()){
prefs = getSharedPreferences(Util.SharedPrefKey, Context.MODE_PRIVATE);
prefs.edit().clear().commit();
if (nymiHandle >= 0) {
disconnectNymi.setEnabled(false);
validateNymi.setEnabled(true);
proviNymi.setEnabled(true);
Ncl.disconnect(nymiHandle);
nymiHandle = -1;
}
}
}
/**
* Initialize the NCL library
*/
protected void initializeNcl() {
if (!nclInitialized) {
if (connectNymi) {
initializeNclForNymiBand();
}
}
}
/**
* Initialize NCL library for connecting to a Nymi Band
* #return true if the library is initialized
*/
protected boolean initializeNclForNymiBand() {
if (!nclInitialized) {
NclCallback nclCallback = new MyNclCallback();
boolean result = Ncl.init(nclCallback, null, "NCLExample", NclMode.NCL_MODE_DEFAULT, this);
if (!result) { // failed to initialize NCL
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
return false;
}
nclInitialized = true;
// nclInitialized();
}
return true;
}
#Override
public void onStartProcess(ProvisionController controller) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi start provision ..",
Toast.LENGTH_LONG).show();
}
});
}
public void save(){
final String id = Base64.encodeToString(provision.id.v, Base64.DEFAULT);
final String key = Base64.encodeToString(provision.key.v, Base64.DEFAULT);
SharedPreferences pref = getSharedPreferences(Util.SharedPrefKey, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(Util.provID, id);
editor.putString(Util.provKey, key);
editor.apply();
editor.commit();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(TestBluetooth.this, id + key,
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onAgreement(final ProvisionController controller) {
nymiHandle = controller.getNymiHandle();
controller.accept();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Agree on pattern: " + Arrays.toString(controller.getLedPatterns()),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onProvisioned(final ProvisionController controller) {
nymiHandle = controller.getNymiHandle();
provision = controller.getProvision();
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
proviNymi.setEnabled(false);
validateNymi.setEnabled(true);
Toast.makeText(TestBluetooth.this, "Nymi provisioned: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
save();
}
});
}
#Override
public void onFailure(ProvisionController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi provision failed!",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDisconnected(ProvisionController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
validateNymi.setEnabled(provision != null);
disconnectNymi.setEnabled(false);
Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onStartProcess(ValidationController controller) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi start validation for: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFound(ValidationController controller) {
nymiHandle = controller.getNymiHandle();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi validation found Nymi on: " + Arrays.toString(provision.id.v),
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onValidated(ValidationController controller) {
nymiHandle = controller.getNymiHandle();
runOnUiThread(new Runnable() {
#Override
public void run() {
validateNymi.setEnabled(false);
disconnectNymi.setEnabled(true);
// HIDE THE SPINNER AFTER LOADING FEEDS
progressbar.setVisibility(View.GONE);
Toast.makeText(TestBluetooth.this, "Nymi validated!",
Toast.LENGTH_LONG).show();
prefs.edit().putBoolean(Util.isValidated, true).commit();
//move to new activity once nymi is validated
Intent intent = new Intent(TestBluetooth.this,CustomNotificationTest.class);
startActivity(intent);
}
});
}
#Override
public void onFailure(ValidationController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Nymi validated failed!",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDisconnected(ValidationController controller) {
controller.stop();
runOnUiThread(new Runnable() {
#Override
public void run() {
disconnectNymi.setEnabled(false);
validateNymi.setEnabled(true);
proviNymi.setEnabled(true);
Toast.makeText(TestBluetooth.this, "Nymi disconnected: " + provision,
Toast.LENGTH_LONG).show();
}
});
}
/**
* Callback for NclEventInit
*
*/
class MyNclCallback implements NclCallback {
#Override
public void call(NclEvent event, Object userData) {
Log.d(LOG_TAG, this.toString() + ": " + event.getClass().getName());
if (event instanceof NclEventInit) {
if (!((NclEventInit) event).success) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(TestBluetooth.this, "Failed to initialize NCL library!", Toast.LENGTH_LONG).show();
}
});
}
}
}
}
}
Edit: After I made the NYmiAssync as inner class, I am able to run the it async using the following :
new Thread() {
public void run() {
TestBluetooth.this.runOnUiThread(new Runnable(){
#Override
public void run() {
try {
NymiAsync task = new NymiAsync();
task.execute(1, 1, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}.start();
But, I have no idea, how to make it run for every 10 seconds.
The problem is in the asynctask:
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
TestBluetooth tb=new TestBluetooth();
tb.startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
Just make the class an inner class of TestBluetooth and then just call startValidatingNymi()
public class NymiAsync extends AsyncTask<Integer,Integer,Integer> {
#Override
protected Integer doInBackground(Integer... integers) {
try{
startValidatingNymi();
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
}
that is because the code below in TestBlutooth:
final Handler timedThread=new Handler();
but in doInBackground you create a instance of TestBluetooth, so you get the exception
i using call function to javascript to android . i using my android code below how to stop android mthread.i used for MyBackgroudMethod mThread but i want to stop this thread in sendCheckOutBackgroundKill();how to possible.please help me!!!
public class EmployeeManager extends CordovaActivity implements
LocationListener{
JavaScriptInterface jsInterface;
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean network_enabled = false;
String provider;
String lati = "";
String latlong = "";
String accuracy = "";
Location currentLocation;
LocationManager mLocationManager;
String devieID = "";
boolean backgroundtask = false;
String iSGps = "";
String mTime="";
String mEmployeeId="";
String mAttendanceId="";
MyBackgroudMethod mThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_employee_manager_main);
super.loadUrl("file:///android_asset/www/index.html");
//mThread = new MyBackgroudMethod();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/**/
jsInterface = new JavaScriptInterface(EmployeeManager.this);
appView.addJavascriptInterface(jsInterface, "JSInterface");
appView.getSettings().setJavaScriptEnabled(true);
appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
devieID = getUniquePsuedoID();
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if (provider != null && !provider.equals("")) {
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else if (network_enabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
// locationManager.requestLocationUpdates(provider, 1000, 0, this);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "Location can't be retrieved",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(), "No Provider Found",Toast.LENGTH_SHORT).show();
}
}
public static String getUniquePsuedoID()
{
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
String serial = null;
try
{
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
catch (Exception e)
{
serial = "serial"; // some value
}
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
public class JavaScriptInterface {
public Activity mContext;
public JavaScriptInterface(Activity c) {
this.mContext = c;
}
#JavascriptInterface
public void sendToAndroid(boolean deviceID) {
Log.v("log", "Sent TO android");
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passLatLong(\"" + lati + "\",\"" + latlong + "\",\"" + accuracy + "\");");
appView.setEnabled(false);
}
});
}
#JavascriptInterface
public void sendToDeviceId() {
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passDevieId(\"" + devieID + "\");");
}
});
}
#JavascriptInterface
public void sendCheckInBackground(String time, String employeeId, String attendanceId) {
mTime= time;
mEmployeeId = employeeId;
mAttendanceId = attendanceId;
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check In Background Native", 3000).show();
mThread = new MyBackgroudMethod();
mThread.setDaemon(true);
mThread.start();
}
});
}
public void sendCheckOutBackgroundKill() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check Out Background Native Kill", 3000).show();
mThread.interrupt();
}
});
}
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private class MyBackgroudMethod extends Thread {
#Override
public void run() {
while (true) {
checkInternetConnection();
try {
Thread.sleep(Integer.parseInt(mTime)*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new JSONTask().execute(mTime,mEmployeeId,mAttendanceId);
} else {
Log.v(TAG, "Internet Connection Not Present");
}
}
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() < 400) {
lati = Double.toString(location.getLatitude());
latlong = Double.toString(location.getLongitude());
accuracy = Double.toString(location.getAccuracy());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public class JSONTask extends AsyncTask<String, Void, String> {
public void onPreExecute() {
// progress.show();
}
protected String doInBackground(String... arg) {
// This value will be returned to your
// onPostExecute(result) method
String time1 = arg[0];
String employeeId2 = arg[1];
String attendenceId2 = arg[2];
String img_url = DBAdpter.onFieldCheckIn(employeeId2, attendenceId2, lati, latlong, accuracy);
return img_url;
}
protected void onPostExecute(String result) {
Toast.makeText(EmployeeManager.this, "JSON TASK", 4000).show();
}
}
}
The loop isn't exiting after the interruption. Put a "break;" inside the catch-clause. That's all.