JSON + picasso图像需要花费太多时间来加载

时间:2016-09-13 09:40:29

标签: java android json picasso

这是我的Activity类加载图片。

package oerrride.we.huzykamz.newsfeed;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

public class MainActivity extends AppCompatActivity {


    ProgressBar pb;


    List<NewsModel> flowerList;
    RecyclerView mRecycler;
    NewsAdapter2 adapter;
    List<MyTask> tasks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb =(ProgressBar) findViewById(R.id.progressBarNews);
        mRecycler =(RecyclerView) findViewById(R.id.recycler_view_news);
        mRecycler.setLayoutManager(new LinearLayoutManager(this));



        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);




        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();




        final String url ="http://10.0.2.2/UgandaMedicalAccess/HealthCentreNews/fecth.php";
        if(netInfo != null && netInfo.isConnectedOrConnecting()) {
            new MyTask().execute(url);
        }
        else{
            Toast.makeText(this,"No network connection! , please check your connectivity",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;
    }
    protected void updateDisplay() {
        adapter = new NewsAdapter2(MainActivity.this, flowerList);
        mRecycler.setAdapter(adapter);
    }




    private class MyTask extends AsyncTask<String, String,List<NewsModel>> {

        @Override
        protected void onPreExecute() {

            setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected List<NewsModel> doInBackground(String... params) {


            String content = HttpManager.getData(params[0], "feeduser", "feedpassword");
            flowerList = NewsParser.parseFeed(content);




                    return flowerList;


        }

        @Override
        protected void onPostExecute(List<NewsModel> newsModels) {
/*   tasks.remove(this);
            if (tasks.size() == 0) {
                pb.setVisibility(View.INVISIBLE);
            }
*/
            pb.setVisibility(View.INVISIBLE);
            if (newsModels == null) {
                Toast.makeText(MainActivity.this, "Data is  not available", Toast.LENGTH_LONG).show();
                return;
            }

            flowerList = newsModels;
            updateDisplay();
        }



    }

}

这是我的 HttpManager.java

package oerrride.we.huzykamz.newsfeed;

import android.util.Base64;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by HUZY_KAMZ on 2/5/2016.
 */
public class HttpManager {


    public static String ata(String uri) {

        BufferedReader reader = null;

        try {
            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

    }

    public static String getData(String uri, String userName, String password) {

        BufferedReader reader = null;
        HttpURLConnection con = null;

        byte[] loginBytes = (userName + ":" + password).getBytes();
        StringBuilder loginBuilder = new StringBuilder()
                .append("Basic ")
                .append(Base64.encodeToString(loginBytes, Base64.DEFAULT));

        try {
            URL url = new URL(uri);
            con = (HttpURLConnection) url.openConnection();

            con.addRequestProperty("Authorization", loginBuilder.toString());

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                int status = con.getResponseCode();
                Log.d("HttpManager", "HTTP response code: " + status);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }


}}

我的 JSONParser

package oerrride.we.huzykamz.newsfeed;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HUZY_KAMZ on 2/7/2016.
 */
public class NewsParser {

    public static List<NewsModel> parseFeed(String content) {

        try {
            JSONArray ar = new JSONArray(content);
            List<NewsModel> flowerList = new ArrayList<>();

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

                JSONObject obj = ar.getJSONObject(i);
                NewsModel healthc = new NewsModel();
                healthc.setDetails(obj.getString("Details"));
                healthc.setHeadlines(obj.getString("Headlines"));
                healthc.setPhoto(obj.getString("photo"));


                flowerList.add(healthc);
            }

            return flowerList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }
}

这是我在RecyclerView中加载我的图片的方式。

@Override
    public void onBindViewHolder(final NewsViewHolder holder,final int position) {
        final  NewsModel feedItems = itemList.get(position);



        holder.root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NewsAdapter2.this.context, NewsInformation.class);
                intent.putExtra(NewsViewHolder.KEY_HEADLINES, feedItems.getHeadlines());
                intent.putExtra(NewsViewHolder.KEY_DETAILS, feedItems.getDetails());

                context.startActivity(intent);


                //Download image using picasso library
                Picasso.with(context).load(url_load_images + feedItems.getPhoto())
                        .error(R.mipmap.ic_launcher).
                        resize(120, 50)
                        .placeholder(R.mipmap.ic_launcher).into(holder.newspic);

                holder.headlines.setText(itemList.get(position).getHeadlines());




            }
        });}

点击ITEM后,JSON数据加上Image加载为什么会这样?

1 个答案:

答案 0 :(得分:0)

基本上,

在使用imageurl加载图片之前,您必须获得picasso(没有更多解决方案),但您可以使用Gson来解析Stream(您正在使用直接并且需要在解析之前将流数据保存到字符串中,它会更快。

P / s不设置适配器,您应该使用notifyDatasetChagnge()刷新适配器。