无法从MongoDb的视图分页器中获取图像

时间:2018-10-17 13:20:16

标签: android node.js mongodb android-studio

我在活动中定义了View pager,并且我正在使用NodeJs和MongoDb作为后端服务。我试图从MongoDb中获取图像,并在View pager中显示以从后端获得响应,我正在使用凌空网络库。 但是问题是即使没有错误,视图寻呼机中也没有图像显示。

下面是我的代码:

DiscViewPager.java

public class DiscViewPager extends PagerAdapter {

private LayoutInflater layoutInflater;
Context context;
private List<OfferImageModel> offers;

public DiscViewPager(List<OfferImageModel> offers,Context context) {
this.context = context;
this.offers = offers;
}

@Override
public int getCount() {
return offers.size();
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return (view == o);
}

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) 
{

layoutInflater = (LayoutInflater) 
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
assert layoutInflater != null;
View view = layoutInflater.inflate(R.layout.custom_offer, null);

ImageView offerImage = view.findViewById(R.id.offerImage);

OfferImageModel model = offers.get(position);

Picasso.with(context).load(model.getImage()).fit().
centerInside().into(offerImage);

ViewPager vp = (ViewPager) container;
vp.addView(view, 0);


return view;
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {

ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);

  }
 }

Home.java

 public class TestViewPager extends AppCompatActivity {

ViewPager discImages;
RequestQueue  discQueue;
StringRequest discRequest;
private static final String OFFER_URL = "https://tiffino.herokuapp.com/offers";

List<OfferImageModel> offers;
DiscViewPager adapter;
TabLayout offertabLayout;
String str1 = "Ajmer";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_view_pager);

    discImages = findViewById(R.id.viewPager2);
    offertabLayout = findViewById(R.id.Tab2);

    offertabLayout.setupWithViewPager(discImages, true);

    offers = new ArrayList<>();

    loadDiscViewPager();

}

private void loadDiscViewPager() {

    final ProgressDialog prg = new ProgressDialog(TestViewPager.this);
    prg.setMessage("Loading...");
    prg.show();

    discQueue = Volley.newRequestQueue(TestViewPager.this);

    discRequest = new StringRequest(Request.Method.POST, OFFER_URL, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            try {
                JSONArray jsonArray = new JSONArray(response);

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String loadImages = jsonObject.getString("Image");

                    OfferImageModel model = new OfferImageModel(loadImages);
                    offers.add(model);
                }

                adapter = new DiscViewPager(offers,TestViewPager.this);

                discImages.setAdapter(adapter);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener()

    {
        @Override
        public void onErrorResponse(VolleyError error) {


        }
    })

    {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            HashMap<String, String> params = new HashMap<>();
            params.put("place",str1);

            return params;
        }
    };

    discQueue.add(discRequest);
  }
 }

OfferImageModel.java

public class OfferImageModel {

String Image;


public OfferImageModel() {

}

public OfferImageModel(String image) {
Image = image;
}

public String getImage() {
return Image;
}

public void setImage(String image) {
Image = image;
 }
}

服务器端代码

var express = require('express');    
var MongoClient = require('mongodb').MongoClient;
var url = "https://example.com";
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true})); 

app.post('/offers',(req, res) => {

 MongoClient.connect(url, (err, db) => {           
    if(err) throw err;
    var obj = req.body.place;
    var dbo = db.db('Tiffino_db');

    dbo.collection("Offers")
        .find({ Name: obj },{ projection: { _id: 0 } })
        .toArray((err, result) => {
             result.forEach((err, doc) => {
                 if (err) {
                     console.log("Error:", +err);
                 }
                 else { 
                    output = result.map(r => ({"Image":r.Image}));
                    res.status(200).json(output);
                    db.close();
                }
            });
        });
   });
});

服务器响应

[
  {
    "Image": "https://firebasestorage.googleapis.com/v0/b/tiffino-b6901.appspot.com/o/Offer%20Images%2Fmealbanner.png?alt=media&token=d46a2834-5948-45e0-9964-d3f8705d4c1a"
  },
  {
    "Image": "https://firebasestorage.googleapis.com/v0/b/tiffino-b6901.appspot.com/o/Offer%20Images%2Fjuices.png?alt=media&token=8f28e147-7d38-42f1-bd0f-9613b8309836"
  },
  {
    "Image": "https://firebasestorage.googleapis.com/v0/b/tiffino-b6901.appspot.com/o/Offer%20Images%2Fcombo.png?alt=media&token=296f5fa8-2740-4963-bb3a-4762882e13e2"
  },
  {
    "Image": "https://firebasestorage.googleapis.com/v0/b/tiffino-b6901.appspot.com/o/Offer%20Images%2Fcombo.png?alt=media&token=296f5fa8-2740-4963-bb3a-4762882e13e2"
  }
]

请让我知道上面代码中做错了什么。

谢谢

1 个答案:

答案 0 :(得分:0)

您正在android端进行json解析,因此您需要从node.js后端发送json响应。

您的后端代码应为a=2 def foo(): if a>1: a=3 return a