displaying picture using JSON and Coverflow Library - android

I have problem while diplayin pictures , nothing is dsplayed in the sceen , seems empty only data are displayed no pictures. I think that the problem while parsing JSON Data in pictures.
here in the Fragment of the hotel where i want to display picture gallery.
public class ViewHotels extends AppCompatActivity {
private Bitmap bitmap;
private TextView nom1;
private TextView grade;
private TextView tele;
private ImageView image;
private TextView sit;
private TextView add1;
private TextView email1;
private FloatingActionButton fab;
LinearLayout layout;
private String id;
public static final String URL="http://gabes.comlu.com/Base_Controle/getEmpdetail.php";
private FeatureCoverFlow coverFlow;
private CoverFlowAdapter adapter;
private ArrayList<Game> games;
String image2;
String addresses;
String subject;
public static final String TAG_JSON_ARRAY="result";
ImageView im;
private int imageSource;
public String stringUrl;
public String stringUrl1;
public String stringUrl2;
public String stringUrl3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hotelsdetails);
final Intent intent = getIntent();
layout=(LinearLayout) findViewById(R.id.layout);
coverFlow = (FeatureCoverFlow) findViewById(R.id.coverflow);
settingDummyData();
adapter = new CoverFlowAdapter(this, games);
coverFlow.setAdapter(adapter);
coverFlow.setOnScrollPositionListener(onScrollListener());
id = intent.getStringExtra("Type");
nom1 = (TextView) findViewById(R.id. nom);
grade = (TextView) findViewById(R.id. grade);
tele = (TextView) findViewById(R.id. tele);
image= (ImageView)findViewById(R.id.imageView);
sit=(TextView) findViewById(R.id.site);
add1=(TextView) findViewById(R.id.adde);
email1=(TextView)findViewById(R.id.email);
nom1.setText(id);
im =new ImageView (this);
getEmployee();
}
private void getEmployee(){
final String login11 = nom1.getText().toString().trim();
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewHotels.this,"Fetching...","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}
#Override
protected String doInBackground(Void... v) {
HashMap<String,String> params = new HashMap<>();
params.put("id",login11)
RequestHandler rh = new RequestHandler();
String res= rh.sendPostRequest(URL, params);
return res;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
private void showEmployee(String json){
try {
JSONArray result = new JSONArray(json);
JSONObject c = result.getJSONObject(0);
String name = c.getString("nom");
String tel = c.getString("tele");
String grade1 = c.getString("grade");
String image1 = c.getString("image");
image2 = c.getString("img1");
String image3 = c.getString("img2");
String image4 = c.getString("img3");
String site= c.getString("site");
String add11= c.getString("add");
String email11= c.getString("email");
tele.setText("Tel : \t"+tel);
grade.setText("Grade : \t"+grade1);
sit.setText("site: \t"+site);
add1.setText("adresse :\t" + add11);
email1.setText("email :\t"+ email11);
final ImageView im1 =new ImageView (this);
final ImageView im2 =new ImageView (this);
final ImageView im3 =new ImageView (this);
stringUrl = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg");
stringUrl1 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image2+".jpg");
stringUrl2 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image3+".jpg");
stringUrl3 = ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image4+".jpg");
} catch (JSONException e) {
e.printStackTrace();
}
}
private FeatureCoverFlow.OnScrollPositionListener onScrollListener() {
return new FeatureCoverFlow.OnScrollPositionListener() {
#Override
public void onScrolledToPosition(int position) {
Log.v("ViewHotels", "position: " + position);
}
#Override
public void onScrolling() {
Log.i("ViewHotels", "scrolling");
}
};
}
private void settingDummyData() {
games = new ArrayList<>();
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
games.add(game1);
games.add(game2);
games.add(game3);
}
}
Here is the coverFlow adapter :
public class CoverFlowAdapter extends BaseAdapter {
private ArrayList<Game> data;
private AppCompatActivity activity;
public CoverFlowAdapter(AppCompatActivity context, ArrayList<Game> objects) {
this.activity = context;
this.data = objects;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Game getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_flow_view, null, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
try {
URL myFileUrl = new URL(data.get(position).getImageSource());
Log.e("TAG stringUri",myFileUrl+"" );
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
viewHolder.gameImage.setImageBitmap(BitmapFactory.decodeStream(is));
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
//viewHolder.gameImage.setImageResource(data.get(position).getImageSource());
viewHolder.gameName.setText(data.get(position).getName());
return convertView;
}
private static class ViewHolder {
private TextView gameName;
private ImageView gameImage;
public ViewHolder(View v) {
gameImage = (ImageView) v.findViewById(R.id.image);
gameName = (TextView) v.findViewById(R.id.name);
}
}
}
And this the Game class :
public class Game {
private String name;
private String imageSource;
public Game (String imageSource, String name) {
this.name = name;
this.imageSource = imageSource;
}
public String getName() {
return name;
}
public String getImageSource() {
return imageSource;
}
}

I think (one of) your problem(s) is this part:
Game game1 = new Game("stringUrl","");
Game game2 = new Game("stringUrl1","");
Game game3 = new Game("stringUrl2","");
You are handing over the String "stringUrlx" to your Game-constructor.
In Java, quotation marks("") are used to explicitly define a string, which means that you are handing over "stringUrl" instead of the variable stringUrl, which would have the correct content ("http://gabes.comlu.com/Base_Controle/ImageBD/"+image1+".jpg").
so replace e.g.
Game game1 = new Game("stringUrl","");
by
Game game1 = new Game(stringUrl,"");
That should solve that one issue.
Other than that, you will also run into issues downloading your files and with memory management. I advise you to look into java specific tutorials, which use pre-built asynchronous image loading and caching libraries (such as Glide or Picasso !)

Related

'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference

I just created an application on android optimized for the mobile phone. Now as the client asked to optimize for 17inch screen size without building separate apk. I almost implemented with some minor UI changes. But in case of listviews, they need Gridviews. So What I did was I created a separate layout for bigger screen with gridview I used a code to detect the screen size and in activity I used a code to detect the screen size and if it's bigger, then I initialized Gridview and after async task i added to a cardview adapter and set the gridview adapter to cardview adapter.
I switched gridview and listview as:
if(Constants.isScreenLarge(getActivity())) {
// width > height, better to use Landscape
mygrid = (GridView) getView().findViewById(R.id.card_gridview);
} else {
listView = (ListView)getView().findViewById(R.id.card_listView);
listView.addHeaderView(new View(getActivity()));
listView.addFooterView(new View(getActivity()));
}
Using Restclient helper:
public void fetchTransaction(){
loading.setVisibility(View.VISIBLE);
pd.setMessage("Fetching Transactions..Please Wait");
pd.setCancelable(false);
pd.show();
String fromDate = from.getText().toString();
String toDate = to.getText().toString();
//mydb.deleteAllTransactions();
cardArrayAdapter = new CardArrayAdapter(this.getActivity().getApplicationContext(), R.layout.list_item_card);
cardArrayAdapter.clear();
String android_id = Settings.Secure.getString(getActivity().getContentResolver(),
Settings.Secure.ANDROID_ID);
String userid = prefs.getString("userId","0");
Log.e("TRANSACTON", Constants.BASE_URL_TRANSACTIONS+"?deviceid="+android_id+"&userid="+userid+"&from="+fromDate+"&to="+toDate);
RestClientHelper.getInstance().get(Constants.BASE_URL_TRANSACTIONS+"?deviceid="+android_id+"&userid="+userid+"&from="+fromDate+"&to="+toDate, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
pd.dismiss();
try{
mydb.deleteAllTransactions();
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("result");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String heading = post.optString("heading");
String description = post.optString("description");
String amount = post.optString("amount");
String imageurl = post.optString("imageurl");
String credit = post.optString("credit");
String date = post.optString("date");
String type = post.optString("type");
String service = post.optString("service");
String cost = post.optString("cost");
String balance = post.optString("balance");
String amountinfo = post.optString("amountinfo");
Log.e("ENTERING TO DB","DATA"+i);
Card card = new Card(heading, description,amount,date,credit,imageurl,cost,balance,amountinfo,id,service);
cardArrayAdapter.add(card);
//mydb.addTransactionContact(new TransactionData(heading, description, amount, imageurl,credit,type,date));
}
} catch (JSONException e) {
e.printStackTrace();
}
catch(Exception e){
}
finally {
//showTransaction();
rl = (RelativeLayout)getView().findViewById(R.id.noItems);
rl.setVisibility(view.INVISIBLE);
if(Constants.isScreenLarge(getActivity())) {
// width > height, better to use Landscape
mygrid.setAdapter(cardArrayAdapter);
} else {
listView.setAdapter(cardArrayAdapter);
}
cardArrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onError(String error) {
pd.dismiss();
SnackbarManager.show(Snackbar.with(getActivity()) // context
.text("An Error occured.. Try after sometime"));
textView2.setText("Some Error Ocurred");
rl = (RelativeLayout)getView().findViewById(R.id.noItems);
rl.setVisibility(view.VISIBLE);
loading.setVisibility(View.INVISIBLE);
}
});
}
My CardArrayAdapter code is:
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
private Context mContext;
DatabaseUserTable mydb;
PreferenceHelper prefs;
ProgressDialog pd;
static class CardViewHolder {
TextView line1;
TextView line2;
ImageView cimageView;
TextView amount;
TextView credit;
TextView date;
TextView cost;
TextView balance;
TextView amountinfo;
TextView costinfo;
TextView balanceinfo;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.mContext = context;
mydb = new DatabaseUserTable(this.mContext);
prefs = new PreferenceHelper(this.mContext);
pd = new ProgressDialog(this.mContext);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.line1);
viewHolder.line2 = (TextView) row.findViewById(R.id.line2);
viewHolder.amount = (TextView) row.findViewById(R.id.amount);
viewHolder.date = (TextView) row.findViewById(R.id.date);
viewHolder.credit = (TextView) row.findViewById(R.id.credit);
viewHolder.cimageView = (ImageView) row.findViewById(R.id.imageId);
viewHolder.cost = (TextView) row.findViewById(R.id.cost);
viewHolder.balance = (TextView) row.findViewById(R.id.balance);
viewHolder.amountinfo = (TextView) row.findViewById(R.id.amountinfo);
viewHolder.costinfo = (TextView) row.findViewById(R.id.costinfo);
viewHolder.balanceinfo = (TextView) row.findViewById(R.id.balanceinfo);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getLine1());
viewHolder.line1.setTextColor(Color.parseColor("#000000"));
viewHolder.line2.setText(card.getLine2());
viewHolder.line2.setTextColor(Color.parseColor("#999999"));
viewHolder.amount.setText(card.getAmount());
viewHolder.amount.setTextColor(Color.parseColor("#000000"));
viewHolder.date.setText(card.getDate());
viewHolder.date.setTextColor(Color.parseColor("#999999"));
viewHolder.credit.setText(card.getCredit());
viewHolder.credit.setTextColor(Color.parseColor("#000000"));
viewHolder.cost.setText(card.getCost());
viewHolder.cost.setTextColor(Color.parseColor("#000000"));
viewHolder.balance.setText(card.getBalance());
viewHolder.balance.setTextColor(Color.parseColor("#000000"));
viewHolder.amountinfo.setText(card.getAmountinfo());
viewHolder.amountinfo.setTextColor(Color.parseColor("#000000"));
viewHolder.costinfo.setText("Cost");
viewHolder.costinfo.setTextColor(Color.parseColor("#000000"));
viewHolder.balanceinfo.setText("Balance");
viewHolder.balanceinfo.setTextColor(Color.parseColor("#000000"));
final String salesid = card.getSalesid();
final String servicename = card.getServiceName();
row.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e("TRANSACTIONS SERVICENAM",servicename);
if(servicename.equals("VOUCHER")) {
alertBox(v,salesid);
}
else if(servicename.equals("WALLET")) {
SnackbarManager.show(Snackbar.with(v.getRootView().getContext()) // context
.text("No Reprinting available for this transaction"));
}
else if(servicename.equals("ELECTRICITY")) {
errorAlert(v,"Printing not yet supported");
//alertBoxElectricity(v,salesid);
}
else if(servicename.equals("MONEY TRANSFER")) {
//errorAlert(v,"Printing not yet supported");
alertBoxMoney(v,salesid);
}
else{
alertBoxOther(v,salesid);
}
//Toast.makeText(v.getContext(), amountinfo, Toast.LENGTH_SHORT).show();
/*SnackbarManager.show(Snackbar.with(this) // context
.text(amountinfo));*/
}
});
Log.e("card.getLine1()",card.getLine1());
Log.e("TRASACTION URL",Constants.BASE_URL_IMAGE+card.getUrl());
Picasso.with(mContext).load(Constants.BASE_URL_IMAGE+card.getUrl()).fit().placeholder(R.drawable.mobeeloadicon).error(R.drawable.mobeeloadicon).into(viewHolder.cimageView);
return row;
}
But I got the error as:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a
null object reference
How can I change CardArrayAdapter as GridViewAdapter preserving all the Card data. Any Help please
UPDATE
I got this right. It was a silly mistake. I was populating the wrong layout.

Fetching image from database into Android GridView

I am trying to fetch a text and image link from the database and add it to an ArrayList and then use it to display the text and image in a grid view. But it doesn't show up. It seems like the list items seem to be null when I try to add it.
What am I missing? I have gone through some answers and wasn't able to figure it out.
public final class GridAdapter extends BaseAdapter {
public static final String showUrl = "http://netbigs.com/apps/fetch.php";
String myJSON;
public String mvname;
String mvinfo;
public String rdate,imglink;
private Context mContext;
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
private static final String TAG_RESULTS = "result";
private static final String TAG_ID = "mvid";
private static final String TAG_NAME = "mvname";
private static final String TAG_IMG = "imglink";
private static final String TAG_DATE = "rdate";
private static final String TAG_MOVINF = "mvinfo";
JSONArray movies = null;
public GridAdapter(Context context) {
mItems.add(new Item(mvname,imglink));
mContext=context;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public Item getItem(int i) {
return mItems.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
getData();
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
Picasso.with(this.mContext).load(item.drawableId).into(picture);
name.setText(item.name);
System.out.println(item.name);
return v;
}
private static class Item {
public final String name;
public final String drawableId;
Item(String name, String drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
protected void showList(){
try{
JSONObject jsonObj = new JSONObject(myJSON);
movies = jsonObj.getJSONArray(TAG_RESULTS);
for (int i=0;i<movies.length();i++){
JSONObject c = movies.getJSONObject(i);
String mvid = c.getString(TAG_ID);
mvname = c.getString(TAG_NAME);
System.out.println(mvname);
imglink = c.getString(TAG_IMG);
System.out.println(imglink);
rdate = c.getString(TAG_DATE);
mvinfo = c.getString(TAG_MOVINF);
try {
}
catch (Exception e){
e.printStackTrace();
}
}
}
catch (JSONException e){
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String uri = showUrl;
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream inputStream = null;
String result = null;
inputStream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
This is the fragment to which the GridAdapter is attached.
public class MovieFragment extends Fragment {
public MovieFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_movie, container, false);
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new GridAdapter(getActivity()));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i;
switch (position){
case 0:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 1:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 2:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
case 3:
i = new Intent(MovieFragment.this.getActivity(),MovieDetail.class);
startActivity(i);
break;
}
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
You are calling getData() from your Adapter so it may possible that when you initialize it at that time your list is null.
Try calling that method form your activity or fragment and then pass the received data you received in your adapter class.
getView() is called multiple time when you scroll up or down so never call any api in that method
Provide the code where you are using this adapter.
the problem is you are not getting values from the DB.
you must get the values from the db first. by using Volley or some plugin like that(or Aysnc task. volley will be better i think.)

How to set all values in listview android

I have created a listview. All values are retrieved from the json response but only the last values were displayed in the list.what to do for displaying the all values in list view.
SixFragment.movieList = new ArrayList<Movie1>();
for (int i1 = 0; i1 < jsonArray3.length(); i1++) {
try {
JSONObject jsonObject = jsonArray3.getJSONObject(i1);
review_rating = jsonObject.optString("review_rating").toString();
username_rate = jsonObject.optString("username").toString();
review_title = jsonObject.optString("review_title").toString();
review_desc = jsonObject.optString("review_desc").toString();
sleep = jsonObject.optString("Sleep").toString();
location = jsonObject.optString("Location").toString();
service = jsonObject.optString("Service").toString();
rooms = jsonObject.optString("Rooms").toString();
cleanliness = jsonObject.optString("Cleanliness").toString();
userimage1 = jsonObject.optString("user_image").toString();
Movie1 movie = new Movie1();
movie.setRate_userimage(userimage1);
movie.setreview_rating(review_rating);
movie.setusername_rate(username_rate);
movie.setreview_title(review_title);
movie.setreview_desc(review_desc);
movie.setsleep(sleep);
movie.setlocation(location);
movie.setservice(service);
movie.setraterooms(rooms);
movie.setcleanliness(cleanliness);
SixFragment.movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
This is my fragment page:
public class SixFragment extends Fragment{
public static String userimage;
public static String review_rating;
public static String username_rate;
public static String review_title;
public static String review_desc;
public static String sleep;
public static String location;
public static String service;
public static String rooms;
public static String cleanliness;
public static ArrayList stringArray;
public static ArrayList<Movie1> movieList= new ArrayList<Movie1>();;
ListView listView;
Reviewadapter reviewadapter;
public SixFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_six, container, false);
ListView list=(ListView)v.findViewById(R.id.six_listView);
return v;
}
}
This logcat error`
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.airstar.abservetech.airstar, PID: 27390
java.lang.NullPointerException
at com.airstar.abservetech.adapter.Reviewadapter.getCount(Reviewadapter.java:160)
at android.widget.ListView.setAdapter(ListView.java:488)
at com.airstar.abservetech.airstar.SixFragment.onCreateView(SixFragment.java:75)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
`
Review adapter
public class Reviewadapter extends BaseAdapter {
private final List<Movie1> movieItems;
public SixFragment context;
OneFragment Fragment;
Bitmap bitmap;
public Reviewadapter(SixFragment context, List<Movie1> movieItems) {
this.context = context;
this.movieItems = movieItems;
this.Fragment=Fragment;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
convertView = inflater.inflate(R.layout.fragment_sixlist,parent,false);
CircleImageView profile_image = (CircleImageView) convertView.findViewById(R.id.profile_image);
TextView rate_username = (TextView) convertView.findViewById(R.id.rate_username);
RatingBar ratingBar = (RatingBar) convertView.findViewById(R.id.ratingBar);
TextView rate_title = (TextView) convertView.findViewById(R.id.rate_title);
TextView rate_description = (TextView) convertView.findViewById(R.id.rate_description);
RatingBar ratingBar_sleep = (RatingBar) convertView.findViewById(R.id.ratingBar_sleep);
RatingBar ratingBar_location = (RatingBar) convertView.findViewById(R.id.ratingBar_location);
RatingBar ratingBar_service = (RatingBar) convertView.findViewById(R.id.ratingBar_service);
RatingBar ratingBar_clearness = (RatingBar) convertView.findViewById(R.id.ratingBar_clearness);
RatingBar ratingBar_rooms = (RatingBar) convertView.findViewById(R.id.ratingBar_rooms);
final Movie1 m = movieItems.get(position);
// Glide.with(context)
// .load(m.getRate_userimage())
// .diskCacheStrategy(DiskCacheStrategy.ALL)
// .into(profile_image);
URL url = null;
String image=m.getRate_userimage();
try {
url = new URL(image);
InputStream is = null;
// Bitmap bitMap = BitmapFactory.decodeStream(is);
//create imageview dynamically
Glide.with(context).load(String.valueOf(url)).into(profile_image);
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Glide.with(context).load(String.valueOf(url)).into(profile_image);
if (m.getusername_rate()!=null)
{
if (!m.getusername_rate().equals("null"))
{
rate_username.setText(m.getusername_rate());
}}
if (m.getreview_rating()!=null)
{
if (!m.getreview_rating().equals("null"))
{
ratingBar.setRating(Float.parseFloat(m.getreview_rating()));
}}
if (m.getsleep()!=null)
{
if (!m.getsleep().equals("null"))
{
ratingBar_sleep.setRating(Float.parseFloat(m.getsleep()));
}}
}
return convertView;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
}
In Your Fragment make your list static:
public class SixFragment extends Fragment{
// Your code
//------------DO THIS------------------///
public static List<Movie1> movieList = new ArrayList<Movie1>();
public SixFragment() {
// Required empty public constructor
}
//Your code
}
Rest of the code in your fragment will be as it is.
Change your JSON loop like this :
SixFragment.movieList = new ArrayList<Movie1>();
for (int i1 = 0; i1 < jsonArray3.length(); i1++) {
try {
JSONObject jsonObject = jsonArray3.getJSONObject(i1);
review_rating = jsonObject.optString("review_rating").toString();
username_rate = jsonObject.optString("username").toString();
review_title = jsonObject.optString("review_title").toString();
review_desc = jsonObject.optString("review_desc").toString();
sleep = jsonObject.optString("Sleep").toString();
location = jsonObject.optString("Location").toString();
service = jsonObject.optString("Service").toString();
rooms = jsonObject.optString("Rooms").toString();
cleanliness = jsonObject.optString("Cleanliness").toString();
userimage1 = jsonObject.optString("user_image").toString();
Movie1 movie = new Movie1();
movie.setRate_userimage(userimage1);
movie.setreview_rating(review_rating);
movie.setusername_rate(username_rate);
movie.setreview_title(review_title);
movie.setreview_desc(review_desc);
movie.setsleep(sleep);
movie.setlocation(location);
movie.setservice(service);
movie.setraterooms(rooms);
movie.setcleanliness(cleanliness);
SixFragment.movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}

Cannot show image in listview from json

May be this question many times.
i am getting some data from server and showing in listview . every thing working fine but i am getting problem to show image in list view.
Here is my example code
public class MainActivity extends ListActivity {
private static String url = null;
private static final String book_name = "b_name";
private static final String book_detail = "b_publisher";
private static final String book_image = "b_image";
ProgressDialog progressDialog;
ListView lv;
String cus_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
url = getResources().getString(R.string.url);
/*----Receiving data from Splash Activity-----*/
Bundle b = getIntent().getExtras();
cus_id = b.getString("custom_id");
new ProgressTask(MainActivity.this).execute();
}
class ProgressTask extends AsyncTask<String, Integer, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(final Boolean success) {
progressDialog.dismiss();
}
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
setBookImageUrl(b_image);
setBookName(b_name);
setBookDetail(b_detail);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
public String getBookImageUrl() {
return book_image;
}
public CharSequence getBookName() {
return book_name;
}
public CharSequence getBookDetail() {
return book_detail;
}
public void setBookImageUrl(String imgeUrl) {
book_image = imgeUrl;
}
public void setBookName(String b_name) {
book_name = b_name;
}
public void setBookDetail(String b_detail) {
book_detail = b_detail;
}
}
BookListAdapter class:
public class BookListAdapter extends ArrayAdapter<MainActivity> {
private ArrayList<MainActivity> bookModels;
private Context context;
public BookListAdapter(Context context, int resource,
ArrayList<MainActivity> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_list_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView.findViewById(R.id.icon);
viewHolder.bookName = (TextView) rowView.findViewById(R.id.b_name);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.b_detail);
rowView.setTag(viewHolder);
}
final MainActivity bookModel = bookModels.get(position);
ViewHolder holder = (ViewHolder) rowView.getTag();
Picasso.with(context).load(bookModel.getBookImageUrl())
.into(holder.bookIcon);
holder.bookName.setText(bookModel.getBookName());
holder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
i can show book name and book detail in listview finely but image is not showing ..
i am getting value for book_image is http:\/\/X.X.X.X\/admin\/book_images\/232513pic9.png how to show in listview from that path..
I think you will need to implement your own adapter and use some library to display the image from URL.
My recommendation is Picasso
This is an example to implement your own adapter
BookListAdapter.java
public class BookListAdapter extends ArrayAdapter<BookModel> {
private ArrayList<BookModel> bookModels;
private Context context;
public BookListAdapter(Context context, int resource, ArrayList<BookModel> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.book_child_list, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView
.findViewById(R.id.bookIcon);
viewHolder.bookName = (TextView) rowView
.findViewById(R.id.bookName);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.bookDetail);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
final BookModel bookModel = bookModels.get(position);
Picasso.with(context).load(bookModel.getBookImageUrl()).into(viewHolder.bookIcon);
viewHolder.bookName.setText(bookModel.getBookName());
viewHolder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
BookModel.java
public class BookModel {
private String bookName;
private String bookDetail;
private String bookImageUrl;
public BookModel() {
bookName = "";
bookDetail = "";
bookImageUrl = "";
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDetail() {
return bookDetail;
}
public void setBookDetail(String bookDetail) {
this.bookDetail = bookDetail;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public void setBookImageUrl(String bookImageUrl) {
this.icons = bookImageUrl;
}
}
Where BookModel class is a class where you can wrap your data (book name, book detail, book image) and pass it as a list to the adapter.
for example :
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
ArrayList<BookModel> bookModelList = new ArrayList<BookModel>();
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
BookModel bookModel = new BookModel();
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
bookModel.setBookName(b_name);
bookModel.setBookDetail(b_detail);
bookModel.setBookImageUrl(b_image);
bookModelList.add(bookModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if(bookModelList.size()>0) {
BookListAdapter bookListAdapter = new BookListAdapter(MainActivity.this, R.id.yourlistview, bookModelList );
}
return null;
}
I hope my answer can help you!
lv.setAdapter(adapter);
use AQuery lib.
and just write this code in your custom adapter:
AQuery aQuery = new AQuery(context);
aQuery.id(your image id).image(your url,true,true);

Android GridView Adapter using ArrayList

I'm stuck creating an Adapter for my Griview that accepts an ArrayList. I think the bad line in the Adapter class is: viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position)); and it appears that the call .setImageResource is the problem.
public class JGrid66 extends Activity {
JSONObject jsonOb;
JSONArray JSArrGallery = null;;
GridView grid65_gv;
JGrid66Adapter2 jGr7Adap;
ProgressDialog mProgressDialog;
ArrayList<String> idStrArrList = new ArrayList<String>();
ArrayList<String> urlStrArrList = new ArrayList<String>();
ArrayList<String> descrStrArrList = new ArrayList<String>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
static String FLAG = "flag";
private String jsonUrl = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jgrid66);
grid65_gv = (GridView) findViewById(R.id.jgrid66_gv);
}//--- END onCreate
//--- DownloadJSON Class
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(jsonUrl);
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
idStrArrList.add(idStr);
urlStrArrList.add(urlStr);
descrStrArrList.add(descrStr);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
return null;
}
#Override
protected void onPostExecute(Void args) {
jGr7Adap = new JGrid66Adapter2(JGrid66.this, urlStrArrList);
grid65_gv.setAdapter(jGr7Adap);
jGr7Adap.notifyDataSetChanged();
}
}
//--- END DownloadJSON Class
}
Here;s the Adapter:
public class JGrid66Adapter2 extends BaseAdapter {
private ArrayList<String> urlStrArrList;
Context context;
public JGrid66Adapter2(Context context,ArrayList<String> urlStrArrList) {
super();
this.urlStrArrList = urlStrArrList;
}
#Override
public int getCount() {
return urlStrArrList.size();
}
#Override
public String getItem(int position) {
return urlStrArrList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView wcbc_image_iv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHldr;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if(convertView==null){
viewHldr = new ViewHolder();
convertView = inflater.inflate(R.layout.jgrid66_item, null);
viewHldr.wcbc_image_iv = (ImageView) convertView.findViewById (R.id.jgrid66_iv);
convertView.setTag(viewHldr);
}
else
{
viewHldr = (ViewHolder) convertView.getTag();
}
//--- I commented this out because this is where it breaks.
//viewHldr.wcbc_image_iv.setImageResource(urlStrArrList.get(position));
return convertView;
}
}
Any help would be great!
private ArrayList<String> urlStrArrList;
is arraylist of strings. If you have the url you need to download the images and then set it to imageview.
setImageResource takes a resource id as a param which is an int value.
public void setImageResource (int resId)
Added in API level 1
Sets a drawable as the content of this ImageView.
You may consider using Lazy Loading Universal Image Loader or using picasso
Caching images and displaying

Categories

Resources