1
I wanted to implement a transition between two Activitys, where the user, via a Progress Bar (I already implemented) and a textview where every 2 seconds, a new phrase appears to me, for example:
- Uploading information...
- Implementing the two definitions...
- To complete the registration...
I’m seeing some solutions, but they didn’t explain the exact way we should update Textview, for now I have the following code:
updatingThread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
//o meu problema em entender está a partir daqui, qual a forma mais correta de implementar o uptadate da textview?
textviewtoWait.setText(R.string.loadInfo);
textviewtoWait.setText(R.string.loadInfo2);
textviewtoWait.setText(R.string.loadInfo3);
}
});
updatingThread.start();
}
Before using Thread, it had a transition with a single Textview with a single string and a Progress Bar with the following code(in this the Textview is in XML)
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent myIntent = new Intent(actualContext, MainActivityProto.class);
myIntent.putExtra("email", novoUtilizador.getEmail_utilizador());
myIntent.putExtra("nome", novoUtilizador.getNome());
startActivity(myIntent); // termina com a actividade anterior, o que impede o utilizador de voltar atras.
finish();
}
}, 5000);
EDIT
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button txttoRegister, txttoLogin;
private EditText editTextUser, editTextPassword, addUser, addEmail, addLocal, addPassword, addTelm;
private TextView textviewtoTitle, txtviewtoMainPage, txtviewtoSecondMain, textviewtoWait;
private SharedPreferences sharedpreferences;
private Toolbar toolmenubar;
// private Thread updatingThread;
final Thread updatingThread = new Thread() {
@Override
public void run() {
try {
// Array com os valores que serão exibidos no textviewtoWait
final int[] txts = {R.string.loadInfo, R.string.loadInfo2, R.string.loadInfo3 };
while (!isInterrupted()) {
// Vamos iterar a lista para atualizar o textviewtoWait
for(final int txt : txts){
// aguarda 2 segundo...
Thread.sleep(2000);
// Runnable responsavel por atualizar a tela...
final Runnable updateUI = new Runnable() {
@Override
public void run() {
textviewtoWait.setText(txt);
}
};
runOnUiThread(updateUI);
}
// este irá sair do while, pois já realizamos as ações!
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txttoRegister = (Button) findViewById(R.id.buttontoRegister);
txttoLogin = (Button) findViewById(R.id.buttontoLogin);
textviewtoWait = (TextView) findViewById(R.id.txtviewtoWait);
changeTextFontFamily();
txttoRegister.setOnClickListener(this);
txttoLogin.setOnClickListener(this);
Typeface face = Typeface.createFromAsset(getAssets(), "Carnevalee Freakshow.ttf");
sharedpreferences = getApplicationContext().getSharedPreferences("Preferences", 0);
String login = sharedpreferences.getString("LOGIN", null);
if (login != null) {
MyDBHelper dbHelper = new MyDBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM Utilizador WHERE email_utilizador = '" + login + "'", null);
if (cursor != null && cursor.moveToFirst()) {
Intent myIntent = new Intent(this, MainActivityProto.class);
myIntent.putExtra("nome", cursor.getString(1));
myIntent.putExtra("email", cursor.getString(0));
startActivity(myIntent);
}
}
}
/**
* Algoritmo e metodo para fazer ligação aos cliques dos botões eixstentes na aplicação.
*
* @param v
*/
@Override
public void onClick(View v) {
if (v.getId() == R.id.buttontoRegister) {
alertDialogtoRegist();
}
if (v.getId() == R.id.buttontoLogin) {
final Context actualContext = this;
String userName = editTextUser.getText().toString();
String passWord = editTextPassword.getText().toString();
MyDBHelper dbHelper = new MyDBHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
if (!userName.matches("") && !passWord.matches("")) {
Cursor cursor = db.rawQuery("SELECT * FROM Utilizador WHERE email_utilizador = '" + userName + "'", null);
if (cursor != null && cursor.moveToFirst()) {
String pass_utilizador = cursor.getString(2);
/*Verifica a igualdade das passwords*/
if (pass_utilizador.equals(passWord)) {
final Utilizador novoUtilizador = criarUtilizador(cursor);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("LOGIN", novoUtilizador.getEmail_utilizador());
editor.commit();
setContentView(R.layout.transition_to_mainpage);
Intent myIntent = new Intent(actualContext, MainActivityProto.class);
myIntent.putExtra("email", novoUtilizador.getEmail_utilizador());
myIntent.putExtra("nome", novoUtilizador.getNome());
startActivity(myIntent); // termina com a actividade anterior, o que impede o utilizador de voltar atras.
finish();
} else {
apresenta_toast("A password que introduziu está errada!");
}
} else {
apresenta_toast("Utilizador inexistente na plataforma!");
}
} else {
apresenta_toast("Não é possível fazer login, senão introduzir nenhum dado!");
}
}
}
/**
* Método para colocar todos os botões e edittexts com o mesmo tipo de letra
*/
private void changeTextFontFamily() {
txttoRegister = (Button) findViewById(R.id.buttontoRegister);
editTextUser = (EditText) findViewById(R.id.ET_username);
editTextPassword = (EditText) findViewById(R.id.ET_password);
Typeface face = Typeface.createFromAsset(getAssets(), "Carnevalee Freakshow.ttf");
txttoLogin.setTypeface(face);
txttoRegister.setTypeface(face);
editTextUser.setTypeface(face);
editTextPassword.setTypeface(face);
}
/**
* Algoritmo para a criação de uma AlertDialog para permitir o registo de novo utilizador
* na plataforma.
*/
private void alertDialogtoRegist() {
final Context actualContext = this;
AlertDialog.Builder dialogtoRegist = new AlertDialog.Builder(this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
final View myView = inflater.inflate(R.layout.registerdialog, null);
textviewtoTitle = (TextView) myView.findViewById(R.id.txttoTitleRegisto);
addUser = (EditText) myView.findViewById(R.id.edittoAddUser);
addEmail = (EditText) myView.findViewById(R.id.edittoAddEmail);
addLocal = (EditText) myView.findViewById(R.id.edittoAddLocal);
addPassword = (EditText) myView.findViewById(R.id.edittoAddPass);
addTelm = (EditText) myView.findViewById(R.id.edittoTelm);
txtviewtoMainPage = (TextView) myView.findViewById(R.id.txttoTitleRegisto);
Typeface face = Typeface.createFromAsset(getAssets(), "Carnevalee Freakshow.ttf");
textviewtoTitle.setTypeface(face);
addUser.setTypeface(face);
addEmail.setTypeface(face);
addLocal.setTypeface(face);
addPassword.setTypeface(face);
addTelm.setTypeface(face);
dialogtoRegist.setView(myView);
dialogtoRegist.setPositiveButton(R.string.registobutton, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MyDBHelper dbHelper = new MyDBHelper(actualContext);
SQLiteDatabase db = dbHelper.getWritableDatabase();
try {
db.execSQL("INSERT INTO Utilizador(email_utilizador, nome, password, localizacao) VALUES ('" + addEmail.getText().toString() + "', '" + addUser.getText().toString() + "', '" + addPassword.getText().toString() + "', '" + addLocal.getText() + "')");
apresenta_toast("Utilizador criado com sucesso!");
} catch (Exception e) {
apresenta_toast("O utilizador que pretende criar já existe! Tente Novamente!");
}
}
});
dialogtoRegist.setNeutralButton("Cancelar", null);
AlertDialog alertDialog = dialogtoRegist.create();
alertDialog.show();
}
@Override
protected void onStart() {
super.onStart();
updatingThread.start();
}
/**
* Algoritmo para a criação de um novo utilizador na plataforma.
*
* @param cursor_utilizadores
* @return
*/
private Utilizador criarUtilizador(Cursor cursor_utilizadores) {
Utilizador newUtilizador = new Utilizador();
newUtilizador.setEmail_utilizador(cursor_utilizadores.getString(0));
newUtilizador.setNome(cursor_utilizadores.getString(1));
newUtilizador.setPassword(cursor_utilizadores.getString(2));
newUtilizador.setLocalizacao(cursor_utilizadores.getString(3));
return newUtilizador;
}
/**
* Algoritmo de impressão de toasts basicamente de impressão
*
* @param mensagem
*/
private void apresenta_toast(String mensagem) {
Toast toast = Toast.makeText(this, mensagem, Toast.LENGTH_SHORT);
toast.show();
}
}
Error when code setText()
is not commented:
java.lang.Nullpointerexception: Attempt to invoke virtual method 'void android.widget.Textview.setText(int)' on a null Object Reference
When commented, it shows the transition layout for not 1 second:
setContentView(R.layout.transition_to_mainpage);
And then it goes right into the Intent, which will redirect it to the next Activity.
I wanted it to show up the R.layout.Transition... with this update of Textview.
SOLUTION
private void mainThread() {
final Thread updatingThread = new Thread() {
@Override
public void run() {
try {
// Array com os valores que serão exibidos no textviewtoWait
final int[] txts = {R.string.loadInfo, R.string.loadInfo2, R.string.loadInfo3};
while (!isInterrupted()) {
// Vamos iterar a lista para atualizar o textviewtoWait
for (final int txt : txts) {
// aguarda 2 segundo...
Thread.sleep(2000);
// Runnable responsavel por atualizar a tela...
final Runnable updateUI = new Runnable() {
@Override
public void run() {
textviewtoWait.setText(txt);
// TextView.class.cast(getLayoutInflater().inflate(R.layout.transition_to_mainpage, null).findViewById(R.id.txtviewtoWait)).setText(txt);
}
};
runOnUiThread(updateUI);
}
// este irá sair do while, pois já realizamos as ações!
break;
}
irParaProximaActivity();
} catch (InterruptedException e) {
// e.printStackTrace();
}
}
};
updatingThread.start();
}
private void irParaProximaActivity() {
actualContext = getApplicationContext();
Intent myIntent = new Intent(actualContext, MainActivityProto.class);
myIntent.putExtra("email", novoUtilizador.getEmail_utilizador());
myIntent.putExtra("nome", novoUtilizador.getNome());
startActivity(myIntent); // termina com a actividade anterior, o que impede o utilizador de voltar atras.
finish();
}
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
final View myView = inflater.inflate(R.layout.transition_to_mainpage, null);
textviewtoWait = (TextView) myView.findViewById(R.id.txtviewtoWait);
setContentView(myView);
mainThread();
Thanks for the answer! Just one question I leave this code in the onCreate()? method or I put it inside the Handler with 5 seconds?
– ZelDias
You can put inside the onStart()
– Thiago Luiz Domacoski
When I run the program in both onStart() and onCreate(), as well as inside Handler, I do not update Textview because it gives a "nullpointerexeption" when I run setText()...
– ZelDias
I put the whole code in, makes it easier for you to understand!
– Thiago Luiz Domacoski
I’m going to test, but just one note, I want this update of Textview and as I said in the question, to be a transition between two Fragments. To achieve this, I invoke the onStart() method in the onClick method()?
– ZelDias
So in the Onclik you call the new Fragment, and this in the onStart, that is, when it is loaded, it will load the Textview
– Thiago Luiz Domacoski
I’ve edited my answer, based on your instructions, please check the code I put in the edition to verify otherwise I’m making a mistake. Textview is in comment, but it still doesn’t work, Nullpointerexception.
– ZelDias
Even commented gives the Nullpointer?? Can you acidify the log with the error? It gets easier!
– Thiago Luiz Domacoski
can already see the issue, I also added some information about what happens and what I want to happen.
– ZelDias
Let’s go continue this discussion in chat.
– Thiago Luiz Domacoski
Thanks Thiago! After a lot of chat talk, we managed to solve the problem. I will put the solution in my question as Edit!
– ZelDias