I have a gallery in my app, with a GridLayout and I want that when the user clicks on it, it pops this effect , ¿How can I achieve that?
if anyone could tell me how the effect it is called or a library or something to how can I do that I would really appreciate it, so far I have tried this library with no luck https://github.com/mzelzoghbi/ZGallery?utm_source=android-arsenal.com&utm_medium=referral&utm_campaign=4987
Here is my code if anyone could see the error:
public class BusinessPremiumGallery extends AppCompatActivity implements GridClickListener
{
GalleryAdapter galleryAdapter;
Gson gson;
private static final Type BUSINESS_TYPE = new TypeToken<ArrayList<Business>>() {}.getType();
JsonObject images;
GridLayoutManager layoutManager;
ArrayList<Business> arrayGallery;
ArrayList<String> arrayImages;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_premium_gallery);
Bundle bundle = getIntent().getExtras();
final int values = bundle.getInt("no");
new PlifRequestBase(BusinessPremiumGallery.this) {
#Override
public JsonObject onHttpOk(JsonObject response) throws JSONException {
JsonObject respuesta, details, location, geolocation, matrix, schedules_array;
JsonArray data,branches, phones, schedules,extra_services,user_images;
respuesta = response;
int catalog_id;
String catalog_descrip,catalog_name,catalog_image,image;
Log.d("VALUES2",String.valueOf(values));
arrayGallery=new ArrayList<Business>();
gson=new Gson();
user_images= respuesta.get("user_images").getAsJsonArray();
if(user_images.size()<0){
arrayGallery=null;
images=null;
}else {
arrayGallery=gson.fromJson(user_images,BUSINESS_TYPE);
for (int i = 0; i < user_images.size(); i++) {
images = user_images.get(i).getAsJsonObject();
image=images.get("image").getAsString();
Log.d("IMAGES",image);
Log.d("CATALOG",String.valueOf(images));
}
}
if (BusinessPremiumGallery.this == null)
return response;
BusinessPremiumGallery.this.runOnUiThread(new Runnable() {
public void run() {
RecyclerView recycler = (RecyclerView) BusinessPremiumGallery.this.findViewById(R.id.recycler_gallery);
galleryAdapter = new GalleryAdapter(BusinessPremiumGallery.this, arrayGallery, R.layout.row_gallery_premium);
recycler.setNestedScrollingEnabled(false);
layoutManager = new GridLayoutManager(BusinessPremiumGallery.this, 2);
recycler.setLayoutManager(layoutManager);
recycler.setAdapter(galleryAdapter);
}
});
return respuesta;
}
#Override
public void onHttpCreate(JsonObject response) throws JSONException
{
}
}.execute("businesses/"+String.valueOf(values), "GET");
}
#Override
public void onBackPressed()
{
super.onBackPressed(); // optional depending on your needs
}
#Override
public void onClick(int i) {
ZGallery.with(this, arrayImages)
.show();
}
}
Related
I am developing an android app which shows a list of countries affected by Coronavirus , the total number of confirmed cases and total Deaths. I am using a JSON API to get the data and displaying it using a RecyclerView . The app works fine , and i get a list of all the countries with their respective case counts. I want to add a search option so that the users can filter the list and find a specific country. How do i do that? I am new to programming , if someone could help with this that would be awesome.
Here is the code snippet
MainActivity.java
private RecyclerView mRecyclerView;
private Corona_Stats_Adapter mCorona_Stats_Adapter;
private TextView mErrorDisplay;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.corona_stats);
mRecyclerView = (RecyclerView)findViewById(R.id.Corona_stats_recycler);
mErrorDisplay = (TextView) findViewById(R.id.tv_error_message_display);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mCorona_Stats_Adapter = new Corona_Stats_Adapter();
mRecyclerView.setAdapter(mCorona_Stats_Adapter);
mProgressBar = (ProgressBar)findViewById(R.id.pb_loading_indicator) ;
loadCoronaData();
}
private void loadCoronaData(){
showCoronaDataView();
//String Country = String.valueOf(mSearchQuery.getText());
new Fetch_data().execute();
}
private void showCoronaDataView(){
mErrorDisplay.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
private void showErrorMessage(){
mRecyclerView.setVisibility(View.INVISIBLE);
mErrorDisplay.setVisibility(View.VISIBLE);
}
public class Fetch_data extends AsyncTask<Void,Void,String[]> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected String[] doInBackground(Void... voids) {
URL covidRequestURL = NetworkUtils.buildUrl();
try {
String JSONCovidResponse = NetworkUtils.getResponseFromHttpUrl(covidRequestURL);
String[] simpleJsonCovidData = CovidJSON_Utils.getSimpleStringFromJson(MainActivity.this, JSONCovidResponse);
return simpleJsonCovidData;
} catch (IOException | JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String[] coronaData) {
mProgressBar.setVisibility(View.INVISIBLE);
if(coronaData !=null){
showCoronaDataView();
mCorona_Stats_Adapter.setCoronaData(coronaData);
} else{
showErrorMessage();
}
}
}
}
RecyclerView Adapter class Corona_stats_Adapter.java
public class Corona_Stats_Adapter extends RecyclerView.Adapter<Corona_Stats_Adapter.Corona_Stats_AdapterViewHolder>
{
private Context context;
// private List<Country> countryList;
// private List<Country> countryListFiltered;
private String[] mCoronaData;
public Corona_Stats_Adapter(){
}
#NonNull
#Override
public Corona_Stats_AdapterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int LayoutIdForListItem =R.layout.corona_stats_list_item;
LayoutInflater inflater =LayoutInflater.from(context);
boolean ShouldAttachToParentImmediately = false;
View view = inflater.inflate(LayoutIdForListItem,viewGroup,ShouldAttachToParentImmediately);
return new Corona_Stats_AdapterViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Corona_Stats_AdapterViewHolder corona_stats_adapterViewHolder, int position) {
String coronaStats = mCoronaData[position];
corona_stats_adapterViewHolder.mCoronaTextView.setText(coronaStats);
}
#Override
public int getItemCount() {
if(null == mCoronaData) return 0;
return mCoronaData.length;
// return countryListFiltered.size();
}
public class Corona_Stats_AdapterViewHolder extends RecyclerView.ViewHolder {
public final TextView mCoronaTextView;
public Corona_Stats_AdapterViewHolder(#NonNull View view) {
super(view);
mCoronaTextView = (TextView) view.findViewById(R.id.tv_corona_data);
}
}
public void setCoronaData(String[] coronaData){
mCoronaData = coronaData;
notifyDataSetChanged();
}
}
Parsing the JSON data in CovidJSON_Utils.java
public final class CovidJSON_Utils {
public static String[] getSimpleStringFromJson(Context context, String codivJsonString)
throws JSONException {
final String COV_COUNTRY = "Countries";
final String COV_CONFIRMED = "confirmed";
final String COV_DEATHS = "deaths";
final String COV_MESSAGE_CODE = "code";
String[] parsedCovidData = null;
JSONObject covidJsonObject = new JSONObject(codivJsonString);
if (covidJsonObject.has(COV_MESSAGE_CODE)) {
int errorCode = covidJsonObject.getInt(COV_MESSAGE_CODE);
switch (errorCode) {
case HttpURLConnection.HTTP_OK:
break;
case HttpURLConnection.HTTP_NOT_FOUND:
return null;
default:
return null;
}
}
JSONArray countryCovidArray = covidJsonObject.getJSONArray(COV_COUNTRY);
parsedCovidData = new String[countryCovidArray.length()];
for (int i = 0; i < countryCovidArray.length(); i++) {
JSONObject countryJSONObject = countryCovidArray.getJSONObject(i);
String Country = countryJSONObject.getString("Country");
String Confirmed = String.valueOf(countryJSONObject.getInt("TotalConfirmed"));
String Deaths = String.valueOf(countryJSONObject.getInt("TotalDeaths"));
parsedCovidData[i] = Country + "- Cases " + Confirmed + "- Deaths " + Deaths;
}
return parsedCovidData;
}
}
The problem is with below initialization in the MainActivity.Oncreate method
mCorona_Stats_Adapter = new Corona_Stats_Adapter(this,countries);
Initialize the adapter in onPostExecute method with updated countries data.
Hope this will help you.
You have to set arraylist to update country data in adapter after getting data from the server.
Public void setCoronaData (Arraylist coronaData) {
countryList = coronaData;
notifyDataSetChanged ();
}
At the moment i am using custom adapter/recycle view to build a simple image and a small galery under the image, every time when i click on one of the images below it loads the image in the main imageView above.
My problem at the moment is, that everytime i click on the images on the galery i do a request for the image, i get the id of the clicked image and load again the image to display it above.
I don't like very well my solution, i want to get the bitmap of the clicked image and display it in the imageView above.
So in my main activity i do a simple request to get the main image, the rest of the images are loading in another reques of my activity that loads a recycle view with all images.
here is the activity:
public class PhotosForPlant extends AppCompatActivity implements IResult,PhotosForPlantsAdapter.OnItemClickListener {
RecyclerView recyclerView;
ArrayList<Photo> photos = new ArrayList<Photo>();
VolleyService mVolleyService;
IResult mResultCallback = null;
IResult mResultCallback2 = null;
final String GETREQUEST = "GETCALL";
PhotosForPlantsAdapter adapter;
String token;
TextView familyTxt;
TextView genreTxt;
TextView specieTxt;
TextView specieDescription;
ImageView plantImg;
int familyId;
int genreId;
String familyName;
String genreName;
Double lat = null;
Double lon = null;
Double alt = null;
String time = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
setContentView(R.layout.photos_for_plant);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);;
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
findViewById(R.id.user_ic2).setVisibility(View.GONE);
TextView toolbarText = (TextView) myToolbar.findViewById(R.id.toolbar_title);
toolbarText.setText("Dados planta");;
familyTxt = (TextView)findViewById(R.id.FamilyName);
genreTxt = (TextView)findViewById(R.id.GenreName);
specieTxt = (TextView)findViewById(R.id.SpecieName);
specieDescription = (TextView)findViewById(R.id.specieDescription);
plantImg = (ImageView)findViewById(R.id.plantImage);
token = checkForToken();
getAllPhotos();
getSpecificPlant();
}
private void getSpecificPlant() {
String id = getIntent().getExtras().getString("plantId");
final String URL = "http://109d0157.ngrok.io/plants/" + id;
getSpecificVolleyCallback();
mVolleyService = new VolleyService(mResultCallback2,this);
mVolleyService.getDataObjectVolley(GETREQUEST,URL,token);
}
private void getAllPhotos() {
String id = getIntent().getExtras().getString("plantId");
final String URL = "http://109d0157.ngrok.io/fotos/" + id + "/plants";
getFotosForPlantVolleyCallback();
mVolleyService = new VolleyService(mResultCallback,this);
mVolleyService.getDataVolley(GETREQUEST,URL,token);
recyclerView = (RecyclerView)findViewById(R.id.gallery);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5,GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
adapter = new PhotosForPlantsAdapter(getApplicationContext(), photos,this);
recyclerView.setAdapter(adapter);
}
private void getSpecificVolleyCallback() {
mResultCallback2 = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
try {
Log.d("ENTREIAQUI","ENTREI");
String specie = response.getString("specie");
loadImage(specie);
familyName = response.getJSONObject("genre").getJSONObject("family").getString("name");
genreName = response.getJSONObject("genre").getString("name");
genreId = response.getJSONObject("genre").getInt("id");
genreTxt.setText(genreName);
specieTxt.setText(specie);
familyTxt.setText(familyName);
specieDescription.setText(response.getString("description"));
familyId = response.getJSONObject("genre").getJSONObject("family").getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Log.d("ENTREIAQUI","ENTREI");
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("erro!",error.toString());
Log.d("ENTREIAQUI","ENTREI");
}
};
}
void getFotosForPlantVolleyCallback(){
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Photo photo;
// iterate over the JSONArray response
for (int i=0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i); // get the individual object from JSONArray
Log.d("objeto",object.toString());
int id = Integer.parseInt(object.getString("id")); // get the unique identifier from the object
if(lat != null && lon != null && alt != null){
lat = Double.parseDouble(object.getString("lat"));
lon = Double.parseDouble(object.getString("lon"));
alt = Double.parseDouble(object.getString("altitude"));
}
time = object.getString("date");
String path = object.getString("image");
photo = new Photo(path,id,lat,lon,alt,time); // construct the object
photos.add(photo); // add the object to the arraylist so it can be used on the cardLayout
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("resposta",error.toString());
}
};
}
public void genrePressed(View view){
Intent i = new Intent(this,SpecieLibrary.class);
i.putExtra("id",String.valueOf(genreId));
i.putExtra("name",String.valueOf(genreName));
startActivity(i);
}
public void familyPressed(View view){
Intent i = new Intent(this,GenreLibrary.class);
i.putExtra("id",String.valueOf(familyId));
i.putExtra("name",String.valueOf(familyName));
startActivity(i);
}
#Override
public void notifySuccess(String requestType, JSONObject response) {
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
}
#Override
public void notifyError(String requestType, VolleyError error) {
}
public String checkForToken() {
SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
String tokenKey = getResources().getString(R.string.token);
String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
return token;
}
public void loadImage(String specie){
String url = "http://109d0157.ngrok.io/images/" + specie + "/Thumbnail.jpg";
Picasso.with(PhotosForPlant.this)
.load(url)
.into(plantImg);
}
#Override
public void onRowClick(int position, int id,String path, View view) {
String url = "http://109d0157.ngrok.io/" + path;
Picasso.with(PhotosForPlant.this)
.load(url)
.into(plantImg);
}
}
the loadImage, is where i load the main image and then i have the onRowClick that comes from my custom adapter, i get the path of the clicked row there and so i load it again, but what i need is to get somehow the bitmap there and setImageResource on the plantImg.
Here is my adapter:
public class PhotosForPlantsAdapter extends RecyclerView.Adapter<PhotosForPlantsAdapter.ViewHolder> {
private ArrayList<Photo> photos;
private Context context;
private OnItemClickListener listener;
public interface OnItemClickListener {
void onRowClick(int position,int id,String path, View view);
}
public PhotosForPlantsAdapter(Context context, ArrayList<Photo> photos,OnItemClickListener listener) {
this.photos = photos;
this.context = context;
this.listener = listener;
}
#Override
public PhotosForPlantsAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.photos_for_plant_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final PhotosForPlantsAdapter.ViewHolder viewHolder, final int i) {
String urlFoto = photos.get(i).getPath();
String url = "http://109d0157.ngrok.io/" + urlFoto;
viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.with(context)
.load(url)
.resize(240, 120)
.centerInside()
.into(viewHolder.img);
viewHolder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onRowClick(viewHolder.getAdapterPosition(),photos.get(i).getId(),photos.get(i).getPath(), view);
}
}
});
}
#Override
public int getItemCount() {
return photos.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private ImageView img;
public ViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.img);
}
}
}
try to set Image in this way as bitmap
URL newurl = new URL("http://109d0157.ngrok.io/" + urlFoto);
mIcon_val=BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
viewHolder.img.setImageBitmap(mIcon_val);
and get Image in this way
Bitmap imgBitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
I have a splash screen using AsyncTask, it will download some data from database and store the data in ArrayList. This ArrayList will be used for RecyclerView in fragments of MainActivity.class.
The problem is when I run the app from Android Studio to my phone, everything works perfectly. But, when I destroy the app and run it manually from my phone it will display blank white screen and then it will crash. And if I run once again after it crashed, the app will work. So, this app will always work only if I run it from Android Studio or after it crashed.
The error says that it is caused by the empty list. If I'm not mistaken, I think the AsyncTask doesn't seem to work properly after the activity is destroyed. But I don't know how to fix it. Please help me to solve this problem.
SplashScreen.java
public class SplashScreenActivity extends AppCompatActivity {
public static Event event;
private static List<Feed> feedList;
private static List<Event> eventList;
private static List<Event> todayList;
private static List<Event> upcomingList;
private static List<Partner> partnerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
Config.TODAY_DATE = String.valueOf(today.monthDay) + "-" + String.valueOf(today.month) + "-" + String.valueOf(today.year);
new DownloadData().execute("");
}
class DownloadData extends AsyncTask<String, Integer, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
startActivity(new Intent(getBaseContext(), WelcomeActivity.class));
finish();
}
#Override
protected String doInBackground(String... params) {
RequestHandler rh = new RequestHandler();
String JSON_STRING = rh.sendGetRequest(Config.URL_GET_ALL_DATA);
JSONObject jsonObject;
eventList = new ArrayList<>();
todayList = new ArrayList<>();
upcomingList = new ArrayList<>();
partnerList = new ArrayList<>();
feedList = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray getEvent = jsonObject.getJSONArray(Config.TAG_JSON_EVENT);
for (int i = 0; i < getEvent.length(); i++) {
int id = getEvent.getJSONObject(i).getInt(Config.TAG_ID);
int eoId = getEvent.getJSONObject(i).getInt(Config.TAG_EO_ID);
String eoName = getEvent.getJSONObject(i).getString(Config.TAG_EO_NAME);
String title = getEvent.getJSONObject(i).getString(Config.TAG_TITLE);
String day = getEvent.getJSONObject(i).getString(Config.TAG_DAY);
String date = getEvent.getJSONObject(i).getString(Config.TAG_DATE);
int price = getEvent.getJSONObject(i).getInt(Config.TAG_PRICE);
event = new Event(id, eoId, eoName, title, day, date, price);
eventList.add(event);
if(Config.TODAY_DATE.equals(event.getDate())){
todayList.add(event);
} else {
upcomingList.add(event);
}
}
JSONArray getPartner = jsonObject.getJSONArray(Config.TAG_JSON_PARTNER);
for (int i = 0; i < getPartner.length(); i++) {
int pId = getPartner.getJSONObject(i).getInt(Config.TAG_ID);
String pName = getPartner.getJSONObject(i).getString(Config.TAG_NAME);
String pEmail = getPartner.getJSONObject(i).getString(Config.TAG_EMAIL);
String pPhone = getPartner.getJSONObject(i).getString(Config.TAG_PHONE);
String pPhoto = getPartner.getJSONObject(i).getString(Config.TAG_PHOTO_URL);
Partner partner = new Partner(pId, pName, pEmail, pPhone, pPhoto);
partnerList.add(partner);
}
JSONArray getArticle = jsonObject.getJSONArray(Config.TAG_JSON_ARTICLE);
for (int i = 0; i < getArticle.length(); i++) {
int feedId = getArticle.getJSONObject(i).getInt(Config.TAG_ID);
String feedAuthor = getArticle.getJSONObject(i).getString(Config.TAG_FEED_AUTHOR);
String feedTitle = getArticle.getJSONObject(i).getString(Config.TAG_FEED_TITLE);
String feedContent = getArticle.getJSONObject(i).getString(Config.TAG_FEED_CONTENT);
String feedDate = getArticle.getJSONObject(i).getString(Config.TAG_FEED_DATE);
String feedThumbnail = getArticle.getJSONObject(i).getString(Config.TAG_FEED_THUMBNAIL);
Feed feed = new Feed(feedId, feedAuthor, feedTitle, feedContent, feedDate, feedThumbnail);
feedList.add(feed);
}
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
}
public static List<Feed> getFeedList(){ return feedList;}
public static List<Event> getEventList() {return eventList;}
public static List<Event> getTodayList() { return todayList;}
public static List<Event> getUpcomingList() { return upcomingList;}
public static List<Partner> getPartnerList() {return partnerList;}
}
DiscoverFragment.java
public class DiscoverFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
protected View view;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
private List<Feed> feedList;
private List<Event> eventList;
private List<Partner> partnerList;
public DiscoverFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_discover, container, false);
RecyclerView recyclerViewEvent = (RecyclerView) view.findViewById(R.id.discover_event_recycler_view);
RecyclerView recyclerViewPartner = (RecyclerView) view.findViewById(R.id.discover_partner_recycler_view);
ClickableViewPager intro_images = (ClickableViewPager) view.findViewById(R.id.pager_introduction);
pager_indicator = (LinearLayout) view.findViewById(R.id.viewPagerCountDots);
eventList = SplashScreenActivity.getEventList();
partnerList = SplashScreenActivity.getPartnerList();
feedList = SplashScreenActivity.getFeedList();
EventAdapter eventAdapter = new EventAdapter(getContext(), eventList);
DiscoverPartnerAdapter discoverPartnerAdapter = new DiscoverPartnerAdapter(getContext(), partnerList);
DiscoverFeedAdapter mAdapter = new DiscoverFeedAdapter(getContext(), feedList);
final LinearLayoutManager layoutManagerEvent = new LinearLayoutManager(getContext());
final LinearLayoutManager layoutManagerPartner = new LinearLayoutManager(getContext());
layoutManagerEvent.setOrientation(LinearLayoutManager.HORIZONTAL);
layoutManagerPartner.setOrientation(LinearLayoutManager.HORIZONTAL);
addBottomDots(0);
intro_images.setAdapter(mAdapter);
intro_images.setCurrentItem(0);
intro_images.addOnPageChangeListener(this);
intro_images.setOnItemClickListener(new ClickableViewPager.OnItemClickListener() {
#Override
public void onItemClick(int position) {
Config.FEED_ID = position;
startActivity(new Intent(getContext(), ArticleActivity.class));
}
});
return view;
}
private void addBottomDots(int currentPage) {
dots = new ImageView[feedList.size()]; //the problem
pager_indicator.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
pager_indicator.addView(dots[i], params);
}
if (dots.length > 0)
dots[currentPage].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
}
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
}
LogCat
01-29 00:40:57.565 32535-32535/com.irmaelita.esodiaapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.irmaelita.esodiaapp, PID: 32535
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.addBottomDots(DiscoverFragment.java:181)
at com.irmaelita.esodiaapp.fragment.DiscoverFragment.onCreateView(DiscoverFragment.java:158)
feedList is null. You create feedList instance when DownloadData task is executed. But you call feedList.size() in addBottomDots when fragment view should be created. So, most probably addBottomDots is called before DownloadData task is executed. You need to fix it.
The feedlist in your discover fragment is going empty while initializing. Please set a null check before doing so.It not about running from android studio.If I have understood it correctly you are trying to access a list from splasScreen activity after finishing it. ie in post execute you finish the current activity and the fragment is in main activity,so the list is going null.So if this is the case (and please correct me if not) then either download the data somewhere centrally or best way send it to main activity with intent and use it there. Also when running from android studio kill the app manually and run it again,while the phone is connected and see if it crashes in current scenario.
Send your data from doInBackground to MainActivity with sendBroadcast
Add broadcast method in DownloadData class
private void broadcast(SplashParcel parcel) {
Intent i = new Intent("splash_parcel");
i.putExtra("values", parcel);
sendBroadcast(i);
}
#Override
protected String doInBackground(String... params) {
// your code
// ..
try {
// your code
// ..
// send splashParcel to MainActivity
SplashParcel splashParcel = new SplashParcel(feedList, eventList, todayList, upcomingList, partnerList);
broadcast (splashParcel);
} catch (JSONException e) {
e.printStackTrace();
}
return JSON_STRING;
}
Add new class SplashParcel.java
public class SplashParcel implements Parcelable {
public static final Creator<SplashParcel> CREATOR = new Creator<SplashParcel>() {
#Override
public SplashParcel createFromParcel(Parcel in) {
return new SplashParcel(in);
}
#Override
public SplashParcel[] newArray(int size) {
return new SplashParcel[size];
}
};
private static List<Feed> _feedList;
private static List<Event> _eventList;
private static List<Event> _todayList;
private static List<Event> _upcomingList;
private static List<Partner> _partnerList;
protected SplashParcel(Parcel in) {
_feedList = new ArrayList<Feed>();
in.readList(_feedList, null);
_eventList = new ArrayList<Event>();
in.readList(_eventList, null);
_todayList = new ArrayList<Event>();
in.readList(_todayList, null);
_upcomingList = new ArrayList<Event>();
in.readList(_upcomingList, null);
_partnerList = new ArrayList<Partner>();
in.readList(_partnerList, null);
}
public SplashParcel(List<Feed> feedList, List<Event> eventList, List<Event> todayList, List<Event> upcomingList, List<Partner> partnerList) {
_feedList = feedList;
_eventList = eventList;
_todayList = todayList;
_upcomingList = upcomingList;
_partnerList = partnerList;
}
public SplashParcel() {
}
public List<Feed> getFeedList() {
return _feedList;
}
public void setFeedList(List<Feed> feedList) {
_feedList = feedList;
}
public List<Event> getEventList() {
return _eventList;
}
public void setEventList(List<Event> eventList) {
_eventList = eventList;
}
public List<Event> getTodayList() {
return _todayList;
}
public void setTodayList(List<Event> todayList) {
_todayList = todayList;
}
public List<Event> getUpcomingList() {
return _upcomingList;
}
public void setUpcomingList(List<Event> upcomingList) {
_upcomingList = upcomingList;
}
public List<Partner> getPartnerList() {
return _partnerList;
}
public void setPartnerList(List<Partner> partnerList) {
_partnerList = partnerList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(_feedList);
parcel.writeList(_eventList);
parcel.writeList(_todayList);
parcel.writeList(_upcomingList);
parcel.writeList(_partnerList);
}
}
MainActivity.java
// member variable
private BroadcastReceiver _splashReceiver;
private Bundle _bundle = new Bundle();
#Override
protected void onResume() {
super.onResume();
splashReceiver();
}
// receive splashParcel from SplashScreenActivity
private void splashReceiver() {
if (_splashReceiver == null) {
_splashReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SplashParcel splashParcel = intent.getParcelableExtra("values");
if (splashParcel != null) {
// save splashParcel into _budle
_bundle.putParcelable("splash_parcel", splashParcel);
}
}
};
registerReceiver(_splashReceiver, new IntentFilter("splash_parcel"));
}
}
//Send _bundle to DiscoverFragment
private void showDiscoverFragment(){
if(_bundle != null) {
// create instance of discoverFragment with passing _bundle as arguments
DiscoverFragment discoverFragment = new DiscoverFragment();
discoverFragment.setArguments(_bundle);
// replace activity_main.xml with discoverFragment
getSupportFragmentManager().beginTransaction().replace(R.id.main_container, discoverFragment).addBackStack(null).commit();
}
}
In onCreateView of DiscoverFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SplashParcel splashParcel = getArguments().getParcelable("splash_parcel");
if(splashParcel != null) {
// your splashParcel ready in here
List<Feed> feedList = splashParcel.getFeedList()
List<Event> eventList = splashParcel.getEventList()
List<Event> todayList = splashParcel.getTodayList();
List<Event> upcommingList = splashParcel.getUpcomingList();
List<Partner> partnerList = splashParcel.getPartnerList();
}
}
I have an activity that displays a list of activities (name, picture, brief description), and where those information are derived from JSON data. I am trying to figure out how I could add a criteria where only the list of activities that falls within lets say 100km would be shown.
I was thinking of adding the following to my JSON data
"location_code":"(49, -123)", where 49 represents latitude and -123 longitude, and what would happen is that it would evaluate the location_code of the activity in respect to the current location of the user and would only populate activities that falls within that range.
Below is my current code:
public class CultureEventsActivity extends Activity{
private static final String URL_WEB_SERVICE = "http://dooba.elasticbeanstalk.com/analytics/culture.php";
private GridView gv;
private ArrayList<Events_List> container;
private ArrayList<Events_List> items;
public Uri list_item_bac;
public String list_item_name;
public String list_item_description;
public String list_item_location;
public String single_list_item_description;
public String list_item_price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events_list_layout);
gv = (GridView) findViewById(R.id.gridview);
container = new ArrayList<Events_List>();
//download JSON
listDownload();
GridView s = (GridView) findViewById(R.id.gridview);
s.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(CultureEventsActivity.this,CultureEventsSingleItemActivity.class);
intent.putExtra("list_item_name", container.get(position).getList_item_title());
intent.putExtra("list_item_price", container.get(position).getList_item_price());
intent.putExtra("list_item_location", container.get(position).getList_item_location());
intent.putExtra("single_list_item_description", container.get(position).getSingle_list_item_description());
intent.putExtra("list_item_bac", container.get(position).getList_item_bac().toString());
intent.putExtra("list_item_purchase_code", container.get(position).getList_item_purchase_code());
startActivity(intent); //start Activity
}
});
}
public void listDownload(){
RequestQueue volley = Volley.newRequestQueue(this);
JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
volley.add(json);
}
private Response.Listener<JSONObject> ResponseListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//your JSON Array
JSONArray array = response.getJSONArray("list_item");
for(int i = 0; i < array.length(); i++){
container.add(convertirAnuncio(array.getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
gv.setAdapter(new AdapterEvents(getApplicationContext(),container));
}
};
};
private Response.ErrorListener ErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }
};
}
//object JSON
private final Events_List convertirAnuncio(JSONObject obj) throws JSONException {
long id = obj.getLong("id"); //id
String list_item_name = obj.getString("list_item_name");
String list_item_location = obj.getString("list_item_location");
String list_item_description = obj.getString("list_item_description");
String list_item_price = obj.getString("list_item_price");
String list_item_purchase_code = obj.getString("list_item_purchase_code");
String single_list_item_description = obj.getString("single_list_item_description");
Uri uri = Uri.parse(obj.getString("list_item_bac"));
return new Events_List(id, list_item_location, single_list_item_description,list_item_name,list_item_description,list_item_price,list_item_purchase_code, uri, uri);
}
}
As of now the code populates all activities, and does not filter by search zone. It would also be nice if I could include a constant like private String SEARCH_DISTANCE = 100KM;
PS. I am also using Parse, where the current user is derived from Parse, but I am not sure if that's relevant.
Any help would be greatly appreciated as I have been trying to figure this out since a while.
If you require any further clarification, let me know.
i want make some process in my aplication to input some text first, after that, When user clicks the done button on the screen keyboard(using android:imeOptions="actionSearch") Isome data will show from this url :
("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);
but when i make some process, there's nothing happen, my code still load all data, not specific as cari_agen, this is my source code :
public class MainActivity extends Activity {
GridView gridView;
private static final String ATASAN = "atasan";
private static final String KODE_AGEN = "kode_agen";
private static final String JENIS = "jenis";
private static final String NO_AAJI = "no_aaji";
private static final String NAMA_AGEN = "nama_agen";
List AgenList = new ArrayList();
boolean boolStatusKoneksi=true;
private ProgressDialog Dialog;
protected Context applicationContext;
EditText cari;
SearchView search;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
search=(SearchView) findViewById(R.id.searchView1);
cari=(EditText) findViewById(R.id.search);
cari.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
new AgenAsyncTask().execute();
return true;
}
return false;
}
});
}
public class AgenAsyncTask extends AsyncTask<String, String, String>
{
String cari_agen = cari.getText().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
Dialog = new ProgressDialog(MainActivity.this);
Dialog.setMessage("Mohon Tunggu sebentar...");
Dialog.setIndeterminate(false);
Dialog.setCancelable(true);
Dialog.show();
}
protected String doInBackground(String... args) {
String url =("http://www.aaaa.com/selectAgent.htm?n="+cari_agen);
try{
JSONParser j=new JSONParser();
JSONArray jsonArray = j.takeJson(url);
for(int i =0; i<jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
if (c.has("nama_agen"))
Log.v(NAMA_AGEN,"Nama agen=") ;
map.put("nama_agen", c.get("nama_agen").toString());
if (c.has("atasan"))
map.put("atasan", c.get("atasan").toString());
if (c.has("jenis"))
map.put("jenis", c.get("jenis").toString());
AgenList.add(map);
if (c.has("no_aaji"))
map.put("no_aaji", c.get("no_aaji").toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String arg)
{
Dialog.dismiss();
GridView gridview = (GridView) findViewById(R.id.gridview);
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, AgenList, R.layout.list_item,
new String[] { NAMA_AGEN, ATASAN, JENIS,NO_AAJI }, new int [] {R.id.nama_agen, R.id.atasan, R.id.jenis,R.id.no_aaji});
gridview.setAdapter(adapter); }
i hope somebody can help me to solve this problem, thank u