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.
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.
Related
So I set up an event listener, but after checking several times, I see that it doesn't even trigger in the first place.
package com.example.globe_all;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginScreen extends AppCompatActivity {
private Button signup, login;
private EditText user_email, password;
private TextView errortext, forgotpassword, usernameText, passwordText, appearText;
private String checkPass;
private int count = 0;
private ImageView globe;
private FrameLayout frame;
private Boolean buttonFlag = false;
private String accessKey = "";
private FirebaseAuth mAuth;
private FirebaseDatabase database;
private DatabaseReference mDatabase;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private SharedPreferences gamePrefs;
private SharedPreferences.Editor gamePrefsEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
signup = findViewById(R.id.signup);
login = findViewById(R.id.loginButton);
user_email = findViewById(R.id.user_email);
password = findViewById(R.id.password);
errortext = findViewById(R.id.loginerror);
usernameText = findViewById(R.id.usernametext);
passwordText = findViewById(R.id.passwordtext);
forgotpassword = findViewById(R.id.forgotpassword);
globe = findViewById(R.id.globe);
frame = findViewById(R.id.frame);
appearText = findViewById(R.id.appearText);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
gamePrefs = getSharedPreferences("gamePrefs", MODE_PRIVATE);
gamePrefsEditor = gamePrefs.edit();
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance("https://globall-326315-default-rtdb.europe-west1.firebasedatabase.app/");
mDatabase = database.getReference("user");
globe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (giveBool("first") && giveBool("second")) {
Log.d("counter", " " + count);
switch (count) {
case 0:
signup.setVisibility(View.GONE);
case 1:
login.setVisibility(View.GONE);
case 2:
usernameText.setVisibility(View.GONE);
case 3:
password.setVisibility(View.GONE);
case 4:
user_email.setVisibility(View.GONE);
case 5:
passwordText.setVisibility(View.GONE);
case 6:
forgotpassword.setVisibility(View.GONE);
case 7:
ViewGroup.LayoutParams params = frame.getLayoutParams();
params.height = 300;
params.width = 300;
frame.setLayoutParams(params);
appearText.setVisibility(View.VISIBLE);
gamePrefsEditor.clear();
gamePrefsEditor.commit();
case 8:
Intent intent = new Intent(LoginScreen.this, MainActivity.class);
finish();
startActivity(intent);
}
count++;
}
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email_user = user_email.getText().toString();
String pass = password.getText().toString();
accessKey = encrypt(email_user) + "&&&" + encrypt(pass);
Log.d("useruser", " " + mDatabase.child(accessKey));
buttonFlag = true;
}
});
mDatabase.child(accessKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User u = snapshot.getValue(User.class);
checkPass = u.getPassword();
Log.d("checkPass", " " + checkPass);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("snapshot", "Error!");
throw error.toException();
}
});
if (buttonFlag && checkPass != null) {
checkPass = decrypt(checkPass);
String email_user = user_email.getText().toString();
String pass = password.getText().toString();
Log.d("decrypt", " " + checkPass);
if (pass.equals(checkPass)) {
errortext.setVisibility(View.GONE);
String email = mDatabase.child(accessKey).child("email").toString();
mAuth.signInWithEmailAndPassword(email, pass).addOnCompleteListener(LoginScreen.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
loginPrefsEditor.putString("username", encrypt(email_user));
loginPrefsEditor.putBoolean("loggedIn", true);
loginPrefsEditor.commit();
Toast.makeText(LoginScreen.this, "Successfully logged in!", Toast.LENGTH_LONG).show();
Intent home = new Intent(LoginScreen.this, MainActivity.class);
finish();
startActivity(home);
}
});
} else {
errortext.setVisibility(View.VISIBLE);
}
} else {
errortext.setVisibility(View.VISIBLE);
}
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent signup = new Intent(LoginScreen.this, SignupScreen.class);
startActivity(signup);
finish();
}
});
}
private String decrypt (String toDec) {
String sh = "abcdefghijklmnopqrstuvwxyz";
String ab = "xytaipckejzsrlfnmhvqgubowd";
String numshuf = "0123456789";
String num = "3298561740";
StringBuilder enc = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(toDec);
while (it.current() != CharacterIterator.DONE)
{
char c = it.current();
if(!Character.isDigit(it.current())) {
for (int i = 0; i < ab.length(); i++) {
if (!(ab.charAt(i) == Character.toLowerCase(c)))
continue;
if (Character.isLowerCase(it.current()))
enc.append(sh.charAt(i));
else
enc.append(Character.toUpperCase(sh.charAt(i)));
break;
}
} else if (Character.isDigit(it.current())) {
for (int i = 0; i < num.length(); i++) {
if (!(num.charAt(i) == c))
continue;
enc.append(numshuf.charAt(i));
break;
}
} else if (!Character.isLetterOrDigit(it.current()))
enc.append(it.current());
it.next();
}
return enc.toString();
}
public String encrypt (String toEnc) {
String ab = "abcdefghijklmnopqrstuvwxyz";
String sh = "xytaipckejzsrlfnmhvqgubowd";
String num = "0123456789";
String numshuf = "3298561740";
StringBuilder enc = new StringBuilder();
CharacterIterator it = new StringCharacterIterator(toEnc);
while (it.current() != CharacterIterator.DONE)
{
char c = it.current();
if(!Character.isDigit(it.current())) {
for (int i = 0; i < ab.length(); i++) {
if (!(ab.charAt(i) == Character.toLowerCase(c)))
continue;
if (Character.isLowerCase(it.current()))
enc.append(sh.charAt(i));
else
enc.append(Character.toUpperCase(sh.charAt(i)));
break;
}
} else if (Character.isDigit(it.current())) {
for (int i = 0; i < num.length(); i++) {
if (!(num.charAt(i) == c))
continue;
enc.append(numshuf.charAt(i));
break;
}
} else if (!Character.isLetterOrDigit(it.current()))
enc.append(it.current());
it.next();
}
return enc.toString();
}
public boolean giveBool(String s) {
return gamePrefs.getBoolean(s, false);
}
}
I've updated the code, and pasted in the entirety of the code.
I've taken the addValueEventListener() out of my Onclick() method, and now I see that onDataChange does indeed trigger, but now I seem to face a problem of an Asynchronious nature, as I am still not getting a null out of my data. I am sure that the data I am trying to retrieve exists, so that's not the problem
So I figured out what was happening - seems that when I put my listener in the onClick() it wasn't triggering at all, so I took it out of there.
Then, it was always returning null so I figured it's about the async, and I went on checking how to fix that problem.
I followed the instructions and created a callback interface that was being used to retrieve the data from the database.
I called the interface in a function:
public void readData (MyCallBack myCallBack) {
mDatabase.child(accessKey).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String value = snapshot.getValue(User.class).getPassword();
myCallBack.onCallback(value);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
And the interface:
public interface MyCallBack {
void onCallback(String value);
}
I have this code in android studio for an app, I am trying to read from a file for the information of the login but anything after BufferedReader is not executing.
both the registration and login page open, the first page in the app i have sa login button and a registration button, when i click on the login button nothng happen, not even checking if the user exist or not
I tried many ways for reading and writing to a file but I couldn't figure out the error
it is not reading anything and not writing any thing, it simply does nothing.
this is the login page
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class LoginActivity extends AppCompatActivity {
private inputValidation InputValidation;
private TextInputLayout IDLayout;
private TextInputLayout PASSWORDlayout;
private TextInputEditText LogID;
private TextInputEditText PASS;
Button SI;
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
PASS = findViewById(R.id.password);
LogID = findViewById(R.id.idd);
IDLayout = findViewById(R.id.IDLayout);
PASSWORDlayout = findViewById(R.id.PasswordLayout);
TV = findViewById(R.id.tv);
SI = findViewById(R.id.signin);
SI.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
TV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Navigate to RegisterActivity
Toast.makeText(LoginActivity.this, "we are in tv.", Toast.LENGTH_LONG).show();
Intent intentRegister = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intentRegister);
}
});
InputValidation = new inputValidation(LoginActivity.this);
}
private void login() {
if (!InputValidation.isInputEditTextFilled(LogID, IDLayout, "ID not filled ")) return;
if (!InputValidation.isInputEditTextFilled(PASS, PASSWORDlayout, "Password not filled"))
return;
TextView FileContentTextView = findViewById(R.id.tv_file_content);
try {
File f = new File ("User.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
if (reader.ready()) {
FileContentTextView.setText("No User registered");
return;
} else {
Toast.makeText(LoginActivity.this, "else", Toast.LENGTH_LONG).show();
boolean found = false;
String role = null;
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(LoginActivity.this, "while", Toast.LENGTH_LONG).show();
StringTokenizer user = new StringTokenizer(line);
String name = user.nextToken();
String Id = user.nextToken();
String dob = user.nextToken();
String pas = user.nextToken();
String Campus = user.nextToken();
String gender = user.nextToken();
role = user.nextToken();
if (LogID.equals(Id)) {
Toast.makeText(LoginActivity.this, "id is good", Toast.LENGTH_LONG).show();
if (PASS.equals(pas)) {
Toast.makeText(LoginActivity.this, "pass good", Toast.LENGTH_LONG).show();
found = true;
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "break.", Toast.LENGTH_LONG).show();
break;
}
}
if (found) {
Toast.makeText(LoginActivity.this, "found", Toast.LENGTH_LONG).show();
if (role.equals("Security")) {
Intent accountsIntent = new Intent(LoginActivity.this, SecurityPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
} else {
Intent accountsIntent = new Intent(LoginActivity.this, StudentPage.class);
accountsIntent.putExtra("ID", LogID.getText().toString().trim());
}
} else
reader.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
this is the registration code, it has the same problem where anything after the BufferedReader is not executing.
package com.example.admin.projectfinal;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.admin.projectfinal.val.inputValidation;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutId;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutDate;
TextInputEditText Name;
TextInputEditText id;
TextInputEditText Password;
TextInputEditText DOB;
Spinner campus;
Spinner Role;
Spinner Gender;
Button btn;
Button Cancel;
private inputValidation InputValidation;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = findViewById(R.id.name);
id = findViewById(R.id.ID);
Password = findViewById(R.id.password);
DOB = findViewById(R.id.dob);
btn = findViewById(R.id.next);
Cancel = findViewById(R.id.cancel);
campus = findViewById(R.id.campus);
Gender = findViewById(R.id.gender);
Role = findViewById(R.id.role);
textInputLayoutName = findViewById(R.id.NameLayout);
textInputLayoutId = findViewById(R.id.IdLayout);
textInputLayoutPassword = findViewById(R.id.PasswordLayout);
textInputLayoutDate = findViewById(R.id.DOBLayout);
//list for campus
String[] CampusList = new String[]{"MainCampus", "SasAlNakhlCampus", "MasdarCampus"};
ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, CampusList);
campus.setAdapter(adapter1);
//list for gender
String[] gen = new String[]{"Male", "Female"};
ArrayAdapter<String> genAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, gen);
Gender.setAdapter(genAdapter);
//list for role
String[] rolee = new String[]{"Student", "Security"};
ArrayAdapter<String> roleAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, rolee);
Role.setAdapter(roleAdapter);
// Buttons validation
btn.setOnClickListener(this);
Cancel.setOnClickListener(this);
InputValidation = new inputValidation(RegisterActivity.this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.next:
try {
validate();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
break;
case R.id.cancel:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(this, LoginActivity.class);
startActivity(intentRegister);
break;
}
}
private void validate() throws IOException {
boolean filled = true;
if (!InputValidation.isInputEditTextFilled(Name, textInputLayoutName, "Fill Name")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(id, textInputLayoutId, "Fill ID")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(DOB, textInputLayoutDate, "Fill Date")) {
filled = false;
return;
}
if (!InputValidation.isInputEditTextFilled(Password, textInputLayoutPassword, "Invalid Password")) {
filled = false;
return;
}
if (filled){
//if (!UserInfo.exists()) UserInfo.createNewFile();
String line;
boolean found = false;
BufferedReader reader= new BufferedReader(new FileReader("User.txt"));
Toast.makeText(getBaseContext(), "ready", Toast.LENGTH_LONG).show();
while ((line = reader.readLine()) != null) {
Toast.makeText(getBaseContext(), "while", Toast.LENGTH_LONG).show();
String[] user = line.split(" ");
String name = user[0];
String Id = user[1];
String dob = user[2];
String password = user[3];
String Campus = user[4];
String gender = user[5];
String role = user[6];
if (id.equals(Id)) {
found = true;
Toast.makeText(getBaseContext(), "User Exist", Toast.LENGTH_LONG).show();
break;
}
if (!found) {
// Adds a line to the file
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("User.txt")));
writer.append(Name + " " + id + " " + DOB + " " + Password + " "
+ campus.getSelectedItem() + " " + Gender.getSelectedItem() + " " + Role.getSelectedItem() + "/n" );
}
}
reader.close();
}
}
}
Input validation class I used in the code:
package com.example.admin.projectfinal.val;
import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
public class inputValidation {
private static Context context;
/**
* constructor
*
* #param context
*/
public inputValidation(Context context) {
this.context = context;
}
/**
* method to check InputEditText filled .
*
* #param textInputEditText
* #param textInputLayout
* #param message
* #return
*/
public static boolean isInputEditTextFilled(TextInputEditText textInputEditText, TextInputLayout textInputLayout, String message) {
String value = textInputEditText.getText().toString().trim();
if (value.isEmpty()) {
textInputLayout.setError(message);
hideKeyboardFrom(textInputEditText);
return false;
} else {
textInputLayout.setErrorEnabled(false);
}
return true;
}
/**
* method to Hide keyboard
*
* #param view
*/
private static void hideKeyboardFrom(View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
I have been developing web pages with php and MySQL for years but am new to developing for Android projects. I have searched and read through all previous questions that I found concerning the subject but have not found the answer that works for my project. Currently when I run the app, all I get is errors and no download. I am posting the complete code for my Main Activity and ask if anyone can explain what I have done wrong. The data in sharedpreferences for UserId is a integer and the Date/session is a number string and the Email/eaddress is a string
package com.example.logintest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
String IgidPreference = "IgidPreference";
String UserId = "userId";
String Date = "session";
//OR SHOULD THE DECLEARATION BE??
//public static final String UserId = "userId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new VerifyLogin().execute();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Login.class);
startActivity(intent);
}
});
}
public class VerifyLogin extends AsyncTask<String, Void, String> {
Context ctx;
SharedPreferences pref;
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
String eaddress = arg0[0];
String today = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?Email=" + URLEncoder.encode(eaddress, "UTF-8");
data += "&Date=" + URLEncoder.encode(today, "UTF-8");
link = "http://domain.com/verifylogin.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String userId = jsonObj.getString("user_id");
String session = jsonObj.getString("session");
String error_type = jsonObj.getString("error");
String error_msg = jsonObj.getString("error_msg");
if (error_type.equals("FALSE")) {
pref = context.getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(UserId, userId);
editor.putString(Date, session);
editor.apply();
Intent intent = new Intent(MainActivity.this, Account.class);
startActivity(intent);
} else if (error_type.equals("TRUE")) {
Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, error_msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I know it has been some time since posting on the topic but I had to replace the computer, along with Android Studio and make all new project.
Here is what I have found to handle the original issue. I am putting comments inside the code to help anyone else who wants to use code for their next project.
public class LoginActivity extends Activity { //Standard Activity code
Button BtnLaunchSigninActivity; //Button to click
private EditText etLoginUserName, etLoginPassword; // data to submit
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etLoginUserName = (EditText) findViewById(R.id.etLoginUserName);
etLoginPassword = (EditText) findViewById(R.id.etLoginPassword);
BtnLaunchSigninActivity = (Button) findViewById(R.id.btnLoginSignin);
BtnLaunchSigninActivity.setOnClickListener(onClickListener);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnLoginSignin) {
signin(v);
}
}
};
public void signin(View v) {
String userName = etLoginUserName.getText().toString();
String passWord = etLoginPassword.getText().toString();
Toast.makeText(this, "Signing In...", Toast.LENGTH_SHORT).show();
new SignIn(this).execute(userName, passWord); // Send data to AsyncTask
}
private class SignIn extends AsyncTask<String, Void, String> {
private Context context; // context is for the SignIn()
SignIn(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String userName = arg0[0];
String passWord = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(userName, "UTF-8");
data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
link = "url/login.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result; // My php returns jsonobjects
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result; //turn object into string
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String status = jsonObj.getString("status");
String userid = jsonObj.getString("uid");
String hash = jsonObj.getString("security");
Log.d("tag", jsonObj.toString(4));
if (status.equals("Good")) {
Toast.makeText(context, "Sign In successful.", Toast.LENGTH_SHORT).show();
//YOU HAVE TO USE JSONSTR TO GET USERID AND SECHASH FOR UPDATING SHARED PREFERENCES
//DUE TO ANY POSSIBLE DELAYS OF PROCESSING doInBackground() SEND JSON TO NEXT ACTIVITY TO SET PREFERENCES
//ADD THE STRING TO THE INTENT BELOW, THEN PROCESS THE DATA FOR SETTING SHAREDPREFERENCES IN THE NEXT ACTIVITY
Log.d("UserID",userid);
Log.d("SecHash", hash);
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Bundle extras = new Bundle();
extras.putString("USERID",jsonObj.getString("uid"));
extras.putString("SECHASH",jsonObj.getString("security"));
extras.putString("USERID","userid");
extras.putString("SECHASH","hash");
intent.putExtras(extras);
startActivity(intent);
} else if (status.equals("Wrong")) {
Toast.makeText(context, "Username/Password is incorrect, could not be verified. Sign In failed.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
}
In next activity get the extras from the intent and add them to the sharedPreferences. That is all there is to it.
Thanks to everyone for their assistance before. I hope this will help others who find themselves with the same problem in the future.
In doInBackground() you define a locale variable but use a members variable
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
if ((pref.contains(UserId)) && (pref.contains(Date))) {
}
Since you only assign pref in onPostExecute() you'll get NullPointerExceptions everytime. Also ctx is null and context is not even declared. So make sure you have pref defined as early as possible.
public class VerifyLogin extends AsyncTask<String, Void, String> {
private final SharedPreferences pref;
VerifyLogin() {
pref = getSharedPreferences(IgidPreference, Context.MODE_PRIVATE);
}
[...]
}
But in the end you should not implement it like this at all. You'll leak your activity here!
I am trying to load a popup window that contains an edittext and a datepicker.
I have included my code below.
Basically the initial window is closed as expected, but my pop up doesn't appear?
I have checked the xml call and the id is correct, no errors and for some reason my logcat in eclipse has stopped working but thats a different issue!
Hopefully someone can tell me what I have missed and / or doing wrong? I am new to android programming so please ignore my ignorance if it is something simple!
package com.zelphe.zelpheapp;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.zelphe.zelpheapp.library.DatabaseHandler;
import com.zelphe.zelpheapp.library.UserFunctions;
public class LoginActivity extends Activity
{
Button btnLogin;
Button Btnregister;
Button passreset;
EditText inputEmail, inputName, inputPassword;
DatePicker inputDOB;
private TextView loginErrorMsg;
/**
* Called when the activity is first created.
*/
private static String KEY_SUCCESS = "success";
private static String KEY_REGISTER = "doRegister";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
Button btnReg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_test);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.loginbtn);
//loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);
/**
* Login button click event
* A Toast is set to alert when the Email and Password field is empty
**/
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if ( ( !inputEmail.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) )
{
NetAsync(view);
}
else if ( ( !inputEmail.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Password field empty", Toast.LENGTH_SHORT).show();
}
else if ( ( !inputPassword.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Email field empty", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),
"Email and Password field are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working.
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(LoginActivity.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(false);
nDialog.show();
}
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
loginErrorMsg.setText("Error in Network Connection");
}
}
}
/**
* Async Task to get and send data to My Sql database through JSON respone.
**/
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String email,password;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
pDialog.setMessage("Loading User Space");
pDialog.setTitle("Getting Data");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Clear all previous data in SQlite database.
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
*If JSON array details are stored in SQlite it launches the User Panel.
**/
Intent upanel = new Intent(getApplicationContext(), MainActivity.class);
upanel.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(upanel);
/**
* Close Login Screen
**/
finish();
}else if(Integer.parseInt(res) == 2)
{
pDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Incorrect Password!", Toast.LENGTH_SHORT).show();
}
else
{
pDialog.dismiss();
initiatePopupWindow();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private PopupWindow pwindo;
private void initiatePopupWindow()
{
try
{
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_register,(ViewGroup)
findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 350, 350, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
btnReg = (Button) layout.findViewById(R.id.btnReg);
btnReg.setOnClickListener((android.view.View.OnClickListener) reguser);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private OnClickListener reguser = new OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
inputName = (EditText) findViewById(R.id.name);
inputDOB = (DatePicker) findViewById(R.id.dob);
if ( ( !inputName.getText().toString().equals("")) &&
( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) > 15) )
{
//register user
}
else if ( ( inputName.getText().toString().equals("")) )
{
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT).show();
}
else if (( getAge(inputDOB.getDayOfMonth(), inputDOB.getMonth(), inputDOB.getYear()) < 16) )
{
Toast.makeText(getApplicationContext(),
"You must be at least 16 to use this app", Toast.LENGTH_SHORT).show();
}
}
};
}
public int getAge (int _year, int _month, int _day) {
GregorianCalendar cal = new GregorianCalendar();
int y, m, d, a;
y = cal.get(Calendar.YEAR);
m = cal.get(Calendar.MONTH);
d = cal.get(Calendar.DAY_OF_MONTH);
cal.set(_year, _month, _day);
a = y - cal.get(Calendar.YEAR);
if ((m < cal.get(Calendar.MONTH))
|| ((m == cal.get(Calendar.MONTH)) && (d < cal
.get(Calendar.DAY_OF_MONTH)))) {
--a;
}
if(a < 0)
throw new IllegalArgumentException("Age < 0");
return a;
}
public void NetAsync(View view){
new NetCheck().execute();
}
}
Embarassingly enough, there is no issue with the popup, I had an error further up in my code, doh!
I'm trying to make a Twitter app which includes posting and retrieving tweets from the user's timeline and setting it in a list view which also updates when someone tweets.
I also wish to allow the user to upload photos to Twitter.
Here's my code:
package com.example.listtweetdemo;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONObject;
import twitter4j.json.DataObjectFactory;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
private Button twitt;
private Button read;
private Button login;
private Button logout;
private EditText edt;
private boolean man = true;
private TextView textName;
private ListView list;
List<Status> statuses = new ArrayList<Status>();
static final String consumerKey = "RVVVPnAUa8e1XXXXXXXXX";
static final String consumerSecretKey = "eCh0Bb12n9oDmcomBdfisKZIfJmChC2XXXXXXXXXXXX";
static final String prefName = "twitter_oauth";
static final String prefKeyOauthToken = "oauth_token";
static final String prefKeyOauthSecret = "oauth_token_secret";
static final String prefKeyTwitterLogin = "isTwitterLogedIn";
static final String twitterCallbackUrl = "oauth://t4jsample";
static final String urlTwitterOauth = "auth_url";
static final String urlTwitterVerify = "oauth_verifier";
static final String urlTwitterToken = "oauth_token";
static SharedPreferences pref;
private static Twitter twitter;
private static RequestToken reqToken;
private connectionDetector cd;
AlertDailogManager alert = new AlertDailogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpIds();
cd = new connectionDetector(getApplicationContext());
if(!cd.isConnectivityToInternet())
{
alert.showAlert(MainActivity.this, "Internet Connection Error", "Please Connect to working Internet connection", false);
return;
}
if(consumerKey.trim().length() == 0 || consumerSecretKey.trim().length() == 0)
{
alert.showAlert(MainActivity.this, "Twitter Oauth Token", "Please set your Twitter oauth token first!", false);
return;
}
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginToTwitter();
}
});
logout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
logoutFromTwitter();
}
});
read.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Paging paging = new Paging(200); // MAX 200 IN ONE CALL. SET YOUR OWN NUMBER <= 200
try {
statuses = twitter.getHomeTimeline();
} catch (TwitterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String strInitialDataSet = DataObjectFactory.getRawJSON(statuses);
JSONArray JATweets = new JSONArray(strInitialDataSet);
for (int i = 0; i < JATweets.length(); i++) {
JSONObject JOTweets = JATweets.getJSONObject(i);
Log.e("TWEETS", JOTweets.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
/*try {
ResponseList<Status> statii = twitter.getHomeTimeline();
statusListAdapter adapter = new statusListAdapter(getApplicationContext(), statii);
setListAdapter(adapter);
Log.d("HOME TIMELINE", statii.toString());
} catch (TwitterException e) {
e.printStackTrace();
}
//list.setVisibility(View.VISIBLE);
read.setVisibility(View.GONE);*/
}
});
twitt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String status = edt.getText().toString();
if(status.trim().length() > 0)
{
new updateTwitter().execute(status);
}
}
});
if(!isTwitterLogedInAlready())
{
Uri uri = getIntent().getData();
if(uri != null && uri.toString().startsWith(twitterCallbackUrl))
{
String verify = uri.getQueryParameter(urlTwitterVerify);
try
{
AccessToken accessToken = twitter.getOAuthAccessToken(reqToken,verify);
Editor edit = pref.edit();
edit.putString(prefKeyOauthToken, accessToken.getToken());
edit.putString(prefKeyOauthSecret, accessToken.getTokenSecret());
edit.putBoolean(prefKeyTwitterLogin, true);
edit.commit();
Log.d("Twitter oauth Token", ">" + accessToken.getToken());
login.setVisibility(View.INVISIBLE);
twitt.setVisibility(View.VISIBLE);
edt.setVisibility(View.VISIBLE);
read.setVisibility(View.VISIBLE);
textName.setVisibility(View.VISIBLE);
if(man == true)
{
logout.setVisibility(View.VISIBLE);
}
long userId = accessToken.getUserId();
User user = twitter.showUser(userId);
//User user = twitter.getHomeTimeline();
Status n = user.getStatus();
String userName = user.getName();
textName.setText(userName);
}
catch(Exception e)
{
Log.d("Twitter Login Error", ">" + e.getMessage());
}
}
}
}
private void setUpIds() {
twitt = (Button)findViewById(R.id.buttTwitt);
login = (Button)findViewById(R.id.buttLogin);
read = (Button)findViewById(R.id.buttRead);
edt = (EditText)findViewById(R.id.editText1);
logout = (Button)findViewById(R.id.buttLogout);
textName = (TextView)findViewById(R.id.textName);
//list = (ListView)findViewById(R.id.listView1);
pref = getApplicationContext().getSharedPreferences("myPref", 0);
}
protected void logoutFromTwitter() {
Editor e = pref.edit();
e.remove(prefKeyOauthSecret);
e.remove(prefKeyOauthToken);
e.remove(prefKeyTwitterLogin);
e.commit();
login.setVisibility(View.VISIBLE);
logout.setVisibility(View.GONE);
twitt.setVisibility(View.GONE);
edt.setVisibility(View.GONE);
read.setVisibility(View.GONE);
textName.setVisibility(View.GONE);
}
protected void loginToTwitter() {
if(!isTwitterLogedInAlready())
{
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
builder.setJSONStoreEnabled(true);
builder.setIncludeEntitiesEnabled(true);
builder.setIncludeMyRetweetEnabled(true);
builder.setIncludeRTsEnabled(true);
Configuration config = builder.build();
TwitterFactory factory = new TwitterFactory(config);
twitter = factory.getInstance();
try{
reqToken = twitter.getOAuthRequestToken(twitterCallbackUrl);
this.startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(reqToken.getAuthenticationURL())));
}
catch(TwitterException e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
logout.setVisibility(View.VISIBLE);
man = false;
}
}
private boolean isTwitterLogedInAlready() {
return pref.getBoolean(prefKeyTwitterLogin, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class updateTwitter extends AsyncTask<String , String, String>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Updating to Twitter status..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecretKey);
// Access Token
String access_token = pref.getString(prefKeyOauthToken, "");
// Access Token Secret
String access_token_secret = pref.getString(prefKeyOauthSecret, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = twitter.updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Status update successfully", Toast.LENGTH_SHORT).show();
edt.setText("");
}
});
}
}
}
Use the new Twitter Fabric SDK for Android. Requires sign up first. If you don't want to wait to be approved for the sign up, then I recommend using the following link
https://github.com/Rockncoder/TwitterTutorial
The link above explains how to retrieve tweets. You should be able to use the above link COMBINED with the information in the link below to POST tweets!
https://dev.twitter.com/overview/documentation