How to save text entered in EditText after orientation changed? - android

I have two activities:
1.Main Activity which contains listview;
2.Second Activity which add item to listview in Main Activity.
For Second Activity I created layout-land layout for landscape.
After Second Activity is opens in portrait, I change it to landscape mode - Second Activity close and app return to Main Activity.
Questions:
1.How save entered to EditText fields values after orientation is changed?
2.And how to apply layout-land to Second Activity when change screen orientation to landscape?
UPD
Second activity code:
public class AddItem extends MainScreen implements OnClickListener{
final String LOG_TAG = "myLogs";
EditText comment_enter, link_enter, password_enter, login_enter, title_enter, date_enter;
Button add_item_button, add_more_button, clear_close_button;
CheckBox showPass;
DBHelper db;
DataBase DB;
SimpleCursorAdapter passListViewAdapter;
SimpleDateFormat sdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
Log.d(LOG_TAG, "before edit : ");
comment_enter = (EditText) findViewById(R.id.comment_enter);
link_enter = (EditText) findViewById(R.id.link_enter);
password_enter = (EditText) findViewById(R.id.password_enter);
login_enter = (EditText) findViewById(R.id.login_enter);
title_enter = (EditText) findViewById(R.id.title_enter);
date_enter = (EditText) findViewById(R.id.date_enter);
showPass = (CheckBox) findViewById(R.id.showPass);
showPass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.d(LOG_TAG, "is checked : " + isChecked);
if (isChecked) {
password_enter.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}
else {
password_enter.setInputType(129);
}
}
});
add_item_button = (Button) findViewById(R.id.add_item_button);
add_item_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "add_item_button : ");
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
byte[] login_byted = null;
try {
login_byted = login_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String login_crypted = Base64.encodeToString(login_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + login_crypted);
byte[] pass_byted = null;
try {
pass_byted = pass_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pass_crypted = Base64.encodeToString(pass_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + pass_crypted);
DataBase DB = new DataBase(AddItem.this);
DB.open();
DB.insertPass(title_str, login_crypted, pass_crypted, link_str, comm_str, date_str);
DB.close();
Log.d(LOG_TAG, "after inserting into DB : ");
finish();
}
});
add_more_button = (Button) findViewById(R.id.add_more_button);
add_more_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "add_more_button : ");
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
byte[] login_byted = null;
try {
login_byted = login_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String login_crypted = Base64.encodeToString(login_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + login_crypted);
byte[] pass_byted = null;
try {
pass_byted = pass_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pass_crypted = Base64.encodeToString(pass_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + pass_crypted);
DataBase DB = new DataBase(AddItem.this);
DB.open();
DB.insertPass(title_str, login_crypted, pass_crypted, link_str, comm_str, date_str);
DB.close();
Log.d(LOG_TAG, "after inserting into DB : ");
fieldClear();
String link_enter_str = link_enter.getText().toString();
if(link_enter_str.equals("")){
link_enter.setText("http://www.");
}
}
});
clear_close_button = (Button) findViewById(R.id.clear_close_button);
clear_close_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "clear/close click button : ");
boolean checkRes = emptyAllCheck();
Log.d(LOG_TAG, "result : " + checkRes);
if(checkRes == true){
finish();
}
fieldClear();
}
});
if(savedInstanceState != null){
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(LOG_TAG, "title : " + savedInstanceState.getString("title"));
title_enter.setText(savedInstanceState.getString("title"));
login_enter.setText(savedInstanceState.getString("login"));
password_enter.setText(savedInstanceState.getString("pass"));
link_enter.setText(savedInstanceState.getString("link"));
comment_enter.setText(savedInstanceState.getString("comm"));
date_enter.setText(savedInstanceState.getString("date"));
add_item_button = (Button) findViewById(R.id.add_item_button);
add_more_button = (Button) findViewById(R.id.add_more_button);
}
else {
Log.d(LOG_TAG, "before getting date : ");
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = sdf.format(new Date(System.currentTimeMillis()));
date_enter.setText(date);
}
}
#Override
protected void onPause() {
super.onPause();
finish();
Log.d(LOG_TAG, "onPause : ");
}
#Override
protected void onResume(){
super.onResume();
}
protected void onSaveInstanceState(Bundle saveInstance) {
super.onSaveInstanceState(saveInstance);
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
saveInstance.putString("title", title_str);
saveInstance.putString("login", login_str);
saveInstance.putString("pass", pass_str);
saveInstance.putString("link", link_str);
saveInstance.putString("comm", comm_str);
saveInstance.putString("date", date_str);
Log.d(LOG_TAG, "onSaveInstanceState +" + title_str + login_str + pass_str + link_str + comm_str + date_str);
}
public void fieldClear(){
comment_enter.setText("");
link_enter.setText("http://www.");
password_enter.setText("");
login_enter.setText("");
title_enter.setText("");
}
public boolean emptyAllCheck(){
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
if (title_str.equals("") && login_str.equals("") && pass_str.equals("") && link_str.equals("http://www.") && comm_str.equals("")) {
return true;
}
return false;
}
}

i advise you to read a bit more about Android Activity life cycle it will help you.
However on configuration Change android destroy you are activity and recreate and you can use the callback method OnsavedInstanceState() to save you instance (it will be call automatically by the system on configuration change)
example
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);{
String savedText = myEditText.getText().toString();
savedInstanceState.putString("Key", savedText);
}
Now when the app is recreated on OnCreate method retrieve your saved text as follow :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
myEditText.setText(savedInstanceState.getString("Key");
//the rest of the code}
Voila and I hope that is that you meant.

use this one:
android:configChanges="orientation|screenSize"
add this code in your manifest file. No need to save the edit text variable.

Related

obtaining the value of an EditText inside Asynctask

I am trying to make an app which uses FTP and changes the filename to a combination of 2 EditTexts. to properly upload it i am uploading it inside a 'asynctask' ,this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
String week = "w" + week_text.getText().toString() + "_";
String pagina = "p" + pagina_text.getText().toString() + ".jpg";
Button foto_keuze = (Button)findViewById(R.id.foto_keuze_button);
Button upload_button = (Button)findViewById(R.id.upload_button);
Typeface Impact = Typeface.createFromAsset(getAssets(), "fonts/Impact.ttf");
foto_keuze.setTypeface(Impact);
upload_button.setTypeface(Impact);
targetImage = (ImageView)findViewById(R.id.imageView);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public void upload_klik (View view) {
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
upload_task.execute(week_text, pagina_text);
}
protected class upload_task extends AsyncTask<EditText, Object, String> {
#Override
protected String doInBackground(EditText... params) {
EditText w = params[0];
EditText p = params[1];
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String ret = "Done!";
if(!bundle.isEmpty()) {
String afdeling_url = bundle.getString("afdeling_url", "DKW/");
String afdeling_preFix = bundle.getString("afdeling_preFix", "dkw");
String locatie_url = bundle.getString("locatie_url", "delf_wend");
String new_fileName = afdeling_preFix + w + p;
File f = new File(foto_path);
File sdcard = Environment.getExternalStorageDirectory();
File to = new File(sdcard, new_fileName);
f.renameTo(to);
if(f == null){
Toast.makeText(upload.this, "Geen foto geselecteerd", Toast.LENGTH_SHORT).show();
}
if(f != null) {
try{
Toast.makeText(getApplicationContext(), afdeling_url + afdeling_preFix, Toast.LENGTH_SHORT).show();
client.setPassive(true);
client.setAutoNoopTimeout(30000);
client.connect(FTP_HOST, 21);
client.login(FTP_USER, FTP_PASS);
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory(locatie_url + afdeling_url);
client.upload(to, new FTP_LISTENER());
restart();
}
catch (Exception e){
e.printStackTrace();
try {
client.disconnect(true);
Toast.makeText(getApplicationContext(), "Upload voltooid", Toast.LENGTH_SHORT);
}
catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
return ret;
}
}
My problem is as follows: i want to use the values of week_text.getText().toString(); and pagina_text.getText().toString(); in my Asynctask, but i cant find a way to achieve this.
i also have zero clue on what to do with the parameters behind Asynchtask, i have looked it up multiple times but it just doesnt make sense when using it for a FTP upload.
Help please ._.
Just pass String values to execute method like below
new upload_task().execute(edtText1.getText.toString,edtText2.getText.toString);
then
#Override
protected String doInBackground(String... params) {
String editText1Value = params[0];
String editText2Value = params[1];
///then do what ever you want
}
Just add the EditText` as parameter:
protected class upload_task extends AsyncTask<EditText, Object, String> {
#Override
protected String doInBackground(EditText... params) {
EditText editText1 = params[0];
EditText editText2 = params[1];
///rest of code:
}
}
And call it:
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
new upload_task().execute(week_text, paging_text);

Select in Android using JDBC

I'm trying to select the values of a table on an oracle DataBase and setting the result (the tudo variable) on a TextView, but when I click on the Button on the App, it closes and nothing happen.
public class MainActivity extends ActionBarActivity {
private String tudo = " ";
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
}
public void onClick(View view){
new Thread(new Runnable() {
#Override
public void run() {
insert();
// textView.setText(select());
}
}).start();
}
protected void select(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "XXXXXXX";
Connection c = DriverManager.getConnection(url, "XXXX", "XXXX");
Statement stmt = c.createStatement();
String teste;
ResultSet rset = stmt.executeQuery("SELECT * FROM TTESTE");
while (rset.next())
{
teste = (" " + rset.getString("NOME") + rset.getInt("ID"));
tudo = tudo + teste;
}
rset.close();
stmt.close();
c.close();
textView.setText(tudo);
}
catch (ClassNotFoundException | SQLException e){
e.printStackTrace();
}
}
}
Use the method:
runOnUiThread(new Runnable() {
#Override
public void run()
{
// seu codigo aqui
});

How to pass the name of the item clicked to another class

How to pass the name of the item clicked on the on list item clicked through Intent?
is this correct?
public class View_PPT_List extends ListActivity {
private final String SAMPLE_DB_NAME = "project";
private final String PPT_TABLE_NAME1 = "notes";
private final String PPT_TABLE_NAME2 = "subject";
SQLiteDatabase notesDB = null;
ArrayList<String> results = new ArrayList<String>();
public void onListItemClick(ListView l, View view, final int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, view, position, id);
Intent ins = new Intent (View_PPT_List.this,PPTActivity.class);
ins.putExtra("com.example.tinio_bolasa_project.finame",
String.valueOf(position));
startActivity(ins);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
notesDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
notesDB.execSQL("CREATE TABLE IF NOT EXISTS " +
PPT_TABLE_NAME1 +
" ( notes_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "subjid
INTEGER, " + "pptName VARCHAR, " + "pptPath VARCHAR);");
int x1 = getIntent().getIntExtra("pos",1);
Cursor c = notesDB.rawQuery("SELECT * FROM notes WHERE "+ x1 +"=subjid", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String pptid = c.getString(c.getColumnIndex("notes_ID"));
String ppt = c.getString(c.getColumnIndex("pptName"));
results.add(pptid + ppt);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (notesDB != null)
notesDB.close();
}
setContentView(R.layout.activity_view__ppt__list);
Button addppt = (Button) this.findViewById(R.id.button1);
addppt.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inten = new Intent (View_PPT_List.this, Add_PPT_Activity.class);
int x = getIntent().getIntExtra("pos",1);
inten.putExtra("key", x);
startActivity(inten);
}
});
}
}
then in my PowerpointActiv
public class PPTActivity extends Activity implements
DocumentSessionStatusListener {
private PersentationView content;
private DocumentSession session;
private SlideShowNavigator navitator;
private int currentSlideNumber;
private Button prev;
private Button next;
private SeekBar scale;
String filename = getIntent().getStringExtra("com.example.tinio_bolasa_project.finame");
String filePath = Environment.getExternalStorageDirectory()
.getPath() + "/" + filename;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
copyFileToSdcard();
this.setContentView(R.layout.powerpoint_main);
this.content = (PersentationView) this.findViewById(R.id.content);
this.prev = (Button) this.findViewById(R.id.prev);
this.prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prev();
}
});
this.next = (Button) this.findViewById(R.id.next);
this.next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
});
this.scale = (SeekBar) this.findViewById(R.id.scale);
this.scale
.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (progress < 1) {
progress = 1;
}
PPTActivity.this.content
.notifyScale(progress /
250.0);
}
});
try {
Context context = PPTActivity.this.getApplicationContext();
IMessageProvider msgProvider = new AndroidMessageProvider(context);
TempFileManager tmpFileManager = new TempFileManager(
new AndroidTempFileStorageProvider(context));
ISystemColorProvider sysColorProvider = new
AndroidSystemColorProvider();
session = new DocumentSessionBuilder(new File(filePath))
.setMessageProvider(msgProvider)
.setTempFileManager(tmpFileManager)
.setSystemColorProvider(sysColorProvider)
.setSessionStatusListener(this).build();
session.startSession();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStart() {
super.onStart();
this.content.setContentView(null);
}
#Override
protected void onDestroy() {
if (this.session != null) {
this.session.endSession();
}
super.onDestroy();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// Toast.makeText(this,
// "(" + event.getRawX() + "," + event.getRawY() + ")",
// Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
public void onSessionStarted() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onSessionStarted",
Toast.LENGTH_SHORT).show();
}
});
}
public void onDocumentReady() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onDocumentReady",
Toast.LENGTH_SHORT).show();
PPTActivity.this.navitator = new SlideShowNavigator(
PPTActivity.this.session.getPPTContext());
PPTActivity.this.currentSlideNumber =
PPTActivity.this.navitator
.getFirstSlideNumber() - 1;
PPTActivity.this.next();
}
});
}
public void onDocumentException(Exception e) {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onDocumentException",
Toast.LENGTH_SHORT).show();
PPTActivity.this.finish();
}
});
}
public void onSessionEnded() {
this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(PPTActivity.this, "onSessionEnded",
Toast.LENGTH_SHORT).show();
}
});
}
private void navigateTo(int slideNumber) {
SlideView slideShow = this.navitator.navigateToSlide(
this.content.getGraphicsContext(), slideNumber);
this.content.setContentView(slideShow);
}
private void next() {
if (this.navitator != null) {
if (this.navitator.getFirstSlideNumber()
+ this.navitator.getSlideCount() - 1 >
this.currentSlideNumber) {
this.navigateTo(++this.currentSlideNumber);
} else {
Toast.makeText(this, "Next page",
Toast.LENGTH_SHORT).show();
}
}
}
private void prev() {
if (this.navitator != null) {
if (this.navitator.getFirstSlideNumber() < this.currentSlideNumber)
{
this.navigateTo(--this.currentSlideNumber);
} else {
Toast.makeText(this, "Pre page", Toast.LENGTH_SHORT).show();
}
}
}
private void copyFileToSdcard() throws FileNotFoundException {
File file = new File(filePath.toString());
FileInputStream inputstream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int count = 0;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(filePath));
while ((count = inputstream.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
} catch (FileNotFoundException e1) {
Toast.makeText(PPTActivity.this, "Check your sdcard",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
i get error (java.runtimeExceptin: cannot instantiate activity ComponentInfo: Java.lang.nullpointerexception)..
how to pass the String name of the item :( pls help :(
This line
String nam = getIntent().getStringExtras("string");
should be
String nam = getIntent().getStringExtra("string"); // without the 's'
String nam = getIntent().getStringExtra("string"); //not getStringExtras
Because you have specified the tag (string) to get one String
You should pick up with:
String nam = getIntent().getStringExtra("string"); //without 's'

How to get Facebook Friends list in android application

I want to get Facebook friends list in my android application (friend picker not required).I have followed the the procedure describe on Facebook application development
I have also run the samples , but confused to get the friends list. your suggestions will be appreciated.
you can get friend list with this code
String returnString = null;
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
for(int i=0;i<jArray.length();i++){
Log.i("log_tag","User Name: "+json_data.getString("name")+
", user_id: "+json_data.getString("id"));
returnString += "\n\t" + jArray.getJSONObject(i);
};
flist.setText(returnString);
progressDialog.dismiss();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
I get just name and id , if you want get different things,
public class MainActivity extends FragmentActivity implements OnClickListener {
private static final String LOGTAG = "MainActivity";
private List<GraphUser> tags;
private Button pickFriendsButton;
Button locationtoast;
private ProfilePictureView profilePictureView;// 2
private LoginButton fb_loginBtn;// loginbtn
private TextView userName, userName2, userName3, userName4, text;
private UiLifecycleHelper uiHelper;
// private Button pickFriendsButton;
Button btnlogin;
String Name;
String Id;
String lastname;
String firstname;
String getUsername;
String get_gender;
GraphPlace location;
String profileid;
String birthday;
String get_email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationtoast = (Button) findViewById(R.id.location_button);
locationtoast.setOnClickListener(this);
btnlogin = (Button) findViewById(R.id.profile_view);
btnlogin.setOnClickListener(this);
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);// 3
text = (TextView) findViewById(R.id.text);
userName = (TextView) findViewById(R.id.user_name);
fb_loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
pickFriendsButton = (Button) findViewById(R.id.add_friend);
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
pickFriendsButton.setEnabled(enableButtons);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void showPickerFragment(FriendPickerFragment fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment,
FacebookException error) {
String text = getString(R.string.exception,
error.getMessage());
Toast toast = Toast.makeText(MainActivity.this, text,
Toast.LENGTH_SHORT);
toast.show();
}
});
}
private void setFriendPickerListeners(
final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(
PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
List<GraphUser> selection = fragment.getSelection();
tags = selection;
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
// showAlert("fghjklkbvbn", results);
showAlert(getString(R.string.you_picked), results);
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(MainActivity.this).setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null).show();
}
});
fb_loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
// Intent intent = new Intent(this, ValuesShow.class);
// startActivity(i);
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
profilePictureView.setProfileId(user.getId());// 4
userName.setText("Hello , " + user.getName()
+ "\n you logged In Uaar Alumni ");
// userName2.setText("frstname"+ user.getFirstName());
// userName3.setText("address"+user.getBirthday());
// userName4.setText("texr"+user.getLocation());
get_email = (String) user.getProperty("email");
Name = user.getName();
Id = user.getId();
lastname = user.getLastName();
firstname = user.getFirstName();
getUsername = user.getUsername();
location = user.getLocation();
get_gender = (String) user.getProperty("gender");
// birthday=user.getBirthday();
// profileid=user.getId();
// profilePictureView.setProfileId(Id.getId());
// text.setText(Name + " \n " + Id + "\n" + firstname +
// "\n"
// + lastname + "\n" + getUsername + "\n" + get_gender);
// profilePicture=user.getId();
} else {
userName.setText("You are not logged");
}
}
});
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
text.setText("");
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = null;
switch (v.getId()) {
// case R.id.fb_login_button:
case R.id.location_button:
i = new Intent(this, LocationGet.class);
break;
// i=new Intent (this,Main_menu.class);
// break;
case R.id.profile_view:
i = new Intent(this, ValuesShow.class);
Log.d(Name, "" + Name);
i.putExtra("Name", Name);
i.putExtra("get_gender", get_gender);
i.putExtra("lastname", lastname);
i.putExtra("firstname", firstname);
i.putExtra("Id", Id);
i.putExtra("birthday", birthday);
i.putExtra("get_email", get_email);
// i.putExtra("profileid",profileid);
break;
}
// profilePictureView.setProfileId(user.getId());
// Intent intent = new Intent(this, ValuesShow.class);
// intent.getBooleanExtra("location", location);
Log.d(lastname, "" + lastname);
Log.d(get_gender, "" + get_gender);
// Log.d(LOGTAG,"Name value name....");
startActivity(i);
}
}

Inner AsyncTask not updating member variables in outer class

I have an app that in one of it's Activities uses AsyncTask to call a method from another class that hooks up to a database to varify a user's login credentials. The Activity EntryActivity Has three member variable that need to be updated with the result of the AsyncTask, carerID, firstName and surName . When I first run the App all three variables are null but if i press the login button a second time the variables are set correctly and the app behaves as it should.
Is there a reason why the three member variables are not set correctly from onPostxecute in the first run of the app?
.
public class EntryActivity extends NfcBaseActivity{
private LoginWebservice loginWebservice;
private static final String TAG = EntryActivity.class.getSimpleName();
private Button login;
private EditText userName;
private EditText passwordPin;
NfcScannerApplication nfcscannerapplication;
public static final String CUSTOM_QRCODE_ACTION = "com.carefreegroup.QRCODE_ACTION";
private String carerID;
private String firstName;
private String surName;
private boolean isValidated = false;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
nfcscannerapplication = (NfcScannerApplication) getApplication();
loginWebservice = new LoginWebservice(this);
carerID = null;
firstName = null;
surName = null;
userName = (EditText)findViewById(R.id.username);
passwordPin = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.buttonlogin);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
////////////get user's input///////////
String compId = "100";
String theUsername = userName.getText().toString();
String thePassword = passwordPin.getText().toString();
String loginType = "1";
String[] params = new String[]{compId, theUsername, thePassword, loginType};
//validate user Asynchonously on background thread
new AsyncValidateCarer().execute(params);
Log.e(TAG, "carerid =" + carerID + " firstname = " + firstName + " surnamee = " + surName);
DateTime now = new DateTime();
long loginTime = now.getMillis();
String fullName = firstName +" " + surName;
Log.e(TAG, "fullname = " + fullName);
if(carerID != null){
ContentValues loginValues = new ContentValues();
loginValues.putNull(LoginValidate.C_ID_INDEX);
loginValues.put(LoginValidate.C_CARER_ID, carerID);
loginValues.put(LoginValidate.C_COMP_ID, compId);
loginValues.put(LoginValidate.C_CARER_NAME, fullName);
loginValues.put(LoginValidate.C_PASSWORD, thePassword);
loginValues.put(LoginValidate.C_DATE_TIME, loginTime);
nfcscannerapplication.loginValidate.insertIntoCarer(loginValues);
Toast.makeText(
EntryActivity.this,
"Carer logged in to System",
Toast.LENGTH_LONG).show();
isValidated = true;
Intent intent = new Intent(EntryActivity.this,
NfcscannerActivity.class);
intent.setAction(CUSTOM_QRCODE_ACTION);
startActivity(intent);
}else{
Toast.makeText(
EntryActivity.this,
"Please check credentials",
Toast.LENGTH_LONG).show();
}
//////////////validate user/////////////////
}
});
Button changeUser = (Button)findViewById(R.id.buttonchangeuser);
changeUser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "change user button clicked");
nfcscannerapplication.loginValidate.deleteTableCarer();
Toast.makeText(
EntryActivity.this,
"Carer logged out",
Toast.LENGTH_LONG).show();
EntryActivity.this.onCreate(savedInstanceState);
}
});
}//end of onCreate
private void hideSoftKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(passwordPin.getWindowToken(), 0);
}
private class AsyncValidateCarer extends AsyncTask<String, Void, ContentValues> {
#Override
protected ContentValues doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside asynctask");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
if (cv != null){
Log.e(TAG, "cv = not null!");
}
} catch (Exception e) {
e.printStackTrace();
}
return cv;
}
#Override
protected void onPostExecute(ContentValues result) {
Log.e(TAG, "inside onpostexecute");
EntryActivity.this.carerID = (String) result.get("carerID");
EntryActivity.this.firstName = (String) result.get("firstname");
EntryActivity.this.surName = (String) result.get("surname");
}
}
}
[update]
private class AsyncValidateCarer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside doInBackground");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
carerID = (String) cv.get("carerID");
firstName = (String) cv.get("firstname");
surName = (String) cv.get("surname");
if (cv != null){
Log.e(TAG, "cv = not null! and exiting doInBackground");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
An AsyncTask will execute asynchronously so you have no guarantee that after the "execute" method call, the task is actually finished. My advice would be to move everything (or at least what is related to those fields) that are after "execute" call in "onPostExecute" method.
The reason why it seems the first click doesn't work and the second works, is that between the first "Login" click and the second one, you wait enough for the AsyncTask to finish. So when you click for the second time you see the results of the first execution. Please add some "Log" messeges in "onPostExecute" to understand what is going on.
Hope it helps:)
carerID = null;
firstName = null;
surName = null;
Remove the above there statements from the onCreate() method, as they have been initialized to their default values as they are in the Class Scope and are known as Instance Variables.

Categories

Resources