Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7844175
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T16:47:44+00:00 2026-06-02T16:47:44+00:00

I want to interrupt a thread1 from another thread2 but when I try make

  • 0

I want to interrupt a thread1 from another thread2 but when I try make the thread1.interrupt(); call I get a null pointer error.

I’m making an android app, I’m on an android login page and when I login I create and start a thread called sessionTimer (which does a session countdown say 2min). What I want is that when I press logout in a different activity that I go to the login page and my sessionTimer thread should be interrupted so that I can start a new login session with max time.

package com.AndroidApp.Login;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.AndroidApp.R;
import com.AndroidApp.domain.Utente;
import com.AndroidApp.pagine.MenuPagina;


public class LoginActivity extends Activity {

    final String TAG = "LogIN";
    ArrayList<HashMap<String, String>> mylist;

    private Button bLogin, bExit;
    private EditText utente, passwd;
    private MediaPlayer mpButtonClick = null;
    private SharedPreferences mPreferences; 
    public volatile Thread sessionTimer;
    public long tId = -1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);

        SharedPreferences.Editor editor = mPreferences.edit();
        editor.clear();
        editor.commit();

        String nome = mPreferences.getString("nome", "Nessuno");
        setTitle("Sessione di : " + nome);
        Log.w("TotThreads", Integer.toString(Thread.activeCount()));
        /*
        final SessionTimer st = new SessionTimer();
        */
        if(MenuPagina.reset){

            Log.w("sessionTimer ID", Long.toString(sessionTimer.getId()));
            if (sessionTimer == null)
                Log.w("sessionTimer", "sessionTimer is NULL");
            sessionTimer.interrupt();
            System.out.println("end current session");

            //st.stopRequest();
        }

        if (!checkLoginInfo()) {

            mpButtonClick = MediaPlayer.create(this, R.raw.button);

            bLogin = (Button)findViewById(R.id.bLogin);
            bLogin.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {

                    mpButtonClick.start();

                    Log.v(TAG, "Trying to Login");
                    utente = (EditText)findViewById(R.id.etUtente);
                    passwd = (EditText)findViewById(R.id.etPassword);

                    String username = utente.getText().toString();
                    username = ("ccce@eex.it");
                    String password = md5(passwd.getText().toString());
                    password = md5("12345");

                    XMLFunctionsLogin.getInstance().setNewURL("u=" + username + "&p=" + password);
                    String xml = XMLFunctionsLogin.getXML();
                    Document doc = XMLFunctionsLogin.xmlFromString(xml); 
                    int status = XMLFunctionsLogin.errStatus(doc); 

                    Log.v("status", Integer.toString(status));
                    if ((status == 0)) {
                        NodeList nodes = doc.getElementsByTagName("login"); 
                        Element e = (Element) nodes.item(0);
                        Utente utente = new Utente();
                        utente.setIdUtente(XMLFunctionsLogin.getValue(e, "idUtente"));
                        utente.setNome(XMLFunctionsLogin.getValue(e, "nome"));
                        utente.setCognome(XMLFunctionsLogin.getValue(e, "cognome"));
                        Log.v("utente", utente.getCognome().toString());

                        List<NameValuePair> nvps = new ArrayList<NameValuePair>(2);
                        nvps.add(new BasicNameValuePair("utente", username));
                        nvps.add(new BasicNameValuePair("password", password));
                        Log.v(TAG, nvps.get(0).toString());
                        Log.v(TAG, nvps.get(1).toString());

                        // Store the username and password in SharedPreferences after the successful login
                        SharedPreferences.Editor editor = mPreferences.edit();
                        editor.putString("userName", username);
                        editor.putString("password", password);
                        editor.putString("idUtente", utente.getIdUtente());
                        editor.putString("nome", utente.getNome());
                        editor.putString("cognome", utente.getCognome());
                        editor.commit();


                        Log.v(TAG, "timer");
                        Log.v("RESET", Boolean.toString(MenuPagina.reset));

                        /*
                        Thread t = new Thread(st);
                        t.start();
                        */




                        sessionTimer = new Thread() {
                            @Override
                            public void run() {
                                long tId = Thread.currentThread().getId();
                                Log.w("TTthread Id", Long.toString(tId));
                                for (int i = 30; i >= 0; i -= 1) {
                                    if ((i == 0) || (MenuPagina.reset)) {
                                        System.out.print("timer finito");
                                        Log.i("Timer", "timer finito");
                                        LoginActivity.this.runOnUiThread(new Runnable() { 
                                            public void run() { 
                                                Toast.makeText(LoginActivity.this, "ti si è scaduta la sessione", Toast.LENGTH_LONG).show(); 
                                            }
                                        });
                                        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        startActivity(intent);
                                        //System.exit(0);
                                    } try {
                                        Thread.sleep(1000);
                                        Log.i("Timer", Integer.toString(i));
                                    } catch (InterruptedException e) {
                                        Log.i("Catch", "Catchhhhhhhhhhhh");
                                        e.printStackTrace();
                                        Thread.currentThread().interrupt();
                                        return;

                                    }
                                }
                            }

                        };
                        sessionTimer.start();


                        Log.v(TAG, "Successo2");

                        Toast.makeText(LoginActivity.this, "LogIn con successo", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getApplicationContext()/*LoginActivity.this*/, MenuPagina.class);
                        startActivity(intent);

                    } else {
                        final String errorMessage = XMLFunctionsLogin.errStatusDesc(doc);
                        Log.v("fallimento", errorMessage);
                        LoginActivity.this.runOnUiThread(new Runnable() { 
                            public void run() { 
                                Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_LONG).show(); 
                            }
                        });

                        Intent intent = getIntent();
                        finish();
                        startActivity(intent);
                    }
                }

            });

            bExit = (Button)findViewById(R.id.bExit);
            bExit.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    mpButtonClick.start();
                    finish();
                }
            });
        }
    }

    //Checking whether the username and password has stored already or not
    private final boolean checkLoginInfo() {
          boolean username_set = mPreferences.contains("UserName");
          boolean password_set = mPreferences.contains("PassWord"); 
          if ( username_set || password_set ) {
                return true;
          } 
          return false;
    }

    //md5 for crypting and hash
    private static String md5(String data) {
        byte[] bdata = new byte[data.length()];
        int i;
        byte[] hash;

        for (i = 0; i < data.length(); i++)
            bdata[i] = (byte) (data.charAt(i) & 0xff);

        try {
            MessageDigest md5er = MessageDigest.getInstance("MD5");
            hash = md5er.digest(bdata);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }

        StringBuffer r = new StringBuffer(32);
        for (i = 0; i < hash.length; i++) {
            String x = Integer.toHexString(hash[i] & 0xff);
            if (x.length() < 2)
                r.append("0");
            r.append(x);
        }
        return r.toString();
    }
}

So what happens is when I logout and I come back to the login page and MenuPagina.reset = true I get an error saying that sessionTimer is null. Why?

I’ve tried also using a seperate class for the thread but I get the same null pointer error.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T16:47:45+00:00Added an answer on June 2, 2026 at 4:47 pm

    onCreate runs when your Activity is being created or re-created, either way it’s a new object, so any local variables have to be initialized again, in your case sessionTimer would be null until the new Thread() {} call.

    If you need to persist a reference to your thread, use more global object than your Activity is – Application, that’s a base class for maintaining global application state. You can always access it by calling Context.getApplicationContext(). Anyway, read the docs.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

How can I get NSURLConnection to call it's delegate methods from a different thread
I want to interrupt a thread after a fixed amount of time. Someone else
I want to interrupt some specific grails domain class events(read,write,delete,update).Is there any hibernate eventlistner
I want to use the before action to optionally interrupt the processing if it
I want to intercept long press on UITextview, but don't want to disable the
Want the function to sort the table by HP but if duplicate HPs then
I want to implement a simple class for logging from multiple threads. The idea
When I got an incoming call then I have to immediately interrupt my long
I just want to intercept raw data (hex)--headers and all--sent to a port, and
I'm starting a Stack Exchange site and I want to be able to intercept

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.