I have an app that shows notification in a listview. I want these notifications to be saved so that if I open the app and see notification I can see these notifications again when I close the app and then open it. I tried this
but nothing was saved.
Another major question is how can I run this app in background? So if notification is received the app lists that notification in the listview without being opened?
My Code
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
if (pack.contains("fake")){
try {
// remotePackageContext = getApplicationContext().createPackageContext(pack, 0);
// Drawable icon = remotePackageContext.getResources().getDrawable(id);
// if(icon !=null) {
// ((ImageView) findViewById(R.id.imageView)).setBackground(icon);
// }
byte[] byteArray = intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if (byteArray != null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
if(text.contains("") && !text.contains(" messages")) {
model.setName(title + ": " + text);
model.setImage(bmp);
if (modelList != null) {
modelList.add(model);
adapter.notifyDataSetChanged();
} else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
Make a class Cache which has the capabilities to serialize and deserialize data.
public class Cache {
private static Cache CACHE;
public static Cache get() {
if (!SharedPreferencesHelper.isCacheAvailable()) {
CACHE = new Cache();
SharedPreferencesHelper.saveCache(CACHE);
} else {
CACHE = SharedPreferencesHelper.getCache();
}
return CACHE;
}
ArrayList<Taxonomy> cachedTaxonomies;
public Cache() {
cachedTaxonomies = new ArrayList<Taxonomy>();
}
public ArrayList<Taxonomy> getCachedTaxonomies() {
return cachedTaxonomies;
}
public static String serialize(Cache cache) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
return gson.toJson(cache);
}
public static Cache deserialize(String json) {
Type type = new TypeToken<Cache>() {
}.getType();
return new Gson().fromJson(json, type);
}
public void update() {
SharedPreferencesHelper.saveCache(this);
}
}
Here Taxonomy is a model.
Below is the class which helps you save in SharedPrefs
public class SharedPreferencesHelper {
private static final String PREFS_CACHE = "prefs_cache";
public static SharedPreferences getSharedPreferences() {
return SpreeApplication.getSharedPreferences();
}
// Cache -------------------------------------
public static boolean isCacheAvailable() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return false;
} else {
return true;
}
}
public static Cache getCache() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return null;
} else {
return Cache.deserialize(json);
}
}
public static void saveCache(Cache cache) {
saveString(PREFS_CACHE, Cache.serialize(cache));
}
// -----------------------------------------------------
private static void saveString(String prefKey, String value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putString(prefKey, value);
prefEditor.commit();
}
private static void saveBoolean(String prefKey, boolean value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putBoolean(prefKey, value);
prefEditor.commit();
}
}
To save write this :
List<Taxonomy> taxonomies = new ArrayList<Taxonomy>();
Cache cache = Cache.get();
cache.getCachedTaxonomies().clear();
cache.getCachedTaxonomies().addAll(taxonomies);
SharedPreferencesHelper.saveCache(cache);
this is my spreeapplication class which is a custom application class
Remember you have to mention in manifest if you create a custom application class
public class SpreeApplication extends Application{
private final static String DEFAULT_PREFERENCES = "spree";
private static SharedPreferences sharedPreferences;
private static Context applicationContext;
#Override
public void onCreate() {
super.onCreate();
applicationContext = this;
sharedPreferences = getSharedPreferences(DEFAULT_PREFERENCES, Context.MODE_PRIVATE);
}
public static SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
public static SharedPreferences.Editor getSharedPreferencesEditor() {
return sharedPreferences.edit();
}
public static Context getContext() {
return applicationContext;
}
}
Related
I am trying when press favorite button saving Object to SharedPreferences I have done it but When I press again favorite button to Remove Object to SharedPreferences I can't do this, I got old Objects without removed Objects I shared below used code for this process.How can I do this?
Saving and Removing to Favorite Object
String tag = holder.order.getTag().toString();
if (tag.equalsIgnoreCase("deactive")) {
//order_models.add(new RetroPhoto(1,dataList.get(position).getSurname(),dataList.get(position).getName()));
sharedPreference.addFavorite(context, dataList.get(position));
//dataList.get(position).getName();
holder.order.setTag("active");
holder.order.setImageResource(R.drawable.ic_favorite);
} else {
sharedPreference.removeFavorite(context, dataList.get(position));
//dataList.get(position).getName();
//dataList.remove(dataList.get(position));
holder.order.setTag("deactive");
holder.order.setImageResource(R.drawable.ic_favorite_outline);
}
public class SharedPreference {
public static final String PREFS_NAME = "NKDROID_APP";
public static final String FAVORITES = "Favorite";
public SharedPreference() {
super();
}
public void storeFavorites(Context context, List<RetroPhoto> favorites){
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public ArrayList<RetroPhoto> loadFavorites(Context context) {
SharedPreferences settings;
List<RetroPhoto> favorites;
settings =
context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
RetroPhoto[] favoriteItems =
gson.fromJson(jsonFavorites,RetroPhoto[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<RetroPhoto>(favorites);
} else
return null;
return (ArrayList<RetroPhoto>) favorites;
}
public void addFavorite(Context context, RetroPhoto beanSampleList) {
List<RetroPhoto> favorites = loadFavorites(context);
if (favorites == null){
favorites = new ArrayList<RetroPhoto>();
}
favorites.add(beanSampleList);
storeFavorites(context, favorites);
}
public void removeFavorite(Context context, RetroPhoto beanSampleList) {
ArrayList<RetroPhoto> favorites = loadFavorites(context);
if (favorites != null) {
favorites.remove(beanSampleList);
storeFavorites(context, favorites);
}
}
}
Getting Update LoadSharedPreferences
#Override
protected void onResume() {
super.onResume();
Log.e("onResume", "onResume Called");
if(order_models != null ) {
try {order_models = sharedPreference.loadFavorites(getApplicationContext());
order_adapter = new OrderAdapter(getApplicationContext(), order_models);
recycle.setAdapter(order_adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
order_adapter.notifyDataSetChanged();
}
}
you actually just add item in SharedPreference and remove item just from your array.
for removing item from SharedPreference you should use this code
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preferences.edit().remove("key").apply();
I have three activities, I capture all data but one from DetailActivity upon button click and save in database using Room; My intention is to insert all these data into the database and start ReviewActivity so as to get the arraylist of reviews and also insert it in the database. Everything seems to work fine until when I want to view review offline because I believe it has been saved, reviews does not get loaded.
This is my DetailActivity,
TextView overview_tv; ImageView image_tv; TextView name_tv; TextView ratings; Context context; TextView release_date; ImageView backdrop_poster; private ExpandableHeightListView trailers; public static ArrayList<Youtube> youtube; public static ArrayList<Review> reviews; TrailerViewAdapter adapter; public static DataObject data; DataObject dataObject; ArrayList<Review> savedReview; private static final String IMAGE_URL = "http://image.tmdb.org/t/p/w185/"; private static final String THE_MOVIEDB_URL2 = "https://api.themoviedb.org/3/movie/"; private static final String MOVIE_QUERY2 = "api_key"; private static final String API_KEY2 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY2 = "videos"; public static int movieId; Button viewReviews; Button favourite; String movieRating; private static final int YOUTUBE_SEARCH_LOADER = 23; private static final int REVIEW_SEARCH_LOADER = 24; File file; String name; String overview; String releaseDate; int switcher; public static ArrayList<Review> favouriteReviews; TextView trev; AppDatabase mDb; //Navigation arrow on the action bar #Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } return super.onOptionsItemSelected(item); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); mDb = AppDatabase.getInstance(getApplicationContext()); youtube = new ArrayList<Youtube>(); reviews = new ArrayList<Review>(); adapter = new TrailerViewAdapter(this, youtube); //Credit to Paolorotolo #github trailers = findViewById(R.id.expandable_list); trailers.setAdapter(adapter); trailers.setExpanded(true); //Navigation arrow on the acton bar; check also override onOptionsItemSelected ActionBar actionBar = this.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } context = getApplicationContext(); Intent intent = getIntent(); if (intent == null) { closeOnError(); } switcher = getIntent().getIntExtra("switch", 3); overview_tv = findViewById(R.id.overview); image_tv = findViewById(R.id.image); name_tv = findViewById(R.id.name); ratings = findViewById(R.id.ratings); release_date = findViewById(R.id.release_date); backdrop_poster = findViewById(R.id.backdrop_poster); trev = findViewById(R.id.review_show); viewReviews = findViewById(R.id.review_button); favourite = findViewById(R.id.favourite_button); addListenerOnRatingBar(ratings); if (switcher != 2) { favourite.setVisibility(View.INVISIBLE); dataObject = (DataObject) getIntent().getParcelableExtra("array"); final String favouriteName = dataObject.getName(); final String favouriteOverview = dataObject.getOverview(); final String favouriteReleaseDate = dataObject.getReleaseDate(); ArrayList<Youtube> savedTrailer = dataObject.getTrailers(); savedReview = dataObject.getMovieReviews(); movieRating = dataObject.getRating(); name_tv.setText(favouriteName); overview_tv.setText(favouriteOverview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + favouriteReleaseDate);// Toast.makeText(this, "Testing Reviews " + savedReview.get(0).getAuthor(), Toast.LENGTH_SHORT).show(); String imagePath = name_tv.getText().toString() + "0i"; String backdropPath = name_tv.getText().toString() + "1b"; try { DataObjectAdapter.downloadImage(imagePath, image_tv, this); } catch (Exception e) { e.printStackTrace(); } try { DataObjectAdapter.downloadImage(backdropPath, backdrop_poster, context); } catch (Exception e) { e.printStackTrace(); } if (savedTrailer != null) { TrailerViewAdapter lv = new TrailerViewAdapter(DetailActivity.this, savedTrailer); trailers.setAdapter(lv); switcher = 3; } } else { name = getIntent().getStringExtra("Name"); overview = getIntent().getStringExtra("Overview"); final String image = getIntent().getStringExtra("Image"); movieId = getIntent().getIntExtra("movieId", 1); final String backdrop = getIntent().getStringExtra("backdrop"); releaseDate = getIntent().getStringExtra("releaseDate"); movieRating = getIntent().getStringExtra("rating"); Log.i("this", "switch " + switcher); name_tv.setText(name); overview_tv.setText(overview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + releaseDate); //load backdrop poster Picasso.with(context) .load(IMAGE_URL + backdrop) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(backdrop_poster); Picasso.with(context) .load(IMAGE_URL + image) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(image_tv); getSupportLoaderManager().initLoader(YOUTUBE_SEARCH_LOADER, null, this); //getSupportLoaderManager().initLoader(REVIEW_SEARCH_LOADER, null, this); //loadTrailers(); //loadReviews(); //populateKeys(); } /** * Here manages the views(list) for reviews */ viewReviews.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { if (switcher == 3) { startActivity(new Intent(DetailActivity.this, ReviewActivity.class) .putExtra("switch", 3)); } else { Log.i("this", "I am from initial" + switcher); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId)); } } } ); favourite.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { data = new DataObject(); data.setName(name); data.setOverview(overview); data.setRating(movieRating); data.setReleaseDate(releaseDate); data.setTrailers(youtube);// data.setMovieReviews(reviews); try { saveImage(name_tv.getText().toString() + "0i", image_tv); saveImage(name_tv.getText().toString() + "1b", backdrop_poster); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(context, "The movie is saved as a favourite", Toast.LENGTH_LONG).show(); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { mDb.dataDao().insertData(data); } }); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId) .putExtra(ReviewActivity.EXTRA_DATA_ID, 20)); } } ); }
And my ReviewActivity
public class ReviewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<Review>>{ public static ArrayList<Review> reviews; public static List<DataObject> favouriteReviews; public static RecyclerView reviewList; ArrayList<Review> r; private static final int REVIEW_SEARCH_LOADER = 24; private static final String MOVIE_QUERY3 = "api_key"; private static final String API_KEY3 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY3 = "reviews"; private static final String THE_MOVIEDB_URL3 = "https://api.themoviedb.org/3/movie/"; private static int movId; public static final String EXTRA_DATA_ID = "extraDataId"; private static final int DEFAULT_TASK_ID = -1; private int mTaskId = DEFAULT_TASK_ID; DataObject data1; AppDatabase mDb; ReviewAdapter revAdapter; int loaderSwitch; #Override protected void onResume() { super.onResume(); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); mDb = AppDatabase.getInstance(getApplicationContext()); reviews = new ArrayList<Review>(); favouriteReviews = new ArrayList<DataObject>(); reviewList = findViewById(R.id.review_list); LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); reviewList.setLayoutManager(layoutManager); reviewList.setHasFixedSize(true); int switcher = getIntent().getIntExtra("switch", 1); Intent intent = getIntent(); if (intent == null) { finish(); } Log.i("this", "swithcer " + switcher); Log.i("this loader", "Loader " + loaderSwitch); if (switcher == 3){ DataObject dataObject = (DataObject) getIntent().getParcelableExtra("ArrayOfReviews"); if (dataObject != null){ ArrayList<Review> movieReviews = dataObject.getMovieReviews(); Toast.makeText(this, "There are reviews saved", Toast.LENGTH_LONG).show(); revAdapter = new ReviewAdapter(this, movieReviews ); reviewList.setAdapter(revAdapter); } } else { movId = getIntent().getIntExtra("id", 20); revAdapter = new ReviewAdapter(this, reviews); reviewList.setAdapter(revAdapter); loadReviews(); //populateReview(); } DividerItemDecoration decoration = new DividerItemDecoration(this, VERTICAL); reviewList.addItemDecoration(decoration); } #Override protected void onStart() { super.onStart(); //loadReviews(); } public static URL buildUrl3(String stringUrl) { Uri uri = Uri.parse(THE_MOVIEDB_URL3).buildUpon() .appendPath(stringUrl) .appendPath(SEARCH_QUERY3) .appendQueryParameter(MOVIE_QUERY3, API_KEY3) .build(); URL url = null; try { url = new URL(uri.toString()); } catch (MalformedURLException exception) { Log.e(TAG, "Error creating URL", exception); } return url; } public void loadReviews(){ // COMPLETED (19) Create a bundle called queryBundle Bundle queryBundle = new Bundle(); // COMPLETED (20) Use putString with SEARCH_QUERY_URL_EXTRA as the key and the String value of the URL as the value// queryBundle.putString(SEARCH_QUERY_URL_EXTRA, url.toString()); // COMPLETED (21) Call getSupportLoaderManager and store it in a LoaderManager variable LoaderManager loaderManager = getSupportLoaderManager(); // COMPLETED (22) Get our Loader by calling getLoader and passing the ID we specified Loader<ArrayList<Review>> movieReviews = loaderManager.getLoader(REVIEW_SEARCH_LOADER); // COMPLETED (23) If the Loader was null, initialize it. Else, restart it. if (movieReviews == null) { loaderManager.initLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } else { loaderManager.restartLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } } #Override public Loader<ArrayList<Review>> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<ArrayList<Review>>(this) { #Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } #Override public ArrayList<Review> loadInBackground() { String g = String.valueOf(movId); // Create URL object URL url = buildUrl3(g); // Perform HTTP request on the URL and receive a JSON response back String jsonResponse = ""; try { jsonResponse = getResponseFromHttpUrl(url); } catch (Exception e) { e.printStackTrace(); } reviews = MovieJsonUtils.parseReview(jsonResponse); return reviews; } }; } #Override public void onLoadFinished(Loader<ArrayList<Review>> loader, ArrayList<Review> dat) { if (reviews != null) { Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_DATA_ID)) { //mButton.setText(R.string.update_button); if (mTaskId == DEFAULT_TASK_ID) { mTaskId = intent.getIntExtra(EXTRA_DATA_ID, DEFAULT_TASK_ID); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { data.setMovieReviews(reviews); mDb.dataDao().updateData(data); //mDb.dataDao().insertData(data); final List<DataObject> task = mDb.dataDao().loadById(mTaskId); runOnUiThread(new Runnable() { #Override public void run() { populateUI(task); } }); } }); } } else { ReviewAdapter lv = new ReviewAdapter(ReviewActivity.this, reviews); reviewList.setAdapter(lv); } } } #Override public void onLoaderReset(Loader<ArrayList<Review>> loader) { }
Data gets loaded from MainActivity, the saved data is passed on to other activities as a parcellable bundle via intent, the passed data is displayed in DetailActivity but not in ReviewActivity.
Alternatively, if I can load reviews alongside YouTube keys from DetailActivity, I believe I can handle the database issue from there, but two Loaders wouldn't just work together, the app crashes; I am aware two AsyncTasks concurrently run together solved this problem, but I prefer to use Loaders because of performance on configuration change
I am getting the default text and not the actual text saved when trying to access a shared preference. I have tested that it returns true when saving so I am pretty sure the problem is in reading from the preference file.
The preference class
public class SaveWarningMessage : Activity
{
private ISharedPreferences myPref;
private ISharedPreferencesEditor myPrefEditor;
private Context myContext;
public void MyAppPref(Context context)
{
this.myContext = context;
myPref = PreferenceManager.GetDefaultSharedPreferences(myContext);
myPrefEditor = myPref.Edit();
}
public void SaveString(string text)
{
myPrefEditor.PutString("warning text", text);
var returnValue = myPrefEditor.Commit();
}
public string GetString()
{
return myPref.GetString("warning text", "could not get pref");
}
}
}
The class saving the preference:
string warningText = Intent.GetStringExtra("warningText");
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
classInstans.SaveString(warningText);
The class reading from the preference:
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
string message = classInstans.GetString();
Personally I would not subclass it from Activity(?) and use the .actor to instance your ISharedPreferences, along with a few other changes you end up with this example.
Example:
public class SaveWarningMessage
{
public const string WARNINGTEXT = "warning text";
ISharedPreferences myPref;
public SaveWarningMessage(Context context)
{
myPref = PreferenceManager.GetDefaultSharedPreferences(context);
}
public void SaveString(string text)
{
var myPrefEditor = myPref.Edit();
myPrefEditor.PutString(WARNINGTEXT, text);
if (!myPrefEditor.Commit())
{
Log.Error("SomeTag", $"Saving {text} to Pref:{WARNINGTEXT} failed");
}
// Or replace the Commit & check of return the following
// if you do not care about checking the return value
// myPrefEditor.Apply();
}
public string GetString()
{
return myPref.GetString(WARNINGTEXT, "could not get pref");
}
}
Then you can you it like this:
string warningText = "SomeStringToSave";
SaveWarningMessage classInstans = new SaveWarningMessage(Application.Context);
classInstans.SaveString(warningText);
SaveWarningMessage classInstans2 = new SaveWarningMessage(Application.Context);
string message = classInstans2.GetString();
Log.Debug("SO", message);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have created a login and trying to save the UserName and UserID for
session but I am getting an error at this line
mAppPreference.setUserID(userid);
The error is :-
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.android.mivas.AppContoller.AppPreference.setUserID(java.lang.String)' on a null object reference
here is my Login class
public class LoginPagefrag extends Fragment implements OnClickListener, MiFeelingBase
{
private Intent i;
private int urlIndex=0;
private Button btnLogin;
private EditText edUserName,edPassword;
private String strUserName,strPassword;
private String strEmailID;
private MultipartEntity reqEntity;
private Dialog dialog;
private ProgressDialog pDialog;
Context cxt;
private SessionManager session;
SharedPreferences myPriference;
AppPreference mAppPreference;
public static final String TAG_USERID = "userid";
public static String TAG_USERNAME = "username";
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.loginpage, container, false);
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
edUserName=(EditText)rootView.findViewById(R.id.edUserName);
edPassword=(EditText)rootView.findViewById(R.id.edPassword);
btnLogin.setOnClickListener(this);
return rootView;
}
#SuppressWarnings("unused")
private void initialiseNoramlVariable() {
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
}
public void postLogin()
{
try
{
StringBody username=new StringBody(strUserName);
StringBody password=new StringBody(strPassword);
reqEntity = new MultipartEntity();
reqEntity.addPart("username", username);
reqEntity.addPart("password", password);
}
catch(Exception e)
{
System.out.println("err" + e);
}
}
public void postForgotPass()
{
try
{
StringBody emailid=new StringBody(strEmailID);
reqEntity = new MultipartEntity();
reqEntity.addPart("email", emailid);
}
catch(Exception e)
{
System.out.println("err" + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnLogin :
if(edUserName.getText().toString().equalsIgnoreCase(""))
{
// Toast.makeText(LoginPagefrag.this, "enter username", Toast.LENGTH_SHORT).show();
}else if(edPassword.getText().toString().equalsIgnoreCase(""))
{
//Toast.makeText(LoginPagefrag.this, "enter pass", Toast.LENGTH_SHORT).show();
}else
{
strUserName=edUserName.getText().toString();
strPassword=edPassword.getText().toString();
urlIndex=0;
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
}
break;
}
}
#Override
public String httpPost() {
// TODO Auto-generated method stub
String response="";
if(urlIndex==0)
{
postLogin();
response=APIAccess.openConnection(StaticData.SABAKUCH_LOGIN, reqEntity);
}
return response;
}
#Override
public String httpAfterPost(String str) {
// TODO Auto-generated method stub
if(str!=null)
{
if(urlIndex==0)
{
if(SabaKuchParsechat.jsonStatus(str)==0)
{
// Toast.makeText(LoginPagefrag.this, SabaKuchParsechat.jsonErrorMessage(str), Toast.LENGTH_SHORT).show();
}
else if(SabaKuchParsechat.jsonStatus(str)==1)
{
LoginData obj=SabaKuchParsechat.parseLoginData(str);
Log.d("objj", "hello"+obj);
String userid = obj.strUserId;
String username= obj.strUserName;
mAppPreference.setUserID(userid);
mAppPreference.setUserName(username);
mAppPreference.setServerKey();
session.setLogin(true);
Intent iintt = new Intent(getActivity(),MainActivity.class);
startActivity(iintt);
}
}
}
return null;
}
private boolean CheckEmail(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
public ConnectivityManager getSystemService(String connectivityService) {
// TODO Auto-generated method stub
return null;
}
}
Here is my AppPreference class :-
public class AppPreference extends Application {
Context cxt;
private static final String SHARED_APP_PREFERENCE_NAME = "sabakuchapp_pref_key";
public static AppPreference mAppprefernce;
private SharedPreferences pref;
private Editor mEditor;
public AppPreference() {
super();
// TODO Auto-generated constructor stub
}
enum SharedPreferenceKey{
USER_ID, USER_NAME, SERVER_KEY;
}
private AppPreference (Context context){
pref = context.getSharedPreferences(SHARED_APP_PREFERENCE_NAME, Context.MODE_PRIVATE);
mEditor = pref.edit();
}
public AppPreference(Context cxt, SharedPreferences pref, Editor mEditor) {
super();
this.cxt = cxt;
this.pref = pref;
this.mEditor = mEditor;
}
public static AppPreference getInstance(Context context){
if(mAppprefernce == null){
mAppprefernce = new AppPreference(context);
}
return mAppprefernce;
}
public void setUserID(String id){
mEditor.putString(SharedPreferenceKey.USER_ID.toString(), id);
mEditor.commit();
}
public String getUserID(){
return pref.getString(SharedPreferenceKey.USER_ID.toString(), "");
}
public void setUserName(String name){
mEditor.putString(SharedPreferenceKey.USER_NAME.toString(), name);
mEditor.commit();
}
public String getUserName(){
return pref.getString(SharedPreferenceKey.USER_NAME.toString(), "");
}
public void setServerKey(){
String original = getUserID()+"_" + getUserName() + "_SBK";
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), sb.toString());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), "");
}
mEditor.commit();
return;
}
public String getServerKey(){
return pref.getString(SharedPreferenceKey.SERVER_KEY.toString(), "");
}
}
Please let me know what I am missing here. Thanks in advance.
#SuppressWarnings("unused")
private void initialiseNoramlVariable() {
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
}
You added "unused" warning by yourself. And you never call this method in fact. So mAppPreference is null. If this method is useless, move mAppPreference = AppPreference.getInstance(cxt); to somewhere else such as onCreateView to make sure it could be inited.
You need to initialize your variable mAppPreference.
I mean you have done that in method initialiseNoramlVariable() but never called the method. You should call the method in onCreateView()
You are not calling initialiseNoramlVariable method and therefor mAppPreference does not get initialized.
This should get you going:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.loginpage, container, false);
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
edUserName=(EditText)rootView.findViewById(R.id.edUserName);
edPassword=(EditText)rootView.findViewById(R.id.edPassword);
btnLogin.setOnClickListener(this);
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
return rootView;
}
I have an Activity which constructs a RESTManager class (used to make an asynchronous call to the server and return data to the Activity).
However, after I construct my RESTManager and call the server using
//Retrieve data from server
RESTManager m = new RESTManager(this,getApplicationContext());
//Set the data list
m.delegate=this;
m.retrieveRoomData();
the server call does not go through until I turn off bluetooth scanning.
However, I start my bluetooth scan immediately after the RESTManager as such:
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.setBackgroundScanPeriod(1100l);
beaconManager.setBackgroundBetweenScanPeriod(100l);
beaconManager.setForegroundScanPeriod(1100l);
beaconManager.setForegroundBetweenScanPeriod(100l);
//Set the custom BeaconLayout for iBeacons
if (myPref.getBoolean("layoutSet", true)) {
beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24"));
backgroundPowerSaver = new BackgroundPowerSaver(this);
Log.v("Beacon Layout", "Beacon Layout Set");
myPref.edit().putBoolean("layoutSet", false).apply();
myPref.edit().commit();
}
beaconManager.bind(this);
I am not getting any error.
Is there any reason why my AsyncTask from RESTManager would hang from the bluetooth scans?
Relevant code:
RESTManager class
public class RESTManager {
private DateTime lastUpdate = DateTime.now();
public AsyncResponse delegate=null;
private SharedPreferences mPrefs;
private SharedPreferences.Editor preferenceEditor;
private ArrayList<RoomData> roomDataList = new ArrayList<RoomData>();
private ArrayList<MeetingData> meetingDataList = new ArrayList<MeetingData>();
private Activity currentActivity;
private Context context;
public RESTManager(Activity currentActivity, Context context) {
this.currentActivity = currentActivity;
this.context = context;
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
//Todo update meeting data logic
public ArrayList<MeetingData> retrieveMeetingDataFromServer() {
return null;
}
public void retrieveRoomData() {
new CallServerForRoomData().execute();
}
//TODO add timestamping logic.
private class CallServerForRoomData extends AsyncTask<String, Void, String> {
String myJsonData = "";
#Override
protected String doInBackground(String... params) {
//If the data isn't cached, call the server.
if (!mPrefs.contains("RoomData")) {
try {
setupHttpClient();
HttpClient myClient = new HttpClient(RequestMethod.GET, "http://10.184.46.217:9012/v1/rooms", new HttpHeaders(), null, null);
myClient.connect();
HttpResponse mR = myClient.processResponse();
myJsonData = mR.getServerResponseAsString();
System.out.println(myJsonData);
preferenceEditor = mPrefs.edit();
preferenceEditor.putString("RoomData", myJsonData);
preferenceEditor.commit();
setRoomDataList(convertRoomDataJson(myJsonData));
return "server";
} catch (HttpClientException e) {
e.printStackTrace();
}
}
//If it is cached, retrieve the data locally.
else {
setRoomDataList(convertRoomDataJson(mPrefs.getString("RoomData", "NULL")));
return "local";
}
return "Done";
}
protected void onPostExecute(final String result) {
delegate.dataFinishedRetrieving(getRoomDataList());
// setRoomDataList(convertRoomDataJson(myJsonData));
currentActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Data retrieved on " + result + " storage", Toast.LENGTH_SHORT).show();
}
});
}
}
/**
* AsyncTask for retrieving a room's meeting data.
* Pass in the room's unique identifier as a parameter of the execute method.
*/
//TODO add timestamping logic
private class CallServerForMeetingData extends AsyncTask<String, Void, String> {
String myJsonData = "";
#Override
protected String doInBackground(String... params) {
try {
setupHttpClient();
HttpClient myClient = new HttpClient(RequestMethod.GET, "http://10.184.146.217:9012/v1/room/" + params[0] + "/schedule", new HttpHeaders(), null, null);
myClient.connect();
HttpResponse mR = myClient.processResponse();
myJsonData = mR.getServerResponseAsString();
} catch (HttpClientException e) {
e.printStackTrace();
}
//Set the converted MeetingData to the RoomData object
for (RoomData e : roomDataList) {
if (e.getObjectId() == params[0]) {
e.setMeetingData(convertMeetingDataJson(myJsonData));
}
}
return "Done";
}
}
//Initializes the HTTPClient and attaches it to the application lifecycle.
public void setupHttpClient() {
HttpCacheManager.init(Application.getAppContext());
}
public ArrayList<MeetingData> convertMeetingDataJson(String JsonData) {
final Gson gson = initCustomGSON();
Type MeetingDataListType = null;
if (JsonData != "") {
MeetingDataListType = new TypeToken<ArrayList<MeetingData>>() {
}.getType();
}
return (gson.fromJson(JsonData, MeetingDataListType));
}
public ArrayList<RoomData> convertRoomDataJson(String JsonData) {
final Gson gson = initCustomGSON();
Type RoomDataListType = null;
if (!JsonData.equals("")) {
RoomDataListType = new TypeToken<ArrayList<RoomData>>() {
}.getType();
roomDataList = (gson.fromJson(JsonData, RoomDataListType));
}
roomDataList = (gson.fromJson(JsonData, RoomDataListType));
for (RoomData e : roomDataList) {
Log.v("RoomData name", e.getName());
Log.v("RoomData roomId", e.getObjectId());
//Log.v("RoomData imageUrl", e.getImageUrl());
if (e.getBeacons() != null) {
Log.v("Number of beacons", e.getBeacons().toString());
}
}
return roomDataList;
}
/**
* Initializes the GSON Json Decoder with the custom JodaTime serializers.
*
* #return
*/
public Gson initCustomGSON() {
final GsonBuilder builder = new GsonBuilder();
JodaTimeConverters converter = new JodaTimeConverters();
converter.registerAll(builder);
return builder.create();
}
public ArrayList<RoomData> getRoomDataList() {
return roomDataList;
}
public void setRoomDataList(ArrayList<RoomData> roomDataList) {
this.roomDataList = roomDataList;
}
public void setMeetingDataListForRoom(RoomData whichRoom) {
new CallServerForMeetingData().execute(whichRoom.getObjectId());
}
}