简体   繁体   中英

JSON + picasso Images taking too much time to load

This is my Activity class which loads images .

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();
        }



    }

}

And this is my HttpManager.java Class

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;
                }
            }
        }


}}

My JSONParser class

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;
        }

    }
}

This is how am loading my Images in the 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());




            }
        });}

The JSON data plus the Image loads , after clicking on the ITEM why is this??

Basically,

You must get imageurl before use picasso to load image (there is no more solution), However you can use Gson to parse Stream (you're using directly and need save stream data to string before parse), it will make faster.

P/s Don't set Adapter, you should use notifyDatasetChagnge() to refresh adapter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM