I'm generating a random string in MainActivity. When i'm using intent method, I can calling and put this string in SecondActivity. But i can't call this string from all activities. How can i do this
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
Several options are available to you - in this case, because it wont introduce any extra dependencies (RxJava, EventBus, etc.), I'd recommend you write it to SharedPreferences, and have your other activities register a listener on SharedPreferences for changes to your value:
public class SaltStringPreference {
private static final String KEY = "a_key";
private final SharedPreferences prefs;
private Listener listener;
private SaltStringPreference(SharedPreferences prefs) {
this.prefs = prefs;
}
public static SaltStringPreference from(Context context) {
return new SaltStringPreference(PreferenceManager.getDefaultSharedPreferences(context));
}
public void set(String saltString) {
prefs.edit().putString(KEY, saltString).apply();
}
public String get() {
return prefs.getString(KEY, "<no_value>");
}
/*
Note we need to keep a reference to the listener somewhere,
otherwise it could be garbage collected, see
https://stackoverflow.com/a/3104265/1219389
*/
public void setListener(Listener listener) {
this.listener = listener;
prefs.registerOnSharedPreferenceChangeListener(listener);
}
public void removeListener() {
prefs.unregisterOnSharedPreferenceChangeListener(listener);
this.listener = null;
}
public static abstract class Listener implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(KEY.equals(key)) {
onSaltStringChanged(sharedPreferences.getString(KEY, "<no_value>"));
}
}
/**
* Called when the 'salt string' value changes in SharedPreferences
* #param saltString The new 'salt string' value
*/
protected abstract void onSaltStringChanged(String saltString);
}
}
class ActivityOne extends AppCompatActivity {
//...
SaltStringPreference.from(this).set(generatedSaltString);
}
class AnotherActivity extends AppCompatActivity {
private final SaltStringPreference.Listener listener = new SaltStringPreference.Listener() {
#Override
protected void onSaltStringChanged(String saltString) {
//Do something with new String...
}
});
private SaltStringPreference pref;
//onCreate...
pref = SaltStringPreference.create(this);
pref.setListener(listener);
//onDestroy...
pref.removeListener();
}
Use static Method, You can call the method to all activities.
public Class UtilClass{
public static String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
}
Related
I have an app that works fine on older Android versions, however, on later (Android 11> onwards) whilst the camera(take photo) function works fine, and permissions are OK I can't use the PhotoPicker function, it just shows blank picker , before crashing out of the app completely - in older devices the photo gallery of the device displays correctly and allows you to select a photo to use.
Here is the onCreate for the
PhotoPickerActivity.java
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
boolean booleanExtra = getIntent().getBooleanExtra(PhotoPicker.EXTRA_SHOW_CAMERA, true);
boolean booleanExtra2 = getIntent().getBooleanExtra(PhotoPicker.EXTRA_SHOW_GIF, false);
boolean booleanExtra3 = getIntent().getBooleanExtra(PhotoPicker.EXTRA_PREVIEW_ENABLED, true);
this.forwardMain = getIntent().getBooleanExtra(PhotoPicker.MAIN_ACTIVITY, false);
setShowGif(booleanExtra2);
setContentView(R.layout.__picker_activity_photo_picker);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
setTitle(getResources().getString(R.string.tap_to_select));
ActionBar supportActionBar = getSupportActionBar();
supportActionBar.setDisplayHomeAsUpEnabled(true);
// if (Build.VERSION.SDK_INT >= 21) {
supportActionBar.setElevation(25.0f);
// }
this.maxCount = getIntent().getIntExtra(PhotoPicker.EXTRA_MAX_COUNT, 9);
int intExtra = getIntent().getIntExtra(PhotoPicker.EXTRA_GRID_COLUMN, 3);
this.originalPhotos = getIntent().getStringArrayListExtra(PhotoPicker.EXTRA_ORIGINAL_PHOTOS);
this.pickerFragment = (PhotoPickerFragment) getSupportFragmentManager().findFragmentByTag("tag");
if (this.pickerFragment == null) {
this.pickerFragment = PhotoPickerFragment.newInstance(booleanExtra, booleanExtra2, booleanExtra3, intExtra, this.maxCount, this.originalPhotos);
getSupportFragmentManager().beginTransaction().replace(R.id.container, this.pickerFragment, "tag").commit();
getSupportFragmentManager().executePendingTransactions();
}
this.pickerFragment.getPhotoGridAdapter().setOnItemCheckListener(new OnItemCheckListener() {
#Override
public final boolean onItemCheck(int i, Photo photo, int i2) {
return PhotoPickerActivity.this.lambda$onCreate$0$PhotoPickerActivity(i, photo, i2);
}
});
}
We also have PhotoPicker.java
public class PhotoPicker {
public static final int DEFAULT_COLUMN_NUMBER = 3;
public static final int DEFAULT_MAX_COUNT = 9;
public static final String EXTRA_GRID_COLUMN = "column";
public static final String EXTRA_MAX_COUNT = "MAX_COUNT";
public static final String EXTRA_ORIGINAL_PHOTOS = "ORIGINAL_PHOTOS";
public static final String EXTRA_PREVIEW_ENABLED = "PREVIEW_ENABLED";
public static final String EXTRA_SHOW_CAMERA = "SHOW_CAMERA";
public static final String EXTRA_SHOW_GIF = "SHOW_GIF";
public static final String KEY_SELECTED_PHOTOS = "SELECTED_PHOTOS";
public static final String MAIN_ACTIVITY = "MAIN_ACTIVITY";
public static final int REQUEST_CODE = 233;
public static PhotoPickerBuilder builder() {
return new PhotoPickerBuilder();
}
public static class PhotoPickerBuilder {
private Intent mPickerIntent = new Intent();
private Bundle mPickerOptionsBundle = new Bundle();
public void start(Activity activity, int i) {
if (PermissionsUtils.checkReadStoragePermission(activity)) {
activity.startActivityForResult(getIntent(activity), i);
}
}
public void start(Context context, Fragment fragment, int i) {
if (PermissionsUtils.checkReadStoragePermission(fragment.getActivity())) {
fragment.startActivityForResult(getIntent(context), i);
}
}
public void start(Context context, Fragment fragment) {
if (PermissionsUtils.checkReadStoragePermission(fragment.getActivity())) {
fragment.startActivityForResult(getIntent(context), PhotoPicker.REQUEST_CODE);
}
}
public Intent getIntent(Context context) {
this.mPickerIntent.setClass(context, PhotoPickerActivity.class);
this.mPickerIntent.putExtras(this.mPickerOptionsBundle);
return this.mPickerIntent;
}
public void start(Activity activity) {
start(activity, PhotoPicker.REQUEST_CODE);
}
public PhotoPickerBuilder setPhotoCount(int i) {
this.mPickerOptionsBundle.putInt(PhotoPicker.EXTRA_MAX_COUNT, i);
return this;
}
public PhotoPickerBuilder setGridColumnCount(int i) {
this.mPickerOptionsBundle.putInt(PhotoPicker.EXTRA_GRID_COLUMN, i);
return this;
}
public PhotoPickerBuilder setShowGif(boolean z) {
this.mPickerOptionsBundle.putBoolean(PhotoPicker.EXTRA_SHOW_GIF, z);
return this;
}
public PhotoPickerBuilder setShowCamera(boolean z) {
this.mPickerOptionsBundle.putBoolean(PhotoPicker.EXTRA_SHOW_CAMERA, z);
return this;
}
public PhotoPickerBuilder setSelected(ArrayList<String> arrayList) {
this.mPickerOptionsBundle.putStringArrayList(PhotoPicker.EXTRA_ORIGINAL_PHOTOS, arrayList);
return this;
}
public PhotoPickerBuilder setForwardMain(boolean z) {
this.mPickerOptionsBundle.putBoolean(PhotoPicker.MAIN_ACTIVITY, z);
return this;
}
public PhotoPickerBuilder setPreviewEnabled(boolean z) {
this.mPickerOptionsBundle.putBoolean(PhotoPicker.EXTRA_PREVIEW_ENABLED, z);
return this;
}
}
}
In the AndroidManifest.xml the permissions for Camera are there, and on runtime are checked, and permission is granted.
I tried to make a covid-19 tracking app by watching Youtube tutorials.
My app shows the country list with flags and when you click on any country it opens an activity and shows the details of that country i.e total cases, deaths, recovered, etc. The video on Youtube uses ListView and I am using recyclerView
I fetched the country list successfully and set onClickListener on the view and it opens second activity which shows the case in detail. But I don't know how to show the data.
my adapter class:
class Countries_adapter extends RecyclerView.Adapter<Countries_adapter.MyViewHolder> {
Context ct;
List<Countries_data> list;
public Countries_adapter(Context context,List<Countries_data> country)
{
ct=context;
list=country;
}
#Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View v = LayoutInflater.from(ct).inflate(R.layout.countries_row,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tvCountryName.setText(list.get(position).getCountry());
holder.tvtotal.setText(list.get(position).getActive());
Glide.with(ct).load(list.get(position).getFlag()).into(holder.imageView);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ct,CountriesDetails.class);
i.putExtra("Country",list.get(position).getCountry());
ct.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCountryName,tvtotal;
ImageView imageView;
LinearLayout linearLayout;
public MyViewHolder( View itemView) {
super(itemView);
tvCountryName = itemView.findViewById(R.id.tvCountryName);
tvtotal=itemView.findViewById(R.id.tvCountrytotalcaese);
imageView = itemView.findViewById(R.id.imageFlag);
linearLayout=itemView.findViewById(R.id.linear_layout);
}
}
my AffectedCoutries class activity is as follows:
public class AffectedCountries extends AppCompatActivity {
EditText edtSearch;
RecyclerView recyclerView;
SimpleArcLoader simpleArcLoader;
public static ArrayList countryList = new ArrayList<>();
Countries_data countryData;
Countries_adapter CountriesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_affected_countries);
edtSearch = findViewById(R.id.edtSearch);
recyclerView=findViewById(R.id.recyclerAffectedCountries);
simpleArcLoader = findViewById(R.id.loader);
fetchData();
}
private void fetchData() {
String url = "https://corona.lmao.ninja/v2/countries/";
simpleArcLoader.start();
StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String countryName = jsonObject.getString("country");
String cases = jsonObject.getString("cases");
String todayCases = jsonObject.getString("todayCases");
String deaths = jsonObject.getString("deaths");
String todayDeaths = jsonObject.getString("todayDeaths");
String recovered = jsonObject.getString("recovered");
String active = jsonObject.getString("active");
String critical = jsonObject.getString("critical");
JSONObject object = jsonObject.getJSONObject("countryInfo");
String flagUrl = object.getString("flag");
countryData = new Countries_data(flagUrl,countryName,cases,todayCases,deaths,todayDeaths,recovered,active,critical);
countryList.add(countryData);
}
CountriesAdapter = new Countries_adapter(AffectedCountries.this,countryList);
recyclerView.setLayoutManager(new LinearLayoutManager(AffectedCountries.this));
recyclerView.setAdapter(CountriesAdapter);
simpleArcLoader.stop();
simpleArcLoader.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
simpleArcLoader.start();
simpleArcLoader.setVisibility(View.GONE);
Toast.makeText(AffectedCountries.this,"catch response", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
simpleArcLoader.stop();
simpleArcLoader.setVisibility(View.GONE);
Toast.makeText(AffectedCountries.this,"error response", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}
my Countries_data class(model class)
public class Countries_data {
public String country;
public String cases;
public String todayCases;
public String deaths;
public String todayDeaths;
public String recovered;
public String active;
public String critical;
public String flag;
public Countries_data(String flag, String country, String cases, String
todayCases, String deaths, String todayDeaths, String recovered,
String active, String critical) {
this.country = country;
this.cases = cases;
this.todayCases = todayCases;
this.deaths = deaths;
this.todayDeaths = todayDeaths;
this.recovered = recovered;
this.active = active;
this.critical = critical;
this.flag = flag;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCases() {
return cases;
}
public void setCases(String cases) {
this.cases = cases;
}
public String getTodayCases() {
return todayCases;
}
public void setTodayCases(String todayCases) {
this.todayCases = todayCases;
}
public String getDeaths() {
return deaths;
}
public void setDeaths(String deaths) {
this.deaths = deaths;
}
public String getTodayDeaths() {
return todayDeaths;
}
public void setTodayDeaths(String todayDeaths) {
this.todayDeaths = todayDeaths;
}
public String getRecovered() {
return recovered;
}
public void setRecovered(String recovered) {
this.recovered = recovered;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getCritical() {
return critical;
}
public void setCritical(String critical) {
this.critical = critical;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
my Country_details class
public class CountriesDetails extends AppCompatActivity {
TextView tvCountry, tvCases, tvRecovered,tvdeaths;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countries_details2);
tvCountry = findViewById(R.id.tvCountry);
tvCases = findViewById(R.id.tvCases);
tvRecovered = findViewById(R.id.tvRecovered);
tvdeaths=findViewById(R.id.tvTotalDeaths);
String positionCountry = getIntent().getStringExtra("Country");
Log.i("country name", positionCountry);
}
}
How to set the data in tvcases?
How can I show the data? Do I have to create a separate recycler view and then fetch the data from the API or can I use my main activity to show the data?
I have some sad information for you: Google Play policy restricts such apps from being published in store... especially when you are showing deaths count. Been there, done that, my app was blocked...
besides above:
you are passing country name in intent:
i.putExtra("Country",list.get(position).getCountry());
but trying to read "position" in details Activity - it will be always 0 (default)
edit due to comments:
pass position of clicked View
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ct,CountriesDetails.class);
i.putExtra("position", position);
ct.startActivity(i);
}
});
in CountriesDetailss onCreate method receive this position and restore proper Countries_data object from your static countryList array in AffectedCountries
int position = getIntent().getIntExtra("position", 0);
Countries_data country = AffectedCountries.countryList.get(position);
tvCountry.setText(country.getCountry());
that should work, but this isn't best way to store data, in fact its very weak... after downloading data (list of countries) you should store it somehow, e.g. SQLite/Room lib or at least SharedPreferences... then in details activity you should restore int position and using it take proper object from database or preferences, instead of stright from static array
it may be also useful to implement Parcelable inteface to your Countries_data - this will allow to put whole Countries_data object into Intents extras, not only primitive int with position in array. in this case details activity won't even need access to whole array or sql database/preferences, it will get whole object straight from Intents extras
EDITED:
The real purpose of that is to have one activity and on class who fetch data and render it to the activity.
The problem is I have dropdown menu. When I clicked on an item of the menu it change my url but it does not load or fetch my data to the activity but when i clicked again it works but with the paramaters selected just before and if I clicked again it still works but still with the previous elements selected.
My "teacher" said I have to call build into my callback method.
But it doesen't work at all. And I still didn't find any solution :/.
As you recommended I changed everything for non-static method
I thought why not saving an history of the dropdown, compare the current value with the saved value and if it's diffrent it means it was changed so reload the app to make new fetch and displyed new data.
But I got :
Here my all code
PhotosActivity
public class PhotosActivity extends AppCompatActivity {
// Local variable
private OkHttpClient httpClient;
private ImageButton home_btn;
private ImageButton favorites_btn;
private ImageButton search_btn;
private ImageButton profil_btn;
// Constante variable
private static final String TAG = "PhotoActivity";
private static final String clientId = "bb0c749c6403fd2";
// Private shared variable
private static List<Photo> mPhotos;
private static JSONArray mItems;
private static String mAccessToken;
private static String userID;
static Activity activity;
// Shared variable
private static String selectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
this.home_btn = findViewById(R.id.home_button);
this.favorites_btn = findViewById(R.id.favorites_button);
this.search_btn = findViewById(R.id.search_button);
this.profil_btn = findViewById(R.id.profil_button);
final HttpHandler httpHandler = new HttpHandler();
httpHandler.fetchData();
build();
activity = this;
Spinner spinner=(Spinner)findViewById(R.id.spinner);
String[] filters=getResources().getStringArray(R.array.filters);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner,R.id.text, filters);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
selectedItem = parent.getItemAtPosition(position).toString();
// httpHandler.fetchData();
// build();
}
public void onNothingSelected(AdapterView<?> parent)
{
Log.d("TAG", "Error");
}
});
home_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), PhotosActivity.class);
finish();
startActivity(next_activity);
}
});
favorites_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
finish();
startActivity(next_activity);
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), SearchActivity.class);
finish();
startActivity(next_activity);
}
});
profil_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), ProfileActivity.class);
finish();
startActivity(next_activity);
}
});
}
public void Filters() {
String hSection;
String hSort;
String hShowV;
hSection = HttpHandler.section ;
hSort = HttpHandler.sort;
hShowV = HttpHandler.showV;
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
if(selectedItem != null) {
if (selectedItem.equals("Most Viral")) {
HttpHandler.sort = "viral/";
HttpHandler.section = "hot/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "most: "+HttpHandler.section);
Log.d("TAG", "H most: "+hSection);
// activity.recreate();
// onRestart();
finish();
startActivity(next_activity);
}
} else if (selectedItem.equals("Newest")) {
HttpHandler.section = "top/";
HttpHandler.sort = "time/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "new: "+HttpHandler.section);
Log.d("TAG", "H new: "+hSection);
finish();
startActivity(next_activity);
// activity.recreate();
// onRestart();
}
} else if (selectedItem.equals("Rising")) {
HttpHandler.section = "user/";
HttpHandler.sort = "rising/";
HttpHandler.showV = "?showViral=false";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "rising: "+HttpHandler.section);
Log.d("TAG", "H rising: "+hSection);
// onRestart();
// activity.recreate();
finish();
startActivity(next_activity);
}
} else {
Log.d(TAG, "Might be a problem");
}
} else {
activity.recreate();
}
}
public void build () {
try {
for(int i = 0; i < mItems.length(); i++) {
JSONObject item = mItems.getJSONObject(i);
Photo photo = new Photo();
if(item.getBoolean("is_album")) {
photo.id = item.getString("cover");
} else {
photo.id = item.getString("id");
}
photo.title = item.getString("title");
mPhotos.add(photo);
runOnUiThread(new Runnable() {
#Override
public void run() {
render(mPhotos);
}
});
}
} catch (Exception e) {
Log.e("JSONerr" , "Something went wrong.");
}
}
private static class PhotoVH extends RecyclerView.ViewHolder {
ImageView photo;
TextView title;
public PhotoVH(View itemView) {
super(itemView);
}
}
private void render(final List<Photo> photos) {
RecyclerView rv = (RecyclerView)findViewById(R.id.rv_of_photos);
rv.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.Adapter<PhotoVH> adapter = new RecyclerView.Adapter<PhotoVH>() {
#NonNull
#Override
public PhotoVH onCreateViewHolder(ViewGroup parent, int viewType) {
PhotoVH vh = new PhotoVH(getLayoutInflater().inflate(R.layout.item, null));
vh.photo = (ImageView) vh.itemView.findViewById(R.id.photo);
vh.title = (TextView) vh.itemView.findViewById(R.id.title);
return vh;
}
#Override
public void onBindViewHolder(PhotoVH holder, int position) {
Picasso.with(PhotosActivity.this).load("https://i.imgur.com/" +
photos.get(position).id + ".jpg").into(holder.photo);
holder.title.setText(photos.get(position).title);
}
#Override
public int getItemCount() {
return photos.size();
}
};
rv.setAdapter(adapter);
}
public static void getUserID(String UserID) {
Log.d("TAG", UserID);
userID = UserID;
}
public void callBackPhoto( List<Photo> photos, JSONArray items)
{
mPhotos = photos;
mItems = items;
// build();
}
}
HttpHandler
public class HttpHandler {
private static final String TAG = "HttpHandler";
private static String clientId = "bb0c749c6403fd2";
private static OkHttpClient httpClient;
private static String mAccessToken;
// URL BUILDER VARIABLES
public static String section = "hot/";
public static String sort = "viral/";
public static String page;
public static String showV;
public static String mUrl;
public void fetchData() {
httpClient = new OkHttpClient.Builder().build();
photosActivity.Filters();
mUrl = "https://api.imgur.com/3/gallery/" + section + sort;
// Log.d("TAG", "Sort: " + sort + ": URl is" + mUrl);
Request request = new Request.Builder()
.url(mUrl + "0.json" + showV)
.addHeader("Authorization", "Client-ID " + clientId)
.header("User-Agent", "epicture")
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "An error has occurred " + e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject data = new JSONObject(response.body().string());
JSONArray items = data.getJSONArray("data");
final List<Photo> photos = new ArrayList<Photo>();
photosActivity.callBackPhoto(photos, items);
} catch (Exception e) {
Log.e("JSONerr", "Something went wrong.");
}
}
});
}
public static void getLoginData(String accessToken) {
mAccessToken = accessToken;
}
}
It doesn't look like making sense to declare callBackPhoto as a static method. If you have put static keyword accidentally in its declaration, simply remove it to solve your problem i.e. replace
public static void callBackPhoto( List<Photo> photos, JSONArray items)
with
public void callBackPhoto( List<Photo> photos, JSONArray items)
Note that there is no way to call a non-static method from a static one directly (i.e. without calling it on an object/instance). Thus, if for any reason, you can't remove static keyword from the declaration of callBackPhoto, you are left with only two options:
Declare build too as static
Call build on an object/instance e.g. new PhotosActivity().build()
Though any of these two options will solve your problem, I don't think this is how you intend to design your class.
In java, a static method belongs to EVERY object of the class that defines it. Therefore, you can call it from the parent class without creating an object like so:
ParentClass.myMethod;
However, this is not the case the case with instance (non-static) methods. To call this type of method, you need to define it in a class, create an object from that class, and then call it from that object, like this:
//inside ParentClass definition
public void myMethod(){bla bla;}
//In some other class
ParentClass obj = new ParentClass;
obj.myMethod;
Suppose you have code calling a static member of a class without creating an instance of that class. If that method contained a non-static method, there would be no object in memory to call it on. This is why it isn't possible.
Static
The static methods are alive all the time. They live from the class is loaded. They don't need objects to live. I think of them as not really belonging to the class, but the class is just a nice way to organize those methods (the same for variables). The methods could be put in any other class definition and it would still work. But organizing them in classes where they will be used make it easy to prevent access from other parts of the program, like other objects or other static methods. They are called class methods or class variables.
Instance
The non-static "stuff" does not live unless there is an object. That's why you cannot call below methodOne or methodTwo from the static methods. You have to create an object first. They are called instance methods or instance variables, because you need an instance of an object to call them.
Error
error: non-static method <methodname> cannot be referenced from a static context basically means "There's no object"
Example
public class StackOverflowTest {
public static void main(String[] args) { // this is just another static method
// methodOne(); // error. There's no object
StackOverflowTest test = new StackOverflowTest();
test.methodOne(); // method called on object.
}
// methods live outside objects
static void staticMethodOne() {
System.out.println("staticMethodOne");
staticMethodTwo(); // no object required.
}
static void staticMethodTwo() {
System.out.println("staticMethodTwo");
// methodTwo(); // error. There's no object
}
// methods that only live inside objects
void methodOne() { // method can only be invoked if there's an object.
System.out.println("methodOne");
methodTwo(); // no problem. Already inside the object.
}
void methodTwo() {
System.out.println("methodTwo");
staticMethodTwo(); // no problem. Objects can access static methods.
}
}
Your case
So you either have to create a PhotosActivity object inside your build(), or you have to make callBackPhoto a static method. I can't see what your render does, but it's the same principle.
I am trying to make a mobile version of a board game and for some reason I have an ArrayList where all elements conform to the last element whenever a new one is added and I canĀ“t figure out why.
(i am pretty new to Android Studio)
Below are all the classes that are concerned with adding to the list:
public class ScoreBoard {
private static final ScoreBoard ourInstance = new ScoreBoard();
public static ScoreBoard getInstance() {
return ourInstance;
}
List<Player> Players;
int nrOfPlayers;
int activePlayer;
private ScoreBoard() {
Players = new ArrayList<Player>();
}
public void addPlayer(CharSequence name) {
Player p = new Player(name);
Players.add(p);
}
public void nrOfPlayers(int number)
{
nrOfPlayers = number;
}
public boolean stop()
{
boolean stop = false;
if (nrOfPlayers <= Players.size())
{
stop = true;
}
return stop;
}
public void StartGame()
{
Random random = new Random();
random.nextInt(nrOfPlayers);
}
public CharSequence GetActivePlayerName()
{
return Players.get(activePlayer).name;
}
}
public class Player {
public CharSequence name;
public int points;
public Player(CharSequence name)
{
this.name = name;
}
}
public class PlayerName extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_name);
}
public void addPlayer(View view)
{
ScoreBoard SB = ScoreBoard.getInstance();
TextView nameText = (TextView)findViewById(R.id.NameText);
TextView playerText = (TextView)findViewById(R.id.PlayerText);
CharSequence name = nameText.getText();
SB.addPlayer(name);
playerText.setText("Player " + (SB.Players.size() + 1) + " enter your name");
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, name + " Added", duration);
toast.show();
if(SB.stop())
{
SB.StartGame();
Intent intent = new Intent(this, TakeTurn.class);
startActivity(intent);
}
else
{
}
}
}
You've used static and final while initializing. Remove them and modify your Scorecard class as follows:
private ScoreBoard ourInstance = new ScoreBoard();
public ScoreBoard getInstance() {
return ourInstance;
}
I have an application in which I want to integrate VIDEO AD from AdColony.
When the user clicks on the button, the loadAd() method is triggered, and after that onRequestFilled.
But after calling show() nothing happens.
Here's class with all methods that i have for AdColony.
public class AdColonyAds {
private final String ZONE_ID = "vzac61b40e83e8436c9e";
private final String APP_ID_ADCOLONY = "appa567471ee29646b5b5";
private AdColonyInterstitial ad;
private AdColonyInterstitialListener listener;
private AdColonyAdOptions ad_options;
private String uniqueID;
private Activity activity;
public AdColonyAds(Activity activity) {
this.activity = activity;
uniqueID = UUID.randomUUID().toString();
}
public void initAdColony(){
AdColonyAppOptions app_options = new AdColonyAppOptions()
.setUserID(uniqueID);
AdColony.configure( activity, app_options, APP_ID_ADCOLONY, ZONE_ID );
AdColonyUserMetadata metadata = new AdColonyUserMetadata()
.setUserAge( 26 )
.setUserEducation( AdColonyUserMetadata.USER_EDUCATION_BACHELORS_DEGREE )
.setUserGender( AdColonyUserMetadata.USER_MALE );
ad_options = new AdColonyAdOptions()
.enableConfirmationDialog( true )
.enableResultsDialog( true )
.setUserMetadata( metadata );
AdColony.setRewardListener( new AdColonyRewardListener()
{
#Override
public void onReward( AdColonyReward reward )
{
reward.getRewardAmount();
}
} );
listener = new AdColonyInterstitialListener() {
#Override
public void onRequestFilled(AdColonyInterstitial adColonyInterstitial) {
Toast.makeText(activity,"Ready",Toast.LENGTH_SHORT).show();
adColonyInterstitial.show();
}
};
}
public void showAdColony(){
ad.show();
}
public void loadAd(){
AdColony.requestInterstitial( ZONE_ID, listener, ad_options );
}
}
You may need to set ad instance variable at onRequestFilled listener to use after from showAdColony method.
listener = new AdColonyInterstitialListener() {
#Override
public void onRequestFilled(AdColonyInterstitial adColonyInterstitial) {
ad = adColonyInterstitial;
}
};