image loading using url in android

痞子三分冷 提交于 2019-12-11 10:05:42

问题


i was tring to load image using url.a single url is working properly. but i need to add a few more images to this page.i need to add this image s to a list view.pls tell me how can i add a string array to this code.

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FareCrd extends Activity {



    String image_url="http://movito.nervov.com/img/ace-hd.png";
    String[] mString ={"http://movito.nervov.com/img/ace-hd.png",
            "http://movito.nervov.com/img/Movito_Logo_M.png"};

JSONArray jsonary;

    ListView list;
    private Activity activity;
    private String[] data;
    private static View inflater=null;
    //private String[] mStrings={"http://movito.nervov.com/img/ace-hd.png"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fare_crd);
        list=(ListView)findViewById(R.id.farelist);



        new ServConn().execute(); 



    }


private void parsedata(String data){
    //System.out.println(data);

        try {
            JSONObject json = new JSONObject(data);

            jsonary = json.getJSONArray("data");


            ListView list = (ListView) findViewById(R.id.farelist);

            list.setAdapter(new DriverOrderList(getApplicationContext(),
                    R.layout.farecrd, new JSONObject[jsonary.length()]));



        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

private class DriverOrderList extends ArrayAdapter<JSONObject> {

    int listViewResource;


    public DriverOrderList(Context context, int resource, JSONObject[] s) {
        super(context, resource, s);
        listViewResource = resource;


    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(listViewResource, parent, false);
        ImageLoader imgLoader = new ImageLoader(getApplicationContext());   
        JSONObject rowdata = new JSONObject();
        int loader = R.drawable.stub;


        try {


            rowdata = jsonary.getJSONObject(position);
            System.out.println(rowdata);

             ImageLoader imgLoader1 = new ImageLoader(getApplicationContext());
        ImageView img=(ImageView) row.findViewById(R.id.imgid);



        imgLoader.DisplayImage(image_url, loader, img);


        TextView nameTxt = (TextView) row.findViewById(R.id.truckname);         
        TextView idTxt = (TextView) row.findViewById(R.id.id);



        TextView minrttv =(TextView) row.findViewById(R.id.minimumRate);
        TextView kmrttxt =(TextView) row.findViewById(R.id.kilometerRate);
        TextView mindurtv=(TextView) row.findViewById(R.id.minimumDuration);
        TextView freewatintim = (TextView) row.findViewById(R.id.freeWaitingTime);
        TextView minuterttxt =(TextView) row.findViewById(R.id.minuteRate);
        TextView watingchrttv =(TextView)row.findViewById(R.id.waitingCharge);

        double freewt=(Double) rowdata.get("freeWaitingTime");
        double kmratetxt=(Double) rowdata.get("kilometerRate");
        double mindurtxt=(Double) rowdata.get("minimumDuration");
        double mindur= mindurtxt/60;
        double minkmrttxt=(Double) rowdata.get("minimumKilometer");     
        double minrttxt=(Double) rowdata.get("minimumRate");
        double mintrate=(Double) rowdata.get("minuteRate");
        double minutrat=mintrate/60;
        double watingchrtxt=(Double) rowdata.get("waitingCharge");
        double waitchgunittxt=(Double) rowdata.get("waitingChargeUnit");



            nameTxt.setText(rowdata.getString("truckModel"));
            minrttv.setText("Rs."+minrttxt+" /-");
            kmrttxt.setText("Rs."+kmratetxt+"/km after "+minkmrttxt+"km");
            mindurtv.setText("first"+mindur+"hr and "+minkmrttxt+"km");
            //minuterttxt.setText(minutrat+"/-");
            freewatintim.setText("first "+freewt+"min free");
            watingchrttv.setText("RS"+watingchrtxt+"after every "+waitchgunittxt+"min");

        }   
         catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



         return row;
    }

}



private class ServConn extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        System.out.println("do in backgrnd");
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://movito.nervov.com/v1/trucks/miniTruckCategories");

        httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
        String replyString = "";

        try {

            HttpResponse response = httpclient.execute(httpget);
            replyString = EntityUtils.toString(response
                    .getEntity());



        } catch (ClientProtocolException e) {

        System.out.println("ex: " + e);
        } catch (IOException e) {

        System.out.println("e: " + e);
        }


    return replyString;

}

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        System.out.println(result);
        result = "{\"data\":"+result+"}";


        parsedata(result);

    }
     @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
}



}

回答1:


Try to use Glide libreries instead od picasso .It might help full for you.Please look at following link which might help you out. http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en




回答2:


try this code I am using Picasso library to populate ImageView,

if you are using android studio add this library using following code into your gradle file

compile 'com.squareup.picasso:picasso:2.5.2'

use following code,

It is complete example of how you can make a custom ListView, I didn't include code where you have to get he JSON data from WebService as i didn't want to make the code complicated, I will write a separate code where i will show how to read the data you are interested in.

XML

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <ListView
        android:id="@+id/CustomListViewActivity_listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

single_item.xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/single_item_textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:layout_weight="0.5"
        android:text="New Text" />

    <ImageView
        android:id="@+id/single_item_imageView"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_margin="4dp"
        android:layout_weight="0.5" />
</LinearLayout>

Code

public class CustomListViewActivity extends AppCompatActivity {

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


        ArrayList<SingleItem> singleItems = new ArrayList<>();
        singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","first Text"));
        singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","Second Text"));
        singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","third Text"));
        singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","fourth Text"));

        ListView listView = (ListView)findViewById(R.id.CustomListViewActivity_listView);
        MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item,singleItems);
        listView.setAdapter(adapter);


    }

    private class MyAdapter extends ArrayAdapter {

        private ArrayList<SingleItem> singleItems;
        private LayoutInflater layoutInflater;
        private Context context;
        private View single_View;

        public MyAdapter(Context context, int resource, ArrayList<SingleItem> singleItems) {
            super(context, resource, singleItems);
            this.context = context;
            this.singleItems = singleItems;
            layoutInflater = LayoutInflater.from(this.context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewHolder holder = null;

            if (row == null) {
                row = layoutInflater.inflate(R.layout.single_item, parent, false);

                holder = new ViewHolder();
                holder.textView = (TextView) row.findViewById(R.id.single_item_textView);
                holder.imageView = (ImageView) row.findViewById(R.id.single_item_imageView);
                row.setTag(holder);
            } else {
                holder = (ViewHolder) row.getTag();
            }

            final SingleItem singleItem = singleItems.get(position);
            holder.textView.setText("" + singleItem.getText());
            Picasso.with(context).load(""+singleItem.getUrl()).into(holder.imageView);

            return row;
        }

        private class ViewHolder {
            // Instance Variable (state or data)
            TextView textView;
            ImageView imageView;
        }
    }

    public class SingleItem {

        private String url;

        private String text;

        public SingleItem() {
        }

        public SingleItem(String url, String text) {
            this.url = url;
            this.text = text;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    }
}

Output

As you will see the loading the images from the URL provided to the appropriate ImageView is taken care by Picasso, do make sure you add the permission for the internet in the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />



来源:https://stackoverflow.com/questions/34608933/image-loading-using-url-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!