Reputation: 139
I'm writing my biggest application and now I have written a json code which gets text from server and shows in list view. Until here everything is ok, but my problem is that I want to show image in my list too.
I have made some changes in my code to show image in list but I always get no image.
I have seen many answers but didn't work. If its possible to solve my problem with picaso lib please help me with that or any other things.
Here is my code:
list_item.xml
<RelativeLayout
android:layout_height="wrap_content" android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/tools"
android:id="@+id/rl">
<RelativeLayout
android:id="@+id/card_view3"
android:layout_width="fill_parent"
android:layout_height="110dp"
card_view:cardCornerRadius="4dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:padding="16dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@drawable/listrowbg"
android:layout_marginTop="12dp">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/imageView6"
android:background="@drawable/newshead"
android:layout_alignParentTop="true"
android:layout_marginBottom="2dp" />
<ImageView
android:layout_width="70dp"
android:layout_height="fill_parent"
android:id="@+id/ico"
android:background="@drawable/standinpic"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_below="@+id/imageView6"
android:layout_marginTop="3dp" />
<TextView
android:id="@+id/txttitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="14dip"
android:textColor="#fafafa"
android:textDirection="ltr"
android:textStyle="bold"
android:singleLine="false"
android:maxLines="3"
android:maxLength="100"
android:maxWidth="200dp"
android:width="200dp"
android:phoneNumber="false"
android:text="Abadi - SohMj"
android:layout_alignLeft="@+id/imageView6"
android:layout_alignStart="@+id/imageView6"
android:layout_above="@+id/ico"
android:layout_alignTop="@+id/pid"
android:layout_marginTop="-4dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView5"
android:background="@drawable/more"
android:layout_alignBottom="@+id/ico"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="15dp" />
<TextView
android:id="@+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtexe"
android:textColor="#ffc53220"
android:textSize="18dp"
android:typeface="sans"
android:layout_alignBottom="@+id/imageView5"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</RelativeLayout>
Tab1 ( get news)
public class tab1 extends ListFragment {
static final String url_all_products = "http://persiancoder.tk/rapnews/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 = "rapnews";
final String TAG_PID = "pid";
final String TAG_TITLE = "title";
final String TAG_PIC = "pic";
final String TAG_WRITER = "writer";
// 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_1, container, false);
final View rootView = super.onCreateView(inflater, container, savedInstanceState);
final ImageView vi =(ImageView)rootView.findViewById(R.id.ico);
/**
String result = "";
InputStream isr = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://persiancoder.tk/rapnews/get_all_products.php");
//conn.setConnectTimeout(7000);
//YOUR PHP SCRIPT ADDRESS
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
//parse json data
try {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
String n = "";
String a = "";
String j = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
String pic = json.getString("pic");
TAG_PIC = pic.toString();
}
} catch (Exception e) {
Log.e("log_tag", "Error Parsing Data " + e.toString());
android.support.v7.app.AlertDialog.Builder dlgAlert = new android.support.v7.app.AlertDialog.Builder(getActivity());
dlgAlert.setMessage("مشکلی نامعلوم پیش آمده!اینترنت خود را چک کنید");
dlgAlert.setTitle("Unknown Problem!");
dlgAlert.setCancelable(false);
dlgAlert.setNegativeButton("باشه", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
}
**/
// 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 {
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,TAG_PIC},
new int[]{R.id.pid, R.id.txttitle,R.id.ico}
);
setListAdapter(adapter);
}
});
}
// Declaring Your View and Variables
}
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;
}
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(),Shownews.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
}
Upvotes: 0
Views: 1969
Reputation: 6050
It's always good not to reinvent the wheel. While loading image from URL there are many things that one has to keep in mind :
The most efficient library I have used is Universal Image Library. https://github.com/nostra13/Android-Universal-Image-Loader
It is pretty efficient and easy to use. You can find easy to follow sample here : https://github.com/nostra13/Android-Universal-Image-Loader/tree/master/sample
Upvotes: 1