Worklight form based authentication in a Native Android Application - android

I'm trying to get working a native android project that uses Worklight form based authentication. I'm already able to authenticate the user through the native APIs. The problem appears when I change between activities (intents). Once the user enters his information and submits the form, it is authenticated but the worklight server connection is lost.
This is the code:
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, "BasicAuth");
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "RSSReader";
String procedureName = "getStoriesFiltered";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
Object[] parameters = new Object[] {"world"};
invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyInvokeListener(), options);
}
});
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MyChallengeHadler challengeHandler = new MyChallengeHadler(LoginActivity.this, "BasicAuth");
challengeHandler.submitLogin(0, "maria", "maria", 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.login, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
this.parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
Intent login = new Intent(parentActivity, MainActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}

I have already solved my code's problem. I was using wrongly android's intents. This is the new version of the code:
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit;
private Intent result;
public static final String Back = "back";
public static final String UserNameExtra = "username";
public static final String PasswordExtra = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
result = new Intent();
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
result.putExtra(UserNameExtra, "maria");
result.putExtra(PasswordExtra, "maria");
result.putExtra(Back, false);
setResult(RESULT_OK, result);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
private String realm = "BasicAuth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, realm);
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "SOAPAdapter";
String procedureName = "getStories";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
//Object[] parameters = new Object[] {"world"};
//invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyResponseListener(), options);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
boolean back = data.getBooleanExtra(LoginActivity.Back, true);
String username = data.getStringExtra(LoginActivity.UserNameExtra);
String password = data.getStringExtra(LoginActivity.PasswordExtra);
challengeHandler.submitLogin(resultCode, username, password, back);
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
if (resultCode != Activity.RESULT_OK || back) {
submitFailure(cachedResponse);
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
}
}
}

Related

How to get the data from server and upload data to server using Json

How to get the data from server and upload data to server using JSON?
please tell me.
This is QRActivity------------------------------------------------
final View.OnClickListener listener = new View.OnClickListener() {
#Override
public
void onClick(View v) {
btnSearch.setClickable(true);
// Server call with record_id
//DistributionDetails detDis <-- response json object from server call
QrActivityViewDetails detDis = new
QrActivityViewDetails(1002,"NORORG147530","No2,abcd Road , Colombo 03","0112233456");
Intent myIntent = new Intent(QrActivity.this, DistributionDetails.class);
myIntent.putExtra("QrActivityViewDetails", detDis);
startActivity(myIntent);
}
};
This is QrActivityViewDetails Class file
public class QrActivityViewDetails implements Serializable {
#SerializedName("DistributionID")
private int DistributionID;
#SerializedName("full_name")
private String full_name;
#SerializedName("full_address")
private String full_address;
#SerializedName("contact")
private String contact;
public QrActivityViewDetails(int DistributionID, String full_name, String full_address, String contact_number)
{
this.DistributionID = DistributionID;
this.full_name = full_name;
this.full_address = full_address;
this.contact = contact_number;
}
public
int getRecord_id() {
return DistributionID;
}
public
void setRecord_id(int record_id) {
this.DistributionID = record_id;
}
public
String getFull_name() {
return full_name;
}
public
void setFull_name(String full_name) {
this.full_name = full_name;
}
public
String getFull_address() {
return full_address;
}
public
void setFull_address(String full_address) {
this.full_address = full_address;
}
public
String getContact() {
return contact;
}
public
void setContact(String contact) {
this.contact = contact;
}
}
This is View Data Activity called DistributionDetails---------------
public class DistributionDetails extends AppCompatActivity {
private QrActivityViewDetails detQRV;
TextView ID ,Address ,name,contact;
Button btnDIR;
#Override
protected
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_distribution_details);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
ID = (TextView) findViewById(R.id.lblID);
Address = (TextView) findViewById(R.id.lblAddress);
name = (TextView) findViewById(R.id.lblUname);
contact = (TextView) findViewById(R.id.lblTelenum);
btnDIR = (Button) findViewById(R.id.btnDelivered);
IntendFill();
btnDIR.setOnClickListener(new View.OnClickListener() {
#Override
public
void onClick(View v) {
Intent intent = new Intent(DistributionDetails.this, FinalActivity.class);
startActivity(intent);
}
});
}
public void IntendFill() {
Intent intent = getIntent();
if (intent.hasExtra("QrActivityViewDetails")) {
detQRV = (QrActivityViewDetails) intent.getSerializableExtra("QrActivityViewDetails");
ID.setText(String.valueOf(detQRV.getRecord_id()));
Address.setText(String.valueOf(detQRV.getFull_address()));
name.setText(String.valueOf(detQRV.getFull_name()));
contact.setText(String.valueOf(detQRV.getContact()));
}
}
}

Update custom adapter with query results

i want to query results from custom adapter by comparing query text with list in RecycleView, it successfully gets results from query then i make list of results and update the existing adapter but it does not effect anything, i use below code fot that
combinationMessagesList = createCombinationMessagesList();
combinationMessages = createCombinationMessagesList();
combinationMessages.clear();
for (int i = 0; i < combinationMessagesList.size(); i++) {
CombinationMessage message = combinationMessagesList.get(i);
if (message.getBody().toString().equals(search.getText().toString())){
combinationMessages.add(combinationMessagesList.get(i));
}
}
messagesAdapter.setList(combinationmessagesList);
messagesAdapter.notifyDataSetChanged();
}
PrivateDialogActivity
public class PrivateDialogActivity extends BaseDialogActivity {
private FriendOperationAction friendOperationAction;
private FriendObserver friendObserver;
private int operationItemPosition;
private final String TAG = "PrivateDialogActivity";
EditText search;
public static void start(Context context, User opponent, Dialog dialog) {
Intent intent = new Intent(context, PrivateDialogActivity.class);
intent.putExtra(QBServiceConsts.EXTRA_OPPONENT, opponent);
intent.putExtra(QBServiceConsts.EXTRA_DIALOG, dialog);
context.startActivity(intent);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initFields();
context = this;
if (dialog == null) {
finish();
}
setUpActionBarWithUpButton();
if (isNetworkAvailable()) {
deleteTempMessages();
}
addObservers();
initMessagesRecyclerView();
search = (EditText) findViewById(R.id.search_edittext);
Button button = (Button) findViewById(R.id.search);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
}
});
}
private void showResult() {
combinationMessagesList = createCombinationMessagesList();
combinationMessages = createCombinationMessagesList();
combinationMessages.clear();
for (int i = 0; i < combinationMessagesList.size(); i++) {
CombinationMessage message = combinationMessagesList.get(i);
if (message.getBody().toString().equals(search.getText().toString())){
combinationMessages.add(combinationMessagesList.get(i));
}
}
messagesAdapter.setList(combinationMessagesList);
messagesAdapter.notifyDataSetChanged();
}
#Override
protected void addActions() {
super.addActions();
addAction(QBServiceConsts.ACCEPT_FRIEND_SUCCESS_ACTION, new AcceptFriendSuccessAction());
addAction(QBServiceConsts.ACCEPT_FRIEND_FAIL_ACTION, failAction);
addAction(QBServiceConsts.REJECT_FRIEND_SUCCESS_ACTION, new RejectFriendSuccessAction());
addAction(QBServiceConsts.REJECT_FRIEND_FAIL_ACTION, failAction);
updateBroadcastActionList();
}
#Override
protected void onResume() {
super.onResume();
checkForCorrectChat();
if (isNetworkAvailable()) {
startLoadDialogMessages();
}
checkMessageSendingPossibility();
}
#Override
protected void onDestroy() {
super.onDestroy();
deleteObservers();
}
#Override
protected void updateActionBar() {
setOnlineStatus(opponentUser);
checkActionBarLogo(opponentUser.getAvatar(), R.drawable.placeholder_user);
}
#Override
protected void onConnectServiceLocally(QBService service) {
onConnectServiceLocally();
setOnlineStatus(opponentUser);
}
#Override
protected void onFileLoaded(QBFile file, String dialogId) {
if(!dialogId.equals(dialog.getDialogId())){
return;
}
try {
privateChatHelper.sendPrivateMessageWithAttachImage(file, opponentUser.getUserId(), null, null);
} catch (QBResponseException exc) {
ErrorUtils.showError(this, exc);
}
}
#Override
protected Bundle generateBundleToInitDialog() {
Bundle bundle = new Bundle();
bundle.putInt(QBServiceConsts.EXTRA_OPPONENT_ID, opponentUser.getUserId());
return bundle;
}
#Override
protected void initMessagesRecyclerView() {
super.initMessagesRecyclerView();
messagesAdapter = new PrivateDialogMessagesAdapter(this, friendOperationAction, combinationMessagesList, this, dialog);
messagesRecyclerView.addItemDecoration(
new StickyRecyclerHeadersDecoration((StickyRecyclerHeadersAdapter) messagesAdapter));
findLastFriendsRequest();
messagesRecyclerView.setAdapter(messagesAdapter);
scrollMessagesToBottom();
}
#Override
protected void updateMessagesList() {
initActualExtras();
checkForCorrectChat();
int oldMessagesCount = messagesAdapter.getAllItems().size();
this.combinationMessagesList = createCombinationMessagesList();
Log.d(TAG, "combinationMessagesList = " + combinationMessagesList);
messagesAdapter.setList(combinationMessagesList);
findLastFriendsRequest();
checkForScrolling(oldMessagesCount);
}
private void initActualExtras() {
opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
}
#Override
public void notifyChangedUserStatus(int userId, boolean online) {
super.notifyChangedUserStatus(userId, online);
if (opponentUser != null && opponentUser.getUserId() == userId) {
setOnlineStatus(opponentUser);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.private_dialog_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean isFriend = DataManager.getInstance().getFriendDataManager().getByUserId(
opponentUser.getUserId()) != null;
if (!isFriend && item.getItemId() != android.R.id.home) {
ToastUtils.longToast(R.string.dialog_user_is_not_friend);
return true;
}
switch (item.getItemId()) {
case R.id.action_audio_call:
callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_AUDIO);
break;
case R.id.switch_camera_toggle:
callToUser(opponentUser, QBRTCTypes.QBConferenceType.QB_CONFERENCE_TYPE_VIDEO);
break;
default:
super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void checkMessageSendingPossibility() {
boolean enable = dataManager.getFriendDataManager().existsByUserId(opponentUser.getUserId()) && isNetworkAvailable();
checkMessageSendingPossibility(enable);
}
#OnClick(R.id.toolbar)
void openProfile(View view) {
UserProfileActivity.start(this, opponentUser.getUserId());
}
private void initFields() {
chatHelperIdentifier = QBService.PRIVATE_CHAT_HELPER;
friendOperationAction = new FriendOperationAction();
friendObserver = new FriendObserver();
initActualExtras();
// opponentUser = (User) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_OPPONENT);
// dialog = (Dialog) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG);
combinationMessagesList = createCombinationMessagesList();
title = opponentUser.getFullName();
}
private void addObservers() {
dataManager.getFriendDataManager().addObserver(friendObserver);
}
private void deleteObservers() {
dataManager.getFriendDataManager().deleteObserver(friendObserver);
}
private void findLastFriendsRequest() {
((PrivateDialogMessagesAdapter) messagesAdapter).findLastFriendsRequestMessagesPosition();
messagesAdapter.notifyDataSetChanged();
}
private void setOnlineStatus(User user) {
if (user != null) {
if (friendListHelper != null) {
String offlineStatus = getString(R.string.last_seen, DateUtils.toTodayYesterdayShortDateWithoutYear2(user.getLastLogin()),
DateUtils.formatDateSimpleTime(user.getLastLogin()));
setActionBarSubtitle(
OnlineStatusUtils.getOnlineStatus(this, friendListHelper.isUserOnline(user.getUserId()), offlineStatus));
}
}
}
public void sendMessage(View view) {
sendMessage(true);
}
private void callToUser(User user, QBRTCTypes.QBConferenceType qbConferenceType) {
if (!isChatInitializedAndUserLoggedIn()) {
ToastUtils.longToast(R.string.call_chat_service_is_initializing);
return;
}
List<QBUser> qbUserList = new ArrayList<>(1);
qbUserList.add(UserFriendUtils.createQbUser(user));
CallActivity.start(PrivateDialogActivity.this, qbUserList, qbConferenceType, null);
}
private void acceptUser(final int userId) {
if (isNetworkAvailable()) {
if (!isChatInitializedAndUserLoggedIn()) {
ToastUtils.longToast(R.string.call_chat_service_is_initializing);
return;
}
showProgress();
QBAcceptFriendCommand.start(this, userId);
} else {
ToastUtils.longToast(R.string.dlg_fail_connection);
return;
}
}
private void rejectUser(final int userId) {
if (isNetworkAvailable()) {
if (!isChatInitializedAndUserLoggedIn()) {
ToastUtils.longToast(R.string.call_chat_service_is_initializing);
return;
}
showRejectUserDialog(userId);
} else {
ToastUtils.longToast(R.string.dlg_fail_connection);
return;
}
}
private void showRejectUserDialog(final int userId) {
User user = DataManager.getInstance().getUserDataManager().get(userId);
if (user == null) {
return;
}
TwoButtonsDialogFragment.show(getSupportFragmentManager(),
getString(R.string.dialog_message_reject_friend, user.getFullName()),
new MaterialDialog.ButtonCallback() {
#Override
public void onPositive(MaterialDialog dialog) {
super.onPositive(dialog);
showProgress();
QBRejectFriendCommand.start(PrivateDialogActivity.this, userId);
}
});
}
private void checkForCorrectChat() {
Dialog updatedDialog = null;
if (dialog != null) {
updatedDialog = dataManager.getDialogDataManager().getByDialogId(dialog.getDialogId());
} else {
finish();
}
if (updatedDialog == null) {
finish();
} else {
dialog = updatedDialog;
}
}
private class FriendOperationAction implements FriendOperationListener {
#Override
public void onAcceptUserClicked(int position, int userId) {
operationItemPosition = position;
acceptUser(userId);
}
#Override
public void onRejectUserClicked(int position, int userId) {
operationItemPosition = position;
rejectUser(userId);
}
}
private class AcceptFriendSuccessAction implements Command {
#Override
public void execute(Bundle bundle) {
((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
messagesAdapter.notifyItemChanged(operationItemPosition);
startLoadDialogMessages();
hideProgress();
}
}
private class RejectFriendSuccessAction implements Command {
#Override
public void execute(Bundle bundle) {
((PrivateDialogMessagesAdapter) messagesAdapter).clearLastRequestMessagePosition();
messagesAdapter.notifyItemChanged(operationItemPosition);
startLoadDialogMessages();
hideProgress();
}
}
private class FriendObserver implements Observer {
#Override
public void update(Observable observable, Object data) {
if (data != null && data.equals(FriendDataManager.OBSERVE_KEY)) {
checkForCorrectChat();
checkMessageSendingPossibility();
}
}
}
}
it was my own mistake it code, i made the code work by changing messagesAdapter.setList(combinationmessagesList)
to
messagesAdapter.setList(combinationMessages);

how to read content description for an alert dialog in android

I am alerting the user after some action and showing alert dialog but when accessibility is on it is not reading full alert dailog header and body. It is reading only header. I found this issue in samsung galaxy s5.
Please help me solving this issue.
public class TransactionDialog extends DialogFragment {
private int _state = -1;
private final String TITLE = "TITLE";
private final String MESSAGE = "MESSAGE";
private final String POS_TEXT = "POS_TEXT";
private final String STATE = "STATE";
private int _title = 0;
private int _message = 0;
private int _positiveText = 0;
private NoticeDialogListener mListener;
Logger logger = Logger.getNewLogger("com.ui.TransactionDialog");
boolean actionPerformed = false;
AlertDialog dialog = null;
public TransactionDialog() {
}
public void setListener(NoticeDialogListener listener) {
this.mListener = listener;
}
public TransactionDialog(int title, int message, int positiveText, int state) {
this._title = title;
this._message = message;
this._positiveText = positiveText;
this._state = state;
}
public int getState() {
return _state;
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putInt(TITLE, this._title);
outState.putInt(MESSAGE, this._message);
outState.putInt(POS_TEXT, this._positiveText);
outState.putInt(STATE, this._state);
}
#Override
public void onResume() {
super.onResume();
logger.debug("TITLE:" + this._title);
logger.debug("_message:" + this._message);
logger.debug("_positiveText:" + this._positiveText);
logger.debug("_state:" + this._state);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
logger.debug("Created");
}
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
super.onDismiss(dialog);
mListener.onDialogDismissed();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
logger.debug("ON CREATE");
if (savedInstanceState != null) {
this._title = savedInstanceState.getInt(TITLE);
this._message = savedInstanceState.getInt(MESSAGE);
this._positiveText = savedInstanceState.getInt(POS_TEXT);
this._state = savedInstanceState.getInt(STATE);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(this._title))
.setMessage(getResources().getString(_message))
.setPositiveButton(getResources().getString(_positiveText), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(actionPerformed)
return;
actionPerformed = true;
mListener.onDialogPositiveClick(TransactionDialog.this);
}
});
dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
dialog.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
mListener.onDialogPositiveClick(TransactionDialog.this);
}
return false;
}
});
return dialog;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogDismissed();
}}
Here i am using the txndialog class for creating the alert dialog.
private TransactionDialog transactionDialog;
transactionDialog = (TransactionDialog) newTransactionFrgment;
transactionDialog.setListener(this);
transactionDialog = new TransactionDialog(R.string.transaction_complete_header, R.string.transaction_complete_message,
R.string.transaction_complete_positive_button, STATE_SET_TRANSACION);
transactionDialog.show(getFragmentManager(), TRANSACTION_DIALOG_TAG);

save info about facebook user to use in another Activity

I'm working on project to my university, and I would like to know how save some information about facebook user like name, e-mail and picture. Then how I can use this information in another Activity? As you can see my code i can show info in the same activity that i logged but i cant have in another activity
MainActivity.java
public class MainActivity extends ActionBarActivity {
public static final int INDEX_SIMPLE_LOGIN = 0;
public static final int INDEX_CUSTOM_LOGIN = 1;
private static final String STATE_SELECTED_FRAGMENT_INDEX = "selected_fragment_index";
public static final String FRAGMENT_TAG = "fragment_tag";
private FragmentManager mFragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#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;
}
if (id == R.id.action_simple_login) {
toggleFragment(INDEX_SIMPLE_LOGIN);
return true;
}
if (id == R.id.action_custom_login) {
toggleFragment(INDEX_CUSTOM_LOGIN);
return true;
}
return super.onOptionsItemSelected(item);
}
private void toggleFragment(int index) {
Fragment fragment = mFragmentManager.findFragmentByTag(FRAGMENT_TAG);
FragmentTransaction transaction = mFragmentManager.beginTransaction();
switch (index) {
case INDEX_SIMPLE_LOGIN:
transaction.replace(android.R.id.content, new FragmentSimpleLoginButton(), FRAGMENT_TAG);
break;
case INDEX_CUSTOM_LOGIN:
transaction.replace(android.R.id.content, new FragmentCustomLoginButton(), FRAGMENT_TAG);
break;
}
transaction.commit();
}
}
MyApplication.java
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
}
/**
* Call this method inside onCreate once to get your hash key
*/
public void printKeyHash() {
try {
PackageInfo info = getPackageManager().getPackageInfo("vivz.slidenerd.facebookv40helloworld", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.e("VIVZ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
}
FragmentSimpleLoginButton.java
public class FragmentSimpleLoginButton extends Fragment {
private TextView mTextDetails;
private CallbackManager mCallbackManager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("VIVZ", "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onCancel() {
Log.d("VIVZ", "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.d("VIVZ", "onError " + e);
}
};
public FragmentSimpleLoginButton() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();
mTokenTracker.startTracking();
mProfileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_simple_login_button, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
setupTextDetails(view);
setupLoginButton(view);
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onStop() {
super.onStop();
mTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setupTextDetails(View view) {
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}
private void setupTokenTracker() {
mTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
Log.d("VIVZ", "" + currentAccessToken);
}
};
}
private void setupProfileTracker() {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Log.d("VIVZ", "" + currentProfile);
mTextDetails.setText(constructWelcomeMessage(currentProfile));
}
};
}
private void setupLoginButton(View view) {
LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
mButtonLogin.setFragment(this);
mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);
}
private String constructWelcomeMessage(Profile profile) {
StringBuffer stringBuffer = new StringBuffer();
if (profile != null) {
stringBuffer.append("Welcome " + profile.getName());
}
return stringBuffer.toString();
}
if you want to send the info to the next activity you can add it to the intent with a bundle.
ACTIVITY:
Intent i=new Intent(Activity.this, SecontActivity.class);
i.putExtra("email", email);
startActivity(i);
SecontActivity:
Intent intent = getIntent();
String email = intent.getStringExtra("email");
if you want the info in all your activities then save it in SharedPreferences
Activity:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("email", email);
editor.commit();
SecondActivity:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String email = sharedPref.getString(email, defaultValue);
Store the info such as name, imageurl and other profile details in a database or (sharedpreferences as indicated here) for access across different activities. This information can be fetched at any stage once saved throughout the history of the app unless the data from the app is cleared.
I would go for the database as it would more structure and can potentially provide multi-user support, incase you want to implement profile switching in your app.

Android Pass string to non Activity

I have MainActivity with two String variables viz. filename & url.
I tried to use one download manager.
I dont know how to pass filename String from my Player Activity.
buttondownload = (TextView )findViewById(R.id.download);
buttondownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadHelper.addNewTask(Player.this, url,
new PreDownloadStatusListener() {
#Override
public void notFoundSDCard(int errorCode, String errorInfo) {
Toast.makeText(Player.this, "No SD Card", Toast.LENGTH_SHORT).show();
}
#Override
public void sdCardCannotWriteOrRead(int errorCode, String errorInfo) {
Toast.makeText(Player.this, "Not read and write SD card", Toast.LENGTH_SHORT).show();
}
#Override
public void moreTaskCount(int errorCode, String errorInfo) {
Toast.makeText(Player.this, "Task list is full", Toast.LENGTH_SHORT).show();
}
});
Intent intent1 = new Intent(Player.this, DownloadListActivity.class);
startActivity(intent1);
}
});
DownloadHelper.startAllTask(Player.this);
mReceiver = new DownloadReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(DownloadValues.Actions.BROADCAST_RECEIVER_ACTION);
registerReceiver(mReceiver, filter);
They call filename from another public class DownloadUtils.. How can i pass filname to DownloadUtils
I want Pass String from Player to ViewHolder.java
package com.download.main;
public class ViewHolder {
public static final int KEY_URL = 0;
public static final int KEY_SPEED = 1;
public static final int KEY_PROGRESS = 2;
public static final int KEY_IS_PAUSED = 3;
public TextView titleText;
public ProgressBar progressBar;
public TextView speedText;
public ImageButton pauseButton;
public ImageButton deleteButton;
public ImageButton continueButton;
private boolean hasInited = false;
public ViewHolder(View parentView) {
if (parentView != null) {
titleText = (TextView) parentView.findViewById(R.id.title);
speedText = (TextView) parentView.findViewById(R.id.speed);
progressBar = (ProgressBar) parentView.findViewById(R.id.progress_bar);
pauseButton = (ImageButton) parentView.findViewById(R.id.btn_pause);
deleteButton = (ImageButton) parentView.findViewById(R.id.btn_delete);
continueButton = (ImageButton) parentView.findViewById(R.id.btn_continue);
hasInited = true;
}
}
public static HashMap<Integer, String> getItemDataMap(String url, String speed, String progress, String isPaused) {
HashMap<Integer, String> item = new HashMap<Integer, String>();
item.put(KEY_URL, url);
item.put(KEY_SPEED, speed);
item.put(KEY_PROGRESS, progress);
item.put(KEY_IS_PAUSED, isPaused);
return item;
}
public void setData(HashMap<Integer, String> item) {
if (hasInited) {
titleText.setText(///////**I want here my my string calle "filename" from player Activity**//////);
speedText.setText(item.get(KEY_SPEED));
String progress = item.get(KEY_PROGRESS);
if (TextUtils.isEmpty(progress)) {
progressBar.setProgress(0);
}
else {
progressBar.setProgress(Integer.parseInt(progress));
}
if (Boolean.parseBoolean(item.get(KEY_IS_PAUSED))) {
onPause();
}
}
}
public void onPause() {
if (hasInited) {
pauseButton.setVisibility(View.GONE);
continueButton.setVisibility(View.VISIBLE);
}
}
public void setData(String url, String speed, String progress) {
setData(url, speed, progress, false + "");
}
public void setData(String url, String speed, String progress, String isPaused) {
if (hasInited) {
HashMap<Integer, String> item = getItemDataMap(url, speed, progress, isPaused);
titleText.setText(///////**I want here my my string calle "filename" from player Activity**//////);
speedText.setText(speed);
if (TextUtils.isEmpty(progress)) {
progressBar.setProgress(0);
}
else {
progressBar.setProgress(Integer.parseInt(item.get(KEY_PROGRESS)));
}
}
}
}
To pass any data from one activity to another use Intent. Example:-
Use below code in your Player.java class:-
Intent intent = new Intent(FromClass.this, ToClass.class);
intent.putExtra("filename", filename);
startActivity(intent);
Write the below code in the ViewHolder.java class:-
do not forget to extend Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayoutName);
Intent intent = getIntent();
String filename= intent.getStringExtra("filename");
}
Then you can use filename in your setData() like this:-
public void setData(HashMap<Integer, String> item) {
if (hasInited) {
titleText.setText(filename);
speedText.setText(item.get(KEY_SPEED));
String progress = item.get(KEY_PROGRESS);
if (TextUtils.isEmpty(progress)) {
progressBar.setProgress(0);
}
else {
progressBar.setProgress(Integer.parseInt(progress));
}
if (Boolean.parseBoolean(item.get(KEY_IS_PAUSED))) {
onPause();
}
}
}

Categories

Resources