Tabbed fragment don't show listviews - java

i try to combine tabbed fragment with listview. I fetch data by JSON and put it in listview in fragment but when i start app fragment don't show list view.
Actors.java
`
public class Actors {
private String name;
private String description;
private String dob;
private String country;
private String height;
private String spouse;
private String children;
private String image;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String name, String description, String dob, String country,
String height, String spouse, String children, String image) {
super();
this.name = name;
this.description = description;
this.dob = dob;
this.country = country;
this.height = height;
this.spouse = spouse;
this.children = children;
//this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}
`
ActorAdapter.java
`
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.vi = LayoutInflater.from(context);
this.Resource = resource;
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
// holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.ic_launcher);
//new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("Pubblicato il: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Categoria: " + actorList.get(position).getHeight());
return v;
}
static class ViewHolder {
//public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
}
/*private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}*/
}
Main.java
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
TopRatedFragment.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
public class TopRatedFragment extends Fragment {
ArrayList<Actors> actorsList;
Context context=getActivity();
ActorAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://www.technologici.it/api/get_recent_posts/");
ListView listview = (ListView)rootView.findViewById(R.id.list);
context = getActivity();
listview.setAdapter(new ActorAdapter(getActivity(), R.layout.row, actorsList));
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
// Starting single contact activity
Intent in = new Intent(getActivity(),
SingleContactActivity.class);
in.putExtra("title", actorsList.get(position).getName());
in.putExtra("author", actorsList.get(position).getCountry());
in.putExtra("data", actorsList.get(position).getDob());
in.putExtra("content", actorsList.get(position).getDescription());
in.putExtra("category", actorsList.get(position).getHeight());
//in.putExtra("image", actorsList.get(position).getImage());
startActivity(in);
}
});
setRetainInstance(true);
return rootView;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Caricamento...");
dialog.setTitle("Contattando il server...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("posts");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("title"));
actor.setDescription(object.getString("content"));
actor.setDob(object.getString("date"));
JSONObject author = object.getJSONObject("author");
actor.setCountry(author.getString("name"));
JSONArray catarray = object.getJSONArray("categories");
JSONObject catobject = catarray.getJSONObject(0);
actor.setHeight(catobject.getString("title"));
// JSONArray imgarray = object.getJSONArray("attachments");
// JSONObject imgobject = imgarray.getJSONObject(0);
//actor.setImage(imgobject.getString("url"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
// adapter.notifyDataSetChanged();
if (result == false) {
Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
}
Layout:
fragment_top_rated.xml
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:listitem="#layout/row" >
</ListView>
</LinearLayout>
row.xml
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tom Cruise"
android:textColor="#166CED"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvDateOfBirth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="Date of Birth: July 3, 1962" />
<TextView
android:id="#+id/tvHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Height: 1.80 m"
android:textColor="#D64530"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/tvCountry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#D64530"
android:text="United States" />
<TextView
android:id="#+id/tvDescriptionn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#009A57"
android:text="Description"
android:visibility="gone"/>
</LinearLayout>
`
Can someone help me?

Related

Previous fragment is not being replaced when selecting a navigation menu item

I have a navigation drawer activity that shows a list of restaurants based on some data passed from the previous activity as the home fragment. On clicking on one of the restaurant cards, another fragment is created which shows the details of the restaurant. All of these fragments have the navigation drawer activity as their parent activity. When I am selecting the home fragment menu on the navigation item, the fragment does not replace the previous fragment rather it superimposes itself on the previous fragment. I will add some images to explain the scenario.
This is my Navigation Drawer -
This is the home fragment containing the restaurant lists -
This is the fragment showing the restaurant details when clicking on one restaurant -
When I press the home item on the navigation drawer from the restaurant detail screen this happens -
Here is the relevant code-
MainActivity2.class
package com.example.wfdmockapp;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import com.example.wfdmockapp.ui.home.HomeFragment;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.example.wfdmockapp.databinding.ActivityMain2Binding;
public class MainActivity2 extends AppCompatActivity{
private static final String TAG = "MainActivity2";
private String cityId = null;
private String townId = null;
private DrawerLayout drawer;
private AppBarConfiguration mAppBarConfiguration;
private ActivityMain2Binding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMain2Binding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarMain.toolbar);
binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
Intent getRestaurantIntent = getIntent();
cityId = getRestaurantIntent.getStringExtra("cityId");
townId = getRestaurantIntent.getStringExtra("townId");
Bundle bundle = new Bundle();
bundle.putString("cityId",cityId);
bundle.putString("townId",townId);
System.out.println(cityId+" "+townId);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.replace(R.id.nav_host_fragment_content_main, HomeFragment.class, bundle)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity2, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}```
HomeFragment.Java
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private RequestQueue mRequestQueue;
private String cityId = null;
private String townId = null;
private String ShopListUrl= Global.base_url+"v1/get-shop-list";
private ArrayList<Shop> shops = new ArrayList<>();
private RecyclerView recyclerView;
private ShopRecyclerViewAdapter adapter;
private GifImageView loadingAnimation;
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
if(bundle!=null){
cityId = bundle.getString("cityId");
townId = bundle.getString("townId");
System.out.println(cityId+" "+townId);
}
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRequestQueue = Volley.newRequestQueue(getContext());
loadingAnimation = view.findViewById(R.id.loading_animation);
initRecyclerView(view);
getShopList();
}
public void getShopList(){
Log.d(TAG,"Creating Shop Object");
JSONObject shopInfoObject = new JSONObject();
try {
shopInfoObject.put("city",cityId);
shopInfoObject.put("town",townId);
shopInfoObject.put("shop_type",null);
shopInfoObject.put("api_token","a4e426652ed46154d67c8af897e77022");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG,"JSON Shop Object created,collecting response for Request");
JsonObjectRequest ShopListRequest = new JsonObjectRequest(Request.Method.POST, ShopListUrl, shopInfoObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG,"Getting response");
JSONArray shopList = response.getJSONArray("shopList");
for(int i=0;i<shopList.length();i++){
JSONObject jsonObject = shopList.getJSONObject(i);
Shop shop = new Shop();
shop.setShopId(jsonObject.getString("shopId"));
shop.setName(jsonObject.getString("title"));
shop.setTypeName(jsonObject.getString("typeName"));
shop.setLogo(Global.base_imageUrl+jsonObject.getString("logo"));
shop.setSpecialOffer(jsonObject.getString("special_offer_text"));
shop.setDeliveredBy(jsonObject.getInt("deliveredBy"));
shop.setMixMatch(jsonObject.getInt("mixAndMatch"));
shop.setDeliveryFee(jsonObject.getString("delivery_fee"));
shop.setMinimumOrder(jsonObject.getString("minOrder"));
shop.setPaymentModeText(jsonObject.getString("paymentModeText"));
shop.setShopStatus(jsonObject.getString("currentStatus"));
shops.add(shop);
}
adapter.notifyDataSetChanged();
Log.d(TAG,"Shop data fetched");
loadingAnimation.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError) {
Global.displayToast("Timeout! Please Try Again",getContext());
}
}
});
ShopListRequest.setRetryPolicy(new DefaultRetryPolicy(
6000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(ShopListRequest);
}
public void initRecyclerView(View view){
recyclerView = view.findViewById(R.id.recycler_view);
adapter = new ShopRecyclerViewAdapter(shops,getContext(),this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}```
RestaurantDetailsFragment.Java
package com.example.wfdmockapp;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.wfdmockapp.models.Restaurant;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import pl.droidsonroids.gif.GifImageView;
public class RestaurantDetailsFragment extends Fragment {
private static final String TAG = "RestaurantDetails";
private RequestQueue mRequestQueue;
private Restaurant restaurant = new Restaurant();
private String getShopDetailsUrl = Global.base_url+"v1/get-shop-details";
private String shopId;
private ArrayList<String> FoodTypeList;
//UI Components
private TextView name;
private TextView typeName;
private TextView shopMessage;
private TextView minOrder;
private TextView paymentModeText;
private RecyclerView foodTypeListRecyclerView;
private FoodTypeRecyclerViewAdapter adapter;
private TextView deliveryText;
private TextView deliveryFee;
private TextView deliveryTime;
private TextView shopStatus;
private CircleImageView shopLogo;
private LinearLayout shopDetailsView;
private GifImageView loadingAnimation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shopId = getArguments().getString("shopId");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_restaurant_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadingAnimation = view.findViewById(R.id.shop_details_loading_animation);
shopDetailsView = view.findViewById(R.id.shop_view);
shopDetailsView.setVisibility(View.GONE);
FoodTypeList = restaurant.getFoodTypeList();
mRequestQueue = Volley.newRequestQueue(getContext());
initRecyclerView(view);
initUIComponents(view);
showRestaurantDetails(view);
}
public void showRestaurantDetails(View view){
JSONObject ShopInfoObject = new JSONObject();
try {
ShopInfoObject.put("api_token","cadbc10d3aa13257cd7c69bb3d434d00");
ShopInfoObject.put("shopId",shopId);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest getShopDetailsRequest = new JsonObjectRequest(Request.Method.POST, getShopDetailsUrl, ShopInfoObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray shopDetails = response.getJSONArray("shop");
String deliveryTextResponse = response.getString("deliveryText");
restaurant.setDeliveryText(deliveryTextResponse);
for(int i=0;i<shopDetails.length();i++){
JSONObject shopJsonObject = shopDetails.getJSONObject(i);
restaurant.setName(shopJsonObject.getString("title"));
restaurant.setTypeName(shopJsonObject.getString("typeName"));
restaurant.setShop_message(shopJsonObject.getString("shop_message"));
String ImageUrl = Global.base_imageUrl+shopJsonObject.getString("logo");
restaurant.setLogo(ImageUrl);
restaurant.setMinOrder(shopJsonObject.getString("minOrder"));
restaurant.setStatus(shopJsonObject.getString("currentStatus"));
JSONArray foodTypeListJSONArray = shopJsonObject.getJSONArray("foodTypeList");
for(int j=0;j<foodTypeListJSONArray.length();j++){
JSONObject foodTypeListJSONObject = foodTypeListJSONArray.getJSONObject(j);
Log.d(TAG,foodTypeListJSONObject.getString("foodTypeName"));
restaurant.addFoodListItems(foodTypeListJSONObject.getString("foodTypeName"));
}
adapter.notifyDataSetChanged();
restaurant.setDelivery_fee(shopJsonObject.getString("delivery_fee"));
JSONObject deliveryHours = shopJsonObject.getJSONObject("deliveryHours");
String openingHours = deliveryHours.getString("openingHour");
String closingHours = deliveryHours.getString("closingHour");
restaurant.setDeliveryTime("Delivery: "+openingHours+" - "+closingHours);
restaurant.setPaymentModeText(shopJsonObject.getString("paymentModeText"));
setUIComponentValues(restaurant,view);
loadingAnimation.setVisibility(View.GONE);
shopDetailsView.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError) {
Global.displayToast("Timeout error!Please try again",getContext());
}
}
});
getShopDetailsRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(getShopDetailsRequest);
}
public void initUIComponents(View view){
name = view.findViewById(R.id.shopName);
typeName = view.findViewById(R.id.shopTypename);
shopMessage = view.findViewById(R.id.shop_message);
minOrder = view.findViewById(R.id.min_order);
paymentModeText = view.findViewById(R.id.payment_Method);
deliveryFee = view.findViewById(R.id.min_delivery_fee);
deliveryText = view.findViewById(R.id.delivery_time_today);
deliveryTime = view.findViewById(R.id.shop_delivery_time);
shopLogo = view.findViewById(R.id.shopLogo);
shopStatus = view.findViewById(R.id.status);
}
public void setUIComponentValues(Restaurant restaurant,View view){
Glide.with(getContext()).load(restaurant.getLogo()).into(shopLogo);
name.setText(restaurant.getName());
typeName.setText(restaurant.getTypeName());
String message = restaurant.getShop_message();
System.out.println(message);
if(message.equals("")||message.equals("null")){
Log.d(TAG,"No shop message,hiding field");
LinearLayout shopMsgField = view.findViewById(R.id.shop_message_field);
shopMsgField.setVisibility(View.GONE);
}else{
shopMessage.setText(message);
}
minOrder.setText("\u20ac "+restaurant.getMinOrder()+" MIN ");
paymentModeText.setText(restaurant.getPaymentModeText());
deliveryFee.setText("Delivery \u20ac "+restaurant.getDelivery_fee());
String text = restaurant.getDeliveryText();
if(text.equals("null")||text.equals("")){
deliveryText.setVisibility(View.GONE);
}else{
deliveryText.setText(text);
}
deliveryTime.setText(restaurant.getDeliveryTime());
Global.setCurrentStatusText(restaurant.getStatus(),shopStatus);
}
public void initRecyclerView(View view){
foodTypeListRecyclerView = view.findViewById(R.id.FoodTypeRecyclerView);
adapter = new FoodTypeRecyclerViewAdapter(FoodTypeList,getContext());
foodTypeListRecyclerView.setAdapter(adapter);
foodTypeListRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
}```
ShopRecyclerViewAdapter.java
package com.example.wfdmockapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.wfdmockapp.models.Shop;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class ShopRecyclerViewAdapter extends RecyclerView.Adapter<ShopRecyclerViewAdapter.ViewHolder> {
private static final String TAG="ShopRecyclerViewAdapter";
private ArrayList<Shop> shops;
private Context mContext;
private Fragment fragment;
public ShopRecyclerViewAdapter(ArrayList<Shop> shops,Context mContext,Fragment fragment) {
this.shops = shops;
this.mContext = mContext;
this.fragment = fragment;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG,"Reached onCreate");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shoplistitem,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.d(TAG,"Reached onBind");
try{
Glide.with(mContext).load(shops.get(position).getLogo()).into(holder.shopLogo);
}catch (Exception e){
Glide.with(mContext).load(R.drawable.shop_logo_base).into(holder.shopLogo);
}
holder.deliveryFee.setText("Delivery \u20ac "+shops.get(position).getDeliveryFee());
holder.minOrder.setText("\u20ac "+shops.get(position).getMinimumOrder()+" MIN ");
holder.paymentMethod.setText(shops.get(position).getPaymentModeText());
String status = shops.get(position).getShopStatus();
Global.setCurrentStatusText(status,holder.shopStatus);
holder.shopName.setText(shops.get(position).getName());
holder.shopTypeName.setText(shops.get(position).getTypeName());
String offerText = shops.get(position).getSpecialOffer();
if(!(offerText==null)){
holder.shopOffer.setText(offerText);
}else{
holder.offerSection.setVisibility(View.GONE);
}
int deliveredBy = shops.get(position).getDeliveredBy();
makeViewInvisible(holder.delivery_layout,deliveredBy);
int mixAndMatch = shops.get(position).getMixMatch();
makeViewInvisible(holder.mixMatchLayout,mixAndMatch);
holder.parent_layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bundle bundle = new Bundle();
bundle.putString("shopId",shops.get(position).getShopId());
FragmentManager fm = fragment.getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTrans = fm.beginTransaction();
fragmentTrans.replace(R.id.nav_host_fragment_content_main,RestaurantDetailsFragment.class,bundle);
fragmentTrans.setReorderingAllowed(true);
fragmentTrans.addToBackStack(null);
fragmentTrans.commit();
}
});
}
#Override
public int getItemCount() {
return shops.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView shopLogo;
TextView shopName;
TextView shopTypeName;
TextView shopOffer;
TextView minOrder;
TextView deliveryFee;
TextView paymentMethod;
TextView shopStatus;
RelativeLayout offerSection;
RelativeLayout parent_layout;
RelativeLayout delivery_layout;
RelativeLayout mixMatchLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
shopLogo = itemView.findViewById(R.id.shop_logo);
shopName = itemView.findViewById(R.id.shop_title);
shopTypeName = itemView.findViewById(R.id.shop_typename);
shopOffer = itemView.findViewById(R.id.offer_text);
offerSection = itemView.findViewById(R.id.offer_section);
minOrder = itemView.findViewById(R.id.shop_min_order);
deliveryFee = itemView.findViewById(R.id.deliver_fee);
shopStatus = itemView.findViewById(R.id.status);
paymentMethod = itemView.findViewById(R.id.shop_payment);
parent_layout = itemView.findViewById(R.id.parent_layout);
delivery_layout = itemView.findViewById(R.id.delivered_by);
mixMatchLayout = itemView.findViewById(R.id.mix_and_match);
}
}
public void makeViewInvisible(View view,int flag){
if(flag==1){
view.setVisibility(View.GONE);
}
}
}```
You need to pop the fragment onBackPressed and function needs to execute from MainActivity thus.
MainActivity
public void popFragment() {
if (getSupportFragmentManager() == null)
return;
getSupportFragmentManager().popBackStack();
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
popFragment();
}
}
Turns out, the problem was in the ShopRecyclerViewAdapter.java file.
In the line
FragmentManager fm = fragment.getActivity().getSupportFragmentManager
fragment.getActivity made the context null. Grabbing context from view instead solved the problem.
I replaced the above line with the following:
FragmentManager fm = ((FragmentActivity) view.getContext()).getSupportFragmentManager()
Here is the reference to the solution:
Replace fragment from recycler adapter

How to implement a custom ArrayList in AsyncTask?

i am building an Android application that takes an API(The Movie Database), and extracts the JSON array. Upon extraction, the appropriate JSONObject is sent to a model. This model is a class composed of setters and getters to extract the object and assign it to variables which i can use. All of this is done on the AsyncTask. However, i am having a hard time understanding the doInBackground method as it expects me to return something. I have done all of the work on the getMovieJson method and i know i must return something from the doInBackground because it is required to update my custom adapter on the onPostExecute method. This custom adapter is an ArrayAdapter that creates the appropriate views to populate in my gridView.
This is my Model
package com.xxcanizeusxx.erick.moviesnow;
/**
* This class acts as the model base for our
* array of JSON Objects that need to be populated.\
* This class uses getters and setters to achieve its task.
*/
public class Movie {
private String title;
private String vote_average;
private String overview;
private String release_date;
private String poster_path;
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getOverview(){
return overview;
}
public void setOverview(String overview){
this.overview = overview;
}
public String getRelease_date(){
return release_date;
}
public void setRelease_date(String release_date){
this.release_date = release_date;
}
public String getVote_average(){
return vote_average;
}
public void setVote_average(String vote_average){
this.vote_average = vote_average;
}
public String getPoster_path(){
return poster_path;
}
public void setPoster_path(String poster_path){
this.poster_path = poster_path;
}
}
This my Fragment
package com.xxcanizeusxx.erick.moviesnow;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by Erick on 1/4/2017.
*/
public class MovieFragment extends Fragment {
//Initialize our array adapter and components.
private ArrayList<Movie> mMovieData;
private MovieAdapter mMovieAdapter;
//Empty constructor
public MovieFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.movie_fragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.popular_movies) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateMovie() {
FetchMovieTask fetchMovie = new FetchMovieTask();
fetchMovie.execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Initialize our array adapter
mMovieData = new ArrayList<>();
mMovieAdapter = new MovieAdapter(getActivity(), R.layout.grid_movie_item, mMovieData);
View rootView = inflater.inflate(R.layout.gird_layout, container, false);
//Get a reference to the gridView and attach the adapter to it
GridView mGridView = (GridView) rootView.findViewById(R.id.gridView);
mGridView.setAdapter(mMovieAdapter);
return rootView;
}
#Override
public void onStart() {
super.onStart();
updateMovie();
}
public class FetchMovieTask extends AsyncTask<String[], Void, String[]> {
private final String LOG = FetchMovieTask.class.getSimpleName();
private String[] getMovieJson(String movieJsonStr) throws JSONException {
final String OWM_RESULTS = "results";
String title;
String posterPath;
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieJsonArray = movieJson.getJSONArray(OWM_RESULTS);
Movie movieItem = new Movie();
//Newly created array that will house the data in order to check for views on the onPostExecute method
String[] results = new String[movieJsonStr.length()];
for (int i = 0; i < movieJsonArray.length(); i++) {
JSONObject movieObject = movieJsonArray.getJSONObject(i);
title = movieObject.getString("title");
posterPath = movieObject.getString("poster_path");
movieItem.setTitle(title);
movieItem.setPoster_path(posterPath);
results[i] = movieObject.getString(posterPath) +" " + movieObject.getString(posterPath);
}
mMovieData.add(movieItem);
return results;
}
#Override
protected String[] doInBackground(String[]... params) {
//Establish a connection
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
//Will contain the raw JSON as a string
String movieJsonStr = null;
//String as placeholders
String descriptionHolder = "popularity.desc";
try {
//String to hold the Base url
final String TMDB_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String APPID = "api_key";
final String DESC = "sort_by";
//Build the url
Uri buildMovieUri = Uri.parse(TMDB_BASE_URL).buildUpon()
.appendQueryParameter(DESC, descriptionHolder)
.appendQueryParameter(APPID, BuildConfig.TMDP_API_KEY)
.build();
URL url = new URL(buildMovieUri.toString());
//Create the request to TMDB and open connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input stream into a string
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
//Nothing to do
return null;
}
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
//Make debugging easier by adding a new line to the bufffer stream
buffer.append(line + "\n");
int result = 1;
}
if (buffer.length() == 0) {
//stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG, "Error ", e);
//If code didnt get the movie data, no point in parsing
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException e) {
Log.e(LOG, "Error closing stream ", e);
}
}
}
try {
return getMovieJson(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result){
if (result != null){
mMovieAdapter.clear();
for (String results : result ){
mMovieAdapter.setMovieData(results);
}
}
}
}
}
This is my Adapter
package com.xxcanizeusxx.erick.moviesnow;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* This class is the MovieAdapter that will take data from the model and
* display it on the View. Additionally, this adapter will load the picasso base_img_url
* to populate the griView according to Udacity.
*/
public class MovieAdapter extends ArrayAdapter<Movie> {
private final String BASE_IMAGE_URL = "http://image.tmdb.org/t/p/w185";
private Context mContext;
private int resource;
private ArrayList<Movie> mMovieData = new ArrayList<Movie>();
//Constructor matching super
public MovieAdapter(Context mContext, int resource, ArrayList<Movie> mMovieData) {
super(mContext, resource, mMovieData);
this.mContext = mContext;
this.resource = resource;
this.mMovieData = mMovieData;
}
//This method sets the movieData and refreshes the gridLayout items.
public void setMovieData(ArrayList<Movie> mMovieData){
this.mMovieData = mMovieData;
//Notifies if data state has changed
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//Declare the variables to hold the convertView and viewHolder static class
View cv = convertView;
ViewHolder viewHolder;
//If the convertView is null, we don't have a view so, create one.
if(cv == null){
//Create the View
cv = LayoutInflater.from(getContext()).inflate(resource, parent, false);
//Call the static viewHolder class
viewHolder = new ViewHolder();
//Initialize the textView and imageView to load inside the view
viewHolder.movieTextView = (TextView) cv.findViewById(R.id.movie_title);
viewHolder.moviePoster = (ImageView) cv.findViewById(R.id.movie_poster);
cv.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) cv.getTag();
}
Movie movieItem = mMovieData.get(position);
//Set the textView holder
viewHolder.movieTextView.setText(movieItem.getTitle());
//use picasso to load images to the holder
Picasso.with(mContext).load(BASE_IMAGE_URL + movieItem.getPoster_path()).fit().into(viewHolder.moviePoster);
return cv;
}
static class ViewHolder{
TextView movieTextView;
ImageView moviePoster;
}
}
This is my Main Activity
package com.xxcanizeusxx.erick.moviesnow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new MovieFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
//Inflate the menu, this adds items to actionbar if present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
}
My girdLayout xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/grid_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/gridView"
android:numColumns="2"
android:gravity="center"
android:drawSelectorOnTop="true"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp">
</GridView>
</FrameLayout>
My movieItem xml (To populate the gridLayout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/movie_detail_item"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/movie_poster"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/movie_title"
android:maxLines="2"
android:gravity="center"
android:textSize="14sp"
android:textAllCaps="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Change the parameter of your Asynctask first
public class FetchMovieTask extends AsyncTask<Void, String[], String[]> {}
Then change the return type of your doInBackground() to get the results
#Override
protected String[] doInBackground(Void... params) {}
Understand the flow of parameters and return types.
UPDATE:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.gird_layout, container, false);
//Initialize our array adapter
mMovieData = new ArrayList<>();
updateView(mMovieData);
return rootView;
}
void updateView(ArrayList<>() movieData){
mMovieAdapter = new MovieAdapter(getActivity(), R.layout.grid_movie_item, movieData);
//Get a reference to the gridView and attach the adapter to it
GridView mGridView = (GridView) rootView.findViewById(R.id.gridView);
mGridView.setAdapter(mMovieAdapter);
}
Return ArrayList from your GetMovie & DoInBackground
#Override
protected ArrayList<Movies> doInBackground(Object... params) {}
and
private ArrayList<Movies> getMovieJson(String movieJsonStr) throws JSONException {
....
mMovieData.add(movieItem);
return mMovieData;
}
call this updateView to update rather setAdapater(..) and postExecute parameters to
#Override
protected void onPostExecute(ArrayList<Movies> movieData){
updateView(movieData);
}
First things is you code compiling ? From what I can See your AsyncTask has the following signature -
public class FetchMovieTask extends AsyncTask<String[], Void, Void> {
But You are returning String[] from doInBackground which ideally would give you an error.
Anyways, you don't have to return anything from the AsyncTask in your case. Just add this call on onPostExecute - mMovieAdapter.setMovieData(Arrays.asList(result))
Btw, the type result should be String[] and not String as I can see.

Android JSON Parsing images into imageview with cached thumbnails

I'm trying to develop an app which works by parsing json and adding parsed json into Imageview. I set a GridView and Imageview into it as a row. When I run app, pictures get parsed as well but when I scroll down, the thumbnails get lost.
The video at this URL Json thumbs shows what I mean.
Here my MainActivity.java:
package berkantkz.wallstation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.baoyz.widget.PullRefreshLayout;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar tool_bar = (Toolbar) findViewById(R.id.tool_bar);
tool_bar.setTitle(R.string.app_name);
tool_bar.setLogo(R.mipmap.ic_launcher);
ProgressBar spinner = (ProgressBar) findViewById(R.id.spinner);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("https://raw.githubusercontent.com/berkantkz/misc/master/sample.json");
PullRefreshLayout layout = (PullRefreshLayout) findViewById(R.id.swipeRefreshLayout);
// listen refresh event
layout.setRefreshStyle(PullRefreshLayout.STYLE_MATERIAL);
layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// start refresh
Intent i = new Intent(MainActivity.this, MainActivity.class); //your class
startActivity(i);
finish();
}
});
// refresh complete
layout.setRefreshing(false);
final GridView listview = (GridView) findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long id) {
//
final ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.VISIBLE);
final Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setVisibility(View.GONE);
LinearLayout linearlayout = (LinearLayout) findViewById(R.id.LinearLayout1);
linearlayout.setBackgroundColor(getResources().getColor(R.color.black));
//TextView tv = (TextView) findViewById(R.id.tvName);
//tv.setVisibility(View.VISIBLE);
final ImageView iv = (ImageView) findViewById(R.id.expanded_image);
Picasso.with(MainActivity.this)
.load(actorsList.get(position).getImage())
.into(iv, new Callback() {
#Override
public void onSuccess() {
pb.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
iv.setVisibility(View.VISIBLE);
listview.setVisibility(View.GONE);
//
}
});
}
#Override
public void onBackPressed() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar.setVisibility(View.VISIBLE);
ImageView iv = (ImageView) findViewById(R.id.expanded_image);
iv.setVisibility(View.GONE);
GridView listview = (GridView) findViewById(R.id.list);
listview.setVisibility(View.VISIBLE);
LinearLayout ln = (LinearLayout) findViewById(R.id.LinearLayout1);
ln.setBackgroundColor(getResources().getColor(R.color.default_bg));
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.GONE);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.refresh) {
// TODO Auto-generated method stub
}
return super.onOptionsItemSelected(item);
}
}
Actors.java
package berkantkz.wallstation;
/**
* Created by berka on 1.12.2016.
*/
public class Actors {
private String name;
private String description;
private String image;
public Actors() {
}
//Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
ActorAdapter.java
package berkantkz.wallstation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by berka on 25.11.2016.
*/
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
Log.d("Deneme", "birinci");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("Deneme", "iki");
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
//holder.tvName = (TextView) v.findViewById(R.id.tvName);
//holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.transparent);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
//holder.tvName.setText(actorList.get(position).getName());
//holder.tvDescription.setText(actorList.get(position).getDescription());
return v;
}
static class ViewHolder {
public ImageView imageview;
//public TextView tvName;
//public TextView tvDescription;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

Custom List View with thumbnail using Android Volley Library will not load any results

I am trying to load a custom listview using Volley Networking library but there are no results while running the app and no errors on the code. The data come from a JSON file
JSON OUTPUT HERE
Below are my classes :
MainActivity.java
package info.androidhive.customlistviewvolley;
import info.androidhive.customlistviewvolley.adater.CustomListAdapter;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "http://178.62.67.237/api/v1/residential/?format=json";
private ProgressDialog pDialog;
private List<CaseStudy> caseList = new ArrayList<CaseStudy>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, caseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
CaseStudy reference = new CaseStudy();
reference.setTitle(obj.getString("title"));
reference.setThumbnailUrl(obj.getString("image"));
reference.setPostcode(obj.getString("postcode"));
// adding movie to movies array
caseList.add(reference);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
CaseStudy.java:
package info.androidhive.customlistviewvolley.model;
public class CaseStudy {
private String title;
private String thumbnailUrl;
private String postcode;
public CaseStudy() {
}
public CaseStudy(String name, String thumbnailUrl, String postcode) {
this.title = name;
this.thumbnailUrl = thumbnailUrl;
this.postcode = postcode;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPostcode() {
return postcode;
}
}
CustomListAdapter.java:
package info.androidhive.customlistviewvolley.adater;
import info.androidhive.customlistviewvolley.R;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.CaseStudy;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CaseStudy> caseItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapter(Activity activity, List<CaseStudy> caseItems) {
this.activity = activity;
this.caseItems = caseItems;
}
#Override
public int getCount() {
return caseItems.size();
}
#Override
public Object getItem(int location) {
return caseItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_row_custom, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
TextView postcode = (TextView) convertView.findViewById(R.id.postcode);
//TextView genre = (TextView) convertView.findViewById(R.id.genre);
//TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
// getting movie data for the row
CaseStudy c = caseItems.get(position);
// thumbnail image
thumbNail.setImageUrl(c.getThumbnailUrl(), imageLoader);
// title
title.setText(c.getTitle());
postcode.setText(c.getPostcode());
// rating
//rating.setText("Rating: " + String.valueOf(m.getRating()));
// genre
//String genreStr = "";
//for (String str : m.getGenre()) {
// genreStr += str + ", ";
//}
//genreStr = genreStr.length() > 0 ? genreStr.substring(0,
// genreStr.length() - 2) : genreStr;
//genre.setText(genreStr);
// release year
//year.setText(String.valueOf(m.getYear()));
return convertView;
}
}
ist_row_custom.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_row_selector"
android:padding="8dp" >
<!-- Thumbnail Image -->
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="8dp" />
<!-- Title -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/title"
android:textStyle="bold" />
<!-- Postcode-->
<TextView
android:id="#+id/postcode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:textSize="#dimen/rating" />
<!-- Genre -->
<!-- Release Year -->
</RelativeLayout>
Any ideas what I have done wrong?
You are referring to wrong xml in you MainActivity. Kindly create a new xml for ex activity_main.xml and initiate your list view there.
Also in your code you are Calling JSONArray however your Json output shows it Json Object. Kindly change your code to JSONObject as shown below
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
hidePDialog();
System.out.println("JsonObject++===---"+jsonObject);
try {
JSONArray response = jsonObject.getJSONArray("objects");
for(int i=0; i <response.length(); i++){
JSONObject obj = response.getJSONObject(i);
CaseStudy reference = new CaseStudy();
reference.setTitle(obj.getString("title"));
reference.setThumbnailUrl(obj.getString("image_path"));
reference.setPostcode(obj.getString("postcode"));
// adding movie to movies array
caseList.add(reference);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("error");
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest, TAG);
According to your Json you should get 'image_path' not 'image' .
reference.setThumbnailUrl(obj.getString("image"));
use
reference.setThumbnailUrl(obj.getString("image_path"));

java.lang.IllegalStateException: Tried to serialize a command referencing a new, unsaved object(Parse.com)

I am pretty new to Android, and i am trying to build an app using the database API from Parse.com. For like one week, i have the following problem when accesing the database and retrieving the object from the database:
E/ParseCommandCache﹕ saveEventually thread had an error.
java.lang.IllegalStateException: Tried to serialize a command referencing a new, > unsaved object.
at com.parse.ParseCommand.resolveLocalIds(ParseCommand.java:407)
at com.parse.ParseCommand.onPreExecute(ParseCommand.java:306)
at com.parse.ParseRequest$7.then(ParseRequest.java:299)
at com.parse.ParseRequest$7.then(ParseRequest.java:296)
at com.parse.Task$11.run(Task.java:481)
at com.parse.Task$ImmediateExecutor.execute(Task.java:673)
at com.parse.Task.completeAfterTask(Task.java:477)
at com.parse.Task.continueWithTask(Task.java:353)
at com.parse.Task.continueWithTask(Task.java:364)
at com.parse.ParseRequest.executeAsync(ParseRequest.java:296)
at com.parse.ParseRequest.executeAsync(ParseRequest.java:286)
at com.parse.ParseCommandCache.maybeRunAllCommandsNow(ParseCommandCache.java:487)
at com.parse.ParseCommandCache.runLoop(ParseCommandCache.java:597)
at com.parse.ParseCommandCache.access$000(ParseCommandCache.java:26)
at com.parse.ParseCommandCache$2.run(ParseCommandCache.java:146)
Here is my code(I apologize if it is a bit messy, but i've been trying all sorts of things in the last week, and i didn't really have much time for refactoring or cleaning.):
package com.example.boacterapp.Pages;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.gms.maps.MapView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class RecentSightings extends Activity {
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
Alert alert;
List<Alert> alerts;
public ParseGeoPoint coordinates;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.list_view_layout);
}
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(RecentSightings.this);
// Set progressdialog title
mProgressDialog.setTitle("Parse.com Simple ListView Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("AlertsClass");
try {
ob = query.find();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.alertListView);
getDataForListView();
adapter = new CustomAdapter(RecentSightings.this,alerts);
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Capture button clicks on ListView items
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send single item click data to SingleItemView Class
Intent i = new Intent(RecentSightings.this,
AlertViewOnMap.class);
// Pass data "name" followed by the position
i.putExtra("coordinatesLatitude", alerts.get(position).getCoordinates().getLatitude());
i.putExtra("coordinatesLongitude", alerts.get(position).getCoordinates().getLongitude());
i.putExtra("description", alerts.get(position).getDescription().toString());
i.putExtra("busNumber", alerts.get(position).getBusNumber());
// Open SingleItemView.java Activity
startActivity(i);
}
});
}
}
public void getDataForListView(){
final List<Alert> alerts = new ArrayList<Alert>();
for (ParseObject alertParse : ob) {
Alert alert = new Alert();
alert.setBusNumber(alertParse.getInt("BusNumber"));
alert.setCoordinates(alertParse.getParseGeoPoint("Coordinates"));
alert.setCreatedAt(alertParse.getDate("createdAt"));
alert.setDescription(alertParse.getString("Description"));
alerts.add(alert);
}
}
}
class CustomAdapter extends BaseAdapter {
Context context;
//ArrayList<HashMap<String,String>> data;
List<Alert> ob;
public CustomAdapter(Context context, List<Alert> ob){
this.context = context;
this.ob = ob;
}
#Override
public int getCount() {
return ob.size();
}
#Override
public Object getItem(int pos) {
return ob.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item,null,false);
holder.channel = (TextView) convertView.findViewById(R.id.channelVariableLabel);
holder.viewOnMap = (TextView) convertView.findViewById(R.id.viewOnMapVariableLabel);
holder.description = (TextView) convertView.findViewById(R.id.descriptionVariableLabel);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.channel.setText(ob.get(position).getBusNumber());
holder.viewOnMap.setText("<Tap here to view alert on map>");
holder.description.setText(ob.get(position).getDescription().toString());
convertView.setTag(holder);
return convertView;
}
class ViewHolder {
TextView channel;
TextView viewOnMap;
TextView description;
}
}
class Alert {
private int busNumber;
private ParseGeoPoint coordinates;
private Date createdAt;
private String description;
public Alert () {
}
public void setCreatedAt(java.util.Date date) {
// TODO Auto-generated method stub
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public ParseGeoPoint getCoordinates() {
return coordinates;
}
public void setCoordinates(ParseGeoPoint coordinates) {
this.coordinates = coordinates;
}
public int getBusNumber() {
return busNumber;
}
public void setBusNumber(int busNumber) {
this.busNumber = busNumber;
}
}
So please, almighty lords of Programming/Java/Android/Parse.com Users, lend this mortal a hand in finding his problem!
Thank you! Respects.

Categories

Resources