0

I have an application which uses json to get links and texts and now i want to load the image from the downloaded url (by json) in the Listview.

I can load texts in the listview but i can load images!

PLZ help me i have spended 2 days for this and searched,... but no chance! I really need your help! anyone can help me i'll make a great thanks to him in application. PLZZZ help me.

MY CODE :

package rappage.rapfarsi.media.appteam.rapnews;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
 import android.content.Intent;
 import android.graphics.Bitmap;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.support.annotation.Nullable;
 import android.support.v4.app.ListFragment;
 import android.util.Log;
 import android.view.LayoutInflater;
     import android.view.View;
     import android.view.ViewGroup;
   import android.widget.ListAdapter;
  import android.widget.ListView;
 import android.widget.SimpleAdapter;
import android.widget.TextView;
 import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
 import org.json.JSONObject;

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

import rappage.rapfarsi.media.appteam.Articlectivity;
 import rappage.rapfarsi.media.appteam.Main;
  import rappage.rapfarsi.media.appteam.R;
  import rappage.rapfarsi.media.appteam.json.JSONParser;


public class tab2 extends ListFragment {


static final String url_all_products = "http://normaluse.persianrapapp021.ml/article/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_RAPNEWS = "article";
final String TAG_PID = "pid";
final String TAG_TITLE = "title";
final String TAG_PIC = "pic";
final String TAG_WRITER = "writer";
Bitmap bmp;

// JSON Node names

// products JSONArray
JSONArray rapnews = null;


public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


    View v = inflater.inflate(R.layout.tab_2, container, false);
    final View rootView = super.onCreateView(inflater, container, savedInstanceState);




    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();
    // Loading products in Background Thread

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */

    try {



        new LoadAllProducts().execute();

    }catch (Exception e)
    {

        final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity());
        dlgAlert.setMessage("لطفا اینترنت خودرا چک کنید! یا ممکن است سرور از دسترس خارج شده باشد ، برای اخبار اپدیت و مشکلات به ویکی رپ مراجعه کنید!");
        dlgAlert.setTitle("Connection Error!");
        dlgAlert.setNegativeButton("باشه گرفتم", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                startActivity(new Intent(getActivity() , Main.class));
            }
        });

        dlgAlert.create().show();
    }





    return v;

}








class LoadAllProducts extends AsyncTask<String, String, String> {


    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading, Wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                rapnews = json.getJSONArray(TAG_RAPNEWS);

                // looping through All Products
                for (int i = 0; i < 11; i++) {
                    JSONObject c = rapnews.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_TITLE);
                    String pic = c.getString(TAG_PIC);





                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_TITLE, name);
                    map.put(TAG_PIC, pic);




                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
                Intent i = new Intent(getActivity().getApplicationContext(),
                        Main.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * *
     */
    protected void onPostExecute(String file_url) {

        // dismiss the dialog after getting all products
        pDialog.dismiss();

        // updating UI from Background Thread
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        getActivity(), productsList,
                        R.layout.list_item, new String[]{TAG_PID,
                        TAG_TITLE},
                        new int[]{R.id.pid, R.id.txttitle}



                );

                setListAdapter(adapter);

            }
        });

    }

}













public void onListItemClick(ListView l, View v, int position, long id) {
    Toast.makeText(getActivity().getApplicationContext(), "Loading, Please Wait...",
            Toast.LENGTH_LONG).show();

    String pid = ((TextView) v.findViewById(R.id.pid)).getText()
            .toString();

    // Starting new intent
    Intent in = new Intent(getActivity(),Articlectivity.class);
    // sending pid to next activity
    in.putExtra(TAG_PID, pid);

    // starting new activity and expecting some response back
    startActivity(in);
}


}

I WANT TO LOAD IMAGES ATLEAST IN THIS BASE... OR ANYOTHER THING...

AliAk
  • 139
  • 1
  • 11

2 Answers2

0

You can use library by square called Picasso Here is the documentation.

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Here is a custom adapter for a listview having 2 texts and an image

public class CustomArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values1;
    private final String[] values2;

    public CustomArrayAdapter(Context context, String[] values1, String[] values2) {
        super(context, R.layout.some_layout, values1);
        this.context = context;
        this.values1 = values1;
        this.values2 = values2;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
//        LayoutInflater inflater = LayoutInflater.from(context);
//        View rowView = inflater.inflate(R.layout.some_layout, null);
        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            rowView = inflater.inflate(R.layout.some_layout, null);
            holder = new ViewHolder();
            holder.text1 = (TextView) rowView.findViewById(R.id.firstLine);
            holder.text2 = (TextView) rowView.findViewById(R.id.secondLine);
            holder.img = (ImageView) rowView.findViewById(R.id.imageView);
            rowView.setTag(holder);
        }
        else {
            holder=(ViewHolder)rowView.getTag();
        }
        holder.text1.setText(values1[position]);
        holder.text2.setText(values2[position]);
        Picasso.with(rowView.getContext()).load("http://www.9ori.com/store/media/images/8ab579a656.jpg").into(holder.img);
//        if (position%2==0) {
//            holder.img.setImageResource(R.drawable.correct);
//        }
//        else {
//            holder.img.setImageResource(R.drawable.incorrect);
//        }
        return rowView;
    }

    public static class ViewHolder {
        public TextView text1, text2;
        public ImageView img;
    }
}
vaibhav
  • 816
  • 9
  • 13
0

There are lots of image loading library available for android.
Have a look at these

https://github.com/square/picasso
https://github.com/nostra13/Android-Universal-Image-Loader
https://code.google.com/p/android-query/wiki/ImageLoading
https://android.googlesource.com/platform/frameworks/volley
https://github.com/koush/UrlImageViewHelper
https://github.com/novoda/image-loader

Ravi
  • 34,851
  • 21
  • 122
  • 183
  • well i checked them out! and picasso was great , but how should i use it in my simpleListAdapter? – AliAk Oct 14 '15 at 12:25
  • according to me it will be good if you use it with BaseAdapter(CustomAdapter). In case you have any change in future then it will be easy to make changes in baseadapter – Ravi Oct 14 '15 at 12:26
  • are there any tuts. about it? how to use it? – AliAk Oct 14 '15 at 12:27