How to check whether an item exists in the dynamodb table? - amazon-web-services

I am making an android app with login via facebook and custom signup. I am using AWS dynamodb to store the user data.
I am able to store the data from facebook and custom signup but unable to scan that data. Actually I want whenever a user come back to login with his/her credentials either custom or facebook, the app should check whether the entered fields present in the table or not. If it is unavailable then app will ask user to signup first.
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
Button login;
TextView signup;
TextView help;
EditText etUsername;
EditText etPassword;
String email;
String pass;
String email1;
String pass1;
private CognitoCachingCredentialsProvider credentialsProvider;
private CallbackManager callbackManager;
private LoginButton loginButton;
private ImageButton btnLoginFb;
private ProgressDialog progressDialog;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login = (Button) findViewById(R.id.loginbutton);
signup = (TextView) findViewById(R.id.textViewsignup);
help = (TextView) findViewById(R.id.textViewHelp);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
login.setOnClickListener(this);
signup.setOnClickListener(this);
help.setOnClickListener(this);
Context mContext = this.getApplicationContext();
credentialsProvider = new CognitoCachingCredentialsProvider(
mContext, // get the context for the current activity
"us-east-1:*******************************",
Regions.US_EAST_1
);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginbutton:
email = etUsername.getText().toString();
pass = etPassword.getText().toString();
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
if (email != null && pass != null) {
Intent slideactivity = new Intent(MainActivity.this, Welcome.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
return;
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Oops");
// Setting Dialog Message
alertDialog.setMessage("No data found. You have to signup first!!!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
startActivity(new Intent(MainActivity.this, SignUp.class));
}
});
// Showing Alert Message
alertDialog.show();
}
break;
case R.id.textViewsignup:
Intent slideactivity = new Intent(MainActivity.this, SignUp.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity, bndlanimation);
break;
case R.id.textViewHelp:
Intent slideactivity1 = new Intent(MainActivity.this, LoginHelp.class);
Bundle bndlanimation1 =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animation, R.anim.animation2).toBundle();
startActivity(slideactivity1, bndlanimation1);
break;
}
}
#Override
protected void onResume() {
super.onResume();
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("public_profile", "email", "user_friends");
btnLoginFb = (ImageButton) findViewById(R.id.btnLoginFb);
btnLoginFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
loginButton.performClick();
loginButton.setPressed(true);
loginButton.invalidate();
loginButton.registerCallback(callbackManager, mCallBack);
loginButton.setPressed(false);
loginButton.invalidate();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progressDialog.dismiss();
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.e("response: ", response + "");
try {
user = new User();
user.facebookID = object.getString("id").toString();
pass = user.facebookID;
Log.e(pass, "id");
user.email = object.getString("email").toString();
email = user.email;
Log.e(email, "email");
user.name = object.getString("name").toString();
user.gender = object.getString("gender").toString();
PrefUtils.setCurrentUser(user, MainActivity.this);
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "welcome " + user.name, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
finish();
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
new db().execute("");
}
#Override
public void onCancel() {
progressDialog.dismiss();
}
#Override
public void onError(FacebookException e) {
progressDialog.dismiss();
}
};
#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);
}
private class db extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
Item item = new Item();
mapper.load(Item.class, email, pass);
if(item==null)
{
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
item.setEmail(email);
item.setPass(pass);
mapper.save(item);
startActivity(new Intent(MainActivity.this,Welcome.class));
}
mapper.load(Item.class, email,pass);
if(item==null) {
startActivity(new Intent(MainActivity.this,SignUp.class));
}
else{
startActivity(new Intent(MainActivity.this,Welcome.class));
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Logcat:-
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMappingException: Null key found for public java.lang.String com.ediode.graphics3d.Item.getEmail()
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.getKey(DynamoDBMapper.java:434)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:387)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:466)
at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.load(DynamoDBMapper.java:350)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:339)
at com.ediode.graphics3d.MainActivity$db.doInBackground(MainActivity.java:333)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
            at java.lang.Thread.run(Thread.java:818)
I am stuck on this from 4,5 hours. It would be awesome if anyone can help me this stuff.
Thanks

What does your mapper class look like for item? I'm going to assume you have the email as a hash key with no range key because the login username should be unique. You only need the hash key of the object to load it using the load method. This is assuming that there is no range key.
Try using this.
AmazonDynamoDBClient ddbClient = new AmazonDynamoDBClient(credentialsProvider);
DynamoDBMapper mapper = new DynamoDBMapper(ddbClient);
// Use the password as the third parameter if it is a range key.
Item item = mapper.load(Item.class, email1);
if(item == null){
// That email is not in the database
}
else{
// Does exist in database, now compare password.
}

Related

Web Service doesn’t work when I try to update the android widget if the app is killed

We are developing android widget for Xamarin.Forms application. The widget updates and gets data from the Web Service when the app is in Background, but stops working when the app is killed/closed. I have followed this article for developing this widget -
Xamarin: Android Widget with timer, stops when app killed
I want to Update the widget when the user clicks on Refresh button. If I add hardcoded data for textboxes and click Refresh it updates the time but doesn’t work if I assign web service result data for the textboxes. I have added internet permission in AndroidManifest.xml. Is there a way I can get the data from web service even when the app is closed? Or Probably I am missing some permission?
AppWidget.cs -
public static class WidgetConsts
{
public const string DebugTag = "com.myapp.WIDGET";
public const string ActionWakeup = "com.myapp.WIDGET_WAKEUP";
public const string ActionWidgetUpdate = "android.appwidget.action.APPWIDGET_UPDATE";
public const string ActionWidgetDisabled = "android.appwidget.action.APPWIDGET_DISABLED";
}
[BroadcastReceiver]
[IntentFilter(new string[] { WidgetConsts.ActionWakeup })]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action.Equals(WidgetConsts.ActionWakeup))
{
Log.Debug(WidgetConsts.DebugTag, "Wakeup alarm called");
if (AppWidget.widgetTimer == null)
{
Log.Debug(WidgetConsts.DebugTag, "Widget updating does not run, enforcing update...");
AppWidget.UpdateAppWidget(context);
}
else
{
Log.Debug(WidgetConsts.DebugTag, "Widget updating runs, no action needed");
}
}
}
}
[BroadcastReceiver]
[IntentFilter(new string[] { WidgetConsts.ActionWidgetUpdate})]
[MetaData("android.appwidget.provider", Resource = "#xml/appwidget_provider")]
public class AppWidget : AppWidgetProvider
{
public static System.Timers.Timer widgetTimer = null;
public override void OnUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
RemoteViews views = BuildRemoteViews(context, appWidgetIds);
(AppWidgetManager.GetInstance(Android.App.Application.Context)).UpdateAppWidget(new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(AppWidget))), views);
// appWidgetManager.UpdateAppWidget(appWidgetIds[0], views);
// set timer for updating the widget views each 5 sec
if (widgetTimer == null)
{
widgetTimer = new System.Timers.Timer();
widgetTimer.Interval = 5000;
widgetTimer.Elapsed += OnTimedEvent;
}
widgetTimer.Enabled = true;
// set alarm to wake up the app when killed, each 60 sec
// needs a fresh BroadcastReceiver because AppWidgetProvider.OnReceive is
// not virtual and overriden method in this class would not be called
AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);
Intent ai = new Intent(context, typeof(AlarmReceiver));
ai.SetAction(WidgetConsts.ActionWakeup);
PendingIntent pi = PendingIntent.GetBroadcast(context, 0, ai, PendingIntentFlags.UpdateCurrent);
am.SetRepeating(AlarmType.ElapsedRealtime, 100, 1000 * 60, pi);
}
public override void OnEnabled(Context context)
{
AlarmManager am = (AlarmManager)context.GetSystemService(Context.AlarmService);
Intent ai = new Intent(context, typeof(AlarmReceiver));
ai.SetAction(WidgetConsts.ActionWakeup);
PendingIntent pi = PendingIntent.GetBroadcast(context, 0, ai, PendingIntentFlags.UpdateCurrent);
am.SetRepeating(AlarmType.ElapsedRealtime, 100, 1000 * 60, pi);
base.OnEnabled(context);
}
public override void OnDisabled(Context context)
{
Log.Debug(WidgetConsts.DebugTag, "Disabling the widget");
if (widgetTimer != null)
{
Log.Debug(WidgetConsts.DebugTag, "Stopping timer");
widgetTimer.Enabled = false;
}
else
Log.Debug(WidgetConsts.DebugTag, "Timer is null");
base.OnDisabled(context);
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
Log.Debug(WidgetConsts.DebugTag, "Updating status...");
new Handler(Looper.MainLooper).Post(() =>
{
//Run my code to periodically update the widget
RemoteViews views = new RemoteViews(Android.App.Application.Context.PackageName, Resource.Layout.SnapVertWidget);
AppWidgetManager manager = AppWidgetManager.GetInstance(Android.App.Application.Context);
ComponentName thisWidget = new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(AppWidget)));
int[] appWidgetIds = manager.GetAppWidgetIds(thisWidget);
(AppWidgetManager.GetInstance(Android.App.Application.Context)).UpdateAppWidget(new ComponentName(Android.App.Application.Context, Java.Lang.Class.FromType(typeof(AppWidget))), views);
// manager.UpdateAppWidget(appWidgetIds[0], views);
});
}
static public void UpdateAppWidget(Context context)
{
Intent intent = new Intent(context, typeof(AppWidget));
intent.SetAction(WidgetConsts.ActionWidgetUpdate);
int[] ids = AppWidgetManager.GetInstance(context).GetAppWidgetIds(new ComponentName(context, Java.Lang.Class.FromType(typeof(AppWidget))));
intent.PutExtra(AppWidgetManager.ExtraAppwidgetIds, ids);
context.SendBroadcast(intent);
}
public RemoteViews BuildRemoteViews(Context context, int[] appWidgetIds)
{
xxx.Droid.Services.MyWidget myWidget = new xxx.Droid.Services.MyWidget();
var entry = myWidget.GetData();
// Build an update that holds the updated widget contents
var updateViews = new RemoteViews(context.PackageName, Resource.Layout.SnapVertWidget);
updateViews.SetTextViewText(Resource.Id.txtvwUpdate, Convert.ToString(DateTime.Now));
updateViews.SetTextViewText(Resource.Id.txtvwCityName, entry.Result.CityName);
updateViews.SetTextViewText(Resource.Id.txtvwTemp, entry.Result.TempValue);
//SetTextViewText(widgetView);
RegisterClicks(context, appWidgetIds, updateViews);
return updateViews;
}
private void RegisterClicks(Context context, int[] appWidgetIds, RemoteViews widgetView)
{
Intent intentUpdate = new Intent(context, typeof(AppWidget));
intentUpdate.SetAction(AppWidgetManager.ActionAppwidgetUpdate);
//Update the current widget instance only, by creating an array that contains the widget’s unique ID//
int[] idArray = new int[] { appWidgetIds[0] };
intentUpdate.PutExtra(AppWidgetManager.ExtraAppwidgetIds, idArray);
PendingIntent pendingUpdate = PendingIntent.GetBroadcast(
context, appWidgetIds[0], intentUpdate,
PendingIntentFlags.UpdateCurrent);
widgetView.SetOnClickPendingIntent(Resource.Id.btnRefresh, pendingUpdate);
Intent launchAppIntent = new Intent(context, typeof(MainActivity));
PendingIntent launchAppPendingIntent = PendingIntent.GetActivity(context, 0, launchAppIntent, PendingIntentFlags.UpdateCurrent);
widgetView.SetOnClickPendingIntent(Resource.Id.pnlWeather, launchAppPendingIntent);
}
}

unable to login as secondary custom user manager in wso2 IS 5.9

in WSO2 IS 5.9,
a)i created a CustomeruserStoreManager and placed in drop-ins and along with mysql driver i lib lib folder,
b)I cud see the users from my custom usertable, created a internal and gave all permissions and assigned the 2 users test.com/dinuka and test.com.malinda to new role created.
c)In the login page i can login as admin/admin but unable to login as test.com/dinuka-dinuka, I get the error as
[2020-02-18 11:03:36,781] [cf46aae7-eb2b-4eeb-9683-e7adbbba5c1f] ERROR {org.wso2.carbon.core.services.authentication.AuthenticationAdmin} - System error while Authenticating/Authorizing User : Error when handling event : PRE_AUTHENTICATION
I have disabled the claims as well,,
public class CustomUserStoreConstants {
//Properties for Read Active Directory User Store Manager
public static final ArrayList<Property> CUSTOM_UM_MANDATORY_PROPERTIES = new ArrayList<Property>();
public static final ArrayList<Property> CUSTOM_UM_OPTIONAL_PROPERTIES = new ArrayList<Property>();
public static final ArrayList<Property> CUSTOM_UM_ADVANCED_PROPERTIES = new ArrayList<Property>();
static {
setMandatoryProperty(JDBCRealmConstants.DRIVER_NAME, "Driver Name", "", "Full qualified driver name");
setMandatoryProperty(JDBCRealmConstants.URL,"Connection URL", "", "URL of the user store database");
setMandatoryProperty(JDBCRealmConstants.USER_NAME, "User Name","", "Username for the database");
setMandatoryProperty(JDBCRealmConstants.PASSWORD, "Password","", "Password for the database");
setProperty(UserStoreConfigConstants.disabled,"Disabled", "false", UserStoreConfigConstants.disabledDescription);
setProperty("ReadOnly","Read Only", "true", "Indicates whether the user store of this realm operates in the user read only mode or not");
setProperty(UserStoreConfigConstants.SCIMEnabled,"SCIM Enabled", "false", UserStoreConfigConstants.SCIMEnabledDescription);
//Advanced Properties (No descriptions added for each property)
setAdvancedProperty("SelectUserSQL","Select User SQL", "SELECT * FROM CUSTOMER_DATA WHERE CUSTOMER_NAME=?", "");
setAdvancedProperty("UserFilterSQL","User Filter SQL", "SELECT CUSTOMER_NAME FROM CUSTOMER_DATA WHERE CUSTOMER_NAME LIKE ? ORDER BY CUSTOMER_ID", "");
setAdvancedProperty("ClaimOperationsSupported","Claim Operations Supported","false","");
}
private static void setProperty(String name, String displayName, String value, String description) {
Property property = new Property(name, value, displayName + "#" +description, null);
CUSTOM_UM_OPTIONAL_PROPERTIES.add(property);
}
private static void setMandatoryProperty(String name, String displayName, String value, String description) {
Property property = new Property(name, value, displayName + "#" +description, null);
CUSTOM_UM_MANDATORY_PROPERTIES.add(property);
}
private static void setAdvancedProperty(String name, String displayName, String value, String description) {
Property property = new Property(name, value, displayName + "#" +description, null);
CUSTOM_UM_ADVANCED_PROPERTIES.add(property);
}
}
public class CustomUserStoreManager extends JDBCUserStoreManager {
private static Log log = LogFactory.getLog(CustomUserStoreManager.class);
public CustomUserStoreManager() {
}
public CustomUserStoreManager(org.wso2.carbon.user.api.RealmConfiguration realmConfig,
Map<String, Object> properties,
ClaimManager claimManager,
ProfileConfigurationManager profileManager,
UserRealm realm, Integer tenantId)
throws UserStoreException {
super(realmConfig, properties, claimManager, profileManager, realm, tenantId, false);
}
#Override
public boolean doAuthenticate(String userName, Object credential) throws UserStoreException {
System.out.println("TRYING TO LOGIN HERE ");
if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(userName)) {
log.error("Anonymous user trying to login");
return false;
}
Connection dbConnection = null;
ResultSet rs = null;
PreparedStatement prepStmt = null;
String sqlstmt = null;
String password = (String) credential;
boolean isAuthed = false;
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
//paring the SELECT_USER_SQL from user_mgt.xml
sqlstmt = realmConfig.getUserStoreProperty(JDBCRealmConstants.SELECT_USER);
if (log.isDebugEnabled()) {
log.debug(sqlstmt);
}
prepStmt = dbConnection.prepareStatement(sqlstmt);
prepStmt.setString(1, userName);
rs = prepStmt.executeQuery();
if (rs.next()) {
String storedPassword = rs.getString(2);
if ((storedPassword != null) && (storedPassword.trim().equals(password))) {
isAuthed = true;
}
}
} catch (SQLException e) {
throw new UserStoreException("Authentication Failure. Using sql :" + sqlstmt);
} finally {
DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
}
if (log.isDebugEnabled()) {
log.debug("User " + userName + " login attempt. Login success :: " + isAuthed);
}
return isAuthed;
}
#Override
public Date getPasswordExpirationTime(String userName) throws UserStoreException {
return null;
}
protected boolean isValueExisting(String sqlStmt, Connection dbConnection, Object... params)
throws UserStoreException {
PreparedStatement prepStmt = null;
ResultSet rs = null;
boolean isExisting = false;
boolean doClose = false;
try {
if (dbConnection == null) {
dbConnection = getDBConnection();
doClose = true; //because we created it
}
if (DatabaseUtil.getStringValuesFromDatabase(dbConnection, sqlStmt, params).length > 0) {
isExisting = true;
}
return isExisting;
} catch (SQLException e) {
log.error(e.getMessage(), e);
log.error("Using sql : " + sqlStmt);
throw new UserStoreException(e.getMessage(), e);
} finally {
if (doClose) {
DatabaseUtil.closeAllConnections(dbConnection, rs, prepStmt);
}
}
}
public String[] getUserListFromProperties(String property, String value, String profileName)
throws UserStoreException {
return new String[0];
}
/*#Override
public Map<String, String> doGetUserClaimValues(String userName, String[] claims,
String domainName) throws UserStoreException {
return new HashMap<String, String>();
}*/
/*#Override
public String doGetUserClaimValue(String userName, String claim, String profileName)
throws UserStoreException {
return null;
}*/
#Override
public boolean isReadOnly() throws UserStoreException {
return true;
}
#Override
public void doAddUser(String userName, Object credential, String[] roleList,
Map<String, String> claims, String profileName,
boolean requirePasswordChange) throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
public void doAddRole(String roleName, String[] userList, org.wso2.carbon.user.api.Permission[] permissions)
throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doDeleteRole(String roleName) throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doDeleteUser(String userName) throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public boolean isBulkImportSupported() {
return false;
}
#Override
public void doUpdateRoleName(String roleName, String newRoleName) throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers)
throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doSetUserClaimValue(String userName, String claimURI, String claimValue,
String profileName) throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doSetUserClaimValues(String userName, Map<String, String> claims,
String profileName) throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doDeleteUserClaimValue(String userName, String claimURI, String profileName)
throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doDeleteUserClaimValues(String userName, String[] claims, String profileName)
throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
#Override
public void doUpdateCredentialByAdmin(String userName, Object newCredential)
throws UserStoreException {
throw new UserStoreException(
"User store is operating in read only mode. Cannot write into the user store.");
}
public String[] getExternalRoleListOfUser(String userName) throws UserStoreException {
/*informix user store manager is supposed to be read only and users in the custom user store
users in the custom user store are only assigned to internal roles. Therefore this method
returns an empty string.
*/
return new String[0];
}
#Override
public String[] doGetRoleNames(String filter, int maxItemLimit) throws UserStoreException {
return new String[0];
}
#Override
public boolean doCheckExistingRole(String roleName) throws UserStoreException {
return false;
}
#Override
public boolean doCheckExistingUser(String userName) throws UserStoreException {
return true;
}
#Override
public org.wso2.carbon.user.api.Properties getDefaultUserStoreProperties(){
Properties properties = new Properties();
properties.setMandatoryProperties(CustomUserStoreConstants.CUSTOM_UM_MANDATORY_PROPERTIES.toArray
(new Property[CustomUserStoreConstants.CUSTOM_UM_MANDATORY_PROPERTIES.size()]));
properties.setOptionalProperties(CustomUserStoreConstants.CUSTOM_UM_OPTIONAL_PROPERTIES.toArray
(new Property[CustomUserStoreConstants.CUSTOM_UM_OPTIONAL_PROPERTIES.size()]));
properties.setAdvancedProperties(CustomUserStoreConstants.CUSTOM_UM_ADVANCED_PROPERTIES.toArray
(new Property[CustomUserStoreConstants.CUSTOM_UM_ADVANCED_PROPERTIES.size()]));
return properties;
}
}
#Component(
name = "com.wso2.carbon.custom.user.store.manager",
immediate = true
)
public class CustomUserStoreMgtDSComponent {
private static Log log = LogFactory.getLog(CustomUserStoreMgtDSComponent.class);
private static RealmService realmService;
#Activate
protected void activate(ComponentContext ctxt) {
try {
CustomUserStoreManager customUserStoreManager = new CustomUserStoreManager();
ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), customUserStoreManager, null);
log.info("CustomUserStoreManager bundle activated successfully..");
} catch (Throwable storeError) {
log.error("ERROR when activating Custom User Store", storeError);
}
}
#Deactivate
protected void deactivate(ComponentContext ctxt) {
System.out.println(" !!! DEACTIVATE COMP !!!");
if (log.isDebugEnabled()) {
log.debug("Custom User Store Manager is deactivated ");
}
}
#Reference(
name = "RealmService",
service = org.wso2.carbon.user.core.service.RealmService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetRealmService")
protected void setRealmService(RealmService realmService) {
realmService = realmService;
}
protected void unsetRealmService(RealmService realmService) {
realmService = null;
}
}

On using swipe refresh in recyclerview my adapter is not getting data when it is refreshing

My Latest fragment
public class Latest extends Fragment {
private RecyclerView recyclerLatest;
private SwipeRefreshLayout swipeRecycler;
private RecyclerView.LayoutManager mLayoutManager;
private List<LatestAdDetails> latestAdDetailsList = new ArrayList<>();
private LatestAdapter latestAdapter;
private LatestAdDetails latestAdDetails,latestAdDetails1;
private JSONObject jsonobject;
private Context context;
private String x;
public Latest() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView=inflater.inflate(R.layout.latest_fragment,container,false);
recyclerLatest = (RecyclerView) mainView.findViewById(R.id.recycler_latest);
swipeRecycler= (SwipeRefreshLayout)mainView.findViewById(R.id.swipe_recycler_latest);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerLatest.setLayoutManager(mLayoutManager);
recyclerLatest.setHasFixedSize(true);
context = getContext();
// url for latest add obtaining
UrlConstants.latest_ad_obtained= UrlConstants.latest_ad+ AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+AppController.getString(getActivity().getApplicationContext(),"city_id");
latestAdapter = new LatestAdapter(latestAdDetailsList);
recyclerLatest.setAdapter(latestAdapter);
latestAdd();
swipeRecycler.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(){refreshLatestAd();
}
});
return mainView;
}
private void refreshLatestAd() {
UrlConstants.latset_ad_refresh_obtained=UrlConstants.latest_ad_refresh+
AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"city_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"refresh_ad")+"/"+0;
LatestRefreshHandler latestRefreshHandler = new LatestRefreshHandler("latestRefreshADD");
latestRefreshHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
latestAdapter.clear();
int Ad_id_refresh = jsonarray.getJSONObject(jsonarray.length()).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.addAll(latestAdDetailsList);
latestAdapter.notifyDataSetChanged();
recyclerLatest.setAdapter(latestAdapter);
swipeRecycler.setRefreshing(false);
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}
private void latestAdd() {
LatestRequestHandler latestHandler = new LatestRequestHandler("latestADD");
latestHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
int Ad_id_refresh = jsonarray.getJSONObject(1).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.notifyDataSetChanged();
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}}
my Adapter class
public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.MyViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String text;
private List<LatestAdDetails> latestAddDetailsList;
public LatestAdapter(List<LatestAdDetails> latestAddDetailsList) {
this.latestAddDetailsList = latestAddDetailsList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle, txtDescription, txtCityName, txtPrice, txtCategory, txtHour, txtPhotoNo;
private NetworkImageView imgPhoto;
public MyViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_fad);
txtDescription = (TextView) itemView.findViewById(R.id.description_fad);
txtCityName = (TextView) itemView.findViewById(R.id.city_name_fad);
txtPrice = (TextView) itemView.findViewById(R.id.price_fad);
txtCategory = (TextView) itemView.findViewById(R.id.category_fad);
txtHour = (TextView) itemView.findViewById(R.id.hours_fad);
txtPhotoNo = (TextView) itemView.findViewById(R.id.txt_photo_no_fad);
imgPhoto = (NetworkImageView) itemView.findViewById(R.id.img_photo_lod_fad);
}
}
public void clear() {
latestAddDetailsList.clear();
notifyDataSetChanged();
}// Add a list of items
public void addAll(List<LatestAdDetails> list) {
latestAddDetailsList.addAll(list);
notifyDataSetChanged();
}
#Override
public LatestAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.featured_ad_adapter_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(LatestAdapter.MyViewHolder holder, int position) {
LatestAdDetails latestAddDetails = latestAddDetailsList.get(position);
holder.txtTitle.setText(translate(latestAddDetails.getTitle()));
holder.txtDescription.setText(translate(latestAddDetails.getDescription()));
holder.txtCityName.setText(translate(latestAddDetails.getCityName()));
holder.txtPrice.setText(Integer.toString(latestAddDetails.getPrice()));
holder.txtCategory.setText(translate(latestAddDetails.getCategoryName()));
holder.txtHour.setText(Integer.toString(latestAddDetails.getCreated()));
holder.txtPhotoNo.setText(Integer.toString(0) + " photos ");
try {
imageLoader = VolleyHandler.getImageLoader();
} catch (Exception e) {
e.printStackTrace();
}
holder.imgPhoto.setImageUrl(latestAddDetails.getDefault_photo(), imageLoader);
}
#Override
public int getItemCount() {
Log.e("size", String.valueOf(latestAddDetailsList.size()));
return latestAddDetailsList.size();
}
private String translate(String myString) {
try {
myString = myString.replace("\n", "").replace("\r", "");
byte[] utf8Bytes = myString.getBytes("UTF8");
text = new String(utf8Bytes, "UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return text;
}}
on refreshing adapter size is zero,but getting json correctly,but not adding to adapter,and the recycler view is not showing new data,please help me ,the json is giving 10 datas on every swipe but it is not getting added to recyclerview
It seems like a logical bug :
In method : refreshLatestAd(), Remove these line :
latestAdapter.clear();
latestAdapter.addAll(latestAdDetailsList);
and
recyclerLatest.setAdapter(latestAdapter); // It need not be set again.
Let me know if it helps.
latestAdapter.notifyDataSetChanged() is sufficient to notify the
adapter that the data is changed. Always modify the list
[latestAdDetailsList] which is being set to adapter, this is the sure
shot way to make the changes reflect when you call notifyDataSetChanged.

Change Activity into Fragment

I am quite new at Android.
So I am a bit confused of working with fragments.
I have found a very great tutorial.
So I have working code. But it is the layout oft a normal activity.
Then I tried to include it into a navigation drawer.
So the list view with data will only be shown when the menu item has been selected.
On the fragment View there is a never ending loading Dialog.
While debugging I have figured out that the code loads still the data and inserts it into feedItems.
So feedItems is filled correctly.
Now after listAdapter.notifyDataSetChanged() there happens nothing.
So here that is my code:
public class FragmentNews extends ListFragment {
private static final String TAG = FragmentNews.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://address.com";
public FragmentNews(){}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
loadDataForNews();
}
private void loadDataForNews(){
listView = this.getListView();
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
// List View Feed
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);
feedItems.add(item);
}
// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Can the problem be that the inflater of listAdapter is null?
Thanks for help!
Sometimes listAdapter.notifyDataSetChanged() does not work properly.
Try removing
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
from loadDataForNews() and adding in
place of listAdapter.notifyDataSetChanged();

how can add list to a fragment of pageindicator?

i want to add list view to one page of pageindicator the code oof page indicator is :
public class VpiAbsTestActivity extends SherlockFragmentActivity {
private static final String[] CONTENT = new String[] { "This", "Is", "A", "ViewPager", "Demo" };
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu subMenu1 = menu.addSubMenu("Action Item");
subMenu1.add(0,15, 0, "Sample");
subMenu1.add(0,20, 0,"Menu");
subMenu1.add("Items");
MenuItem subMenu1Item = subMenu1.getItem();
subMenu1Item.setIcon(R.drawable.ic_title_share_default);
subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
SubMenu subMenu2 = menu.addSubMenu("Overflow Item");
subMenu2.add("These");
subMenu2.add("Are");
subMenu2.add("Sample");
subMenu2.add("Items");
MenuItem subMenu2Item = subMenu2.getItem();
subMenu2Item.setIcon(R.drawable.ic_compose);
subMenu2Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case 10:
Toast.makeText(VpiAbsTestActivity.this, "Now "+item.getItemId(), Toast.LENGTH_SHORT).show();
return true;
case 15:
Toast.makeText(VpiAbsTestActivity.this, "Now = "+item.getItemId(), Toast.LENGTH_SHORT).show();
return true;
case 20:
Toast.makeText(VpiAbsTestActivity.this, "Now == "+item.getItemId(), Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
class TestFragmentAdapter extends FragmentPagerAdapter {
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(String.valueOf(position));
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position];
}
}
}
i want to add a list view to page one for example this list but i cant write a list fragment for this code please tel me what i do
public static final String[] list = new String[]{"France", "London", "Sweden"};
what can I do ?
First of all you have to understand what is a Fragment and how to instantiate it and how to send to it data (you should look the guide dedicated to Fragments and the documentation for Fragments here).
Then you have to do 2 things :
Create your custom list fragment, I suggest you to look at the android documentation of ListFragment and create a class that inherits from ListFragment.
public class CustomListFragment extends ListFragment {
// your code here to add content
}
Modify your TestFragmentAdapter to instanciate your new CustomListFragment when you are in the first page (see example below)
public class TestFragmentAdapter
extends FragmentPagerAdapter
{
protected final Class[] CONTENT_CLASSES = new Class[] { CustomListFragment.class, TestFragment.class};
protected final String[] CONTENT_TITLES = new String[] { "List", "Test"};
public TabAdapter( FragmentManager manager, Activity context )
{
super( manager );
this.context = context;
}
#Override
public Fragment getItem( int i )
{
Class targetFragmentClass = CONTENT_CLASSES[i];
Bundle args = new Bundle();
// add your args here
Fragment targetFragment = Fragment.instantiate( context, targetFragmentClass.getName(), args );
return targetFragment;
}
#Override
public int getCount()
{
return CONTENT_CLASSES.length;
}
#Override
public CharSequence getPageTitle( int position )
{
return CONTENT_TITLES[i];
}
}