cannot setvisibility in listview - android

Here is to control visibility of the layout
if (!(imagepath[i].toString().equals("no picture"))) {
try {
aURL = new URL("http://www.orientaldaily.com.my/"
+ imagepath[i]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
layout_image.setVisibility(View.VISIBLE);
imageview.setVisibility(View.VISIBLE);
imageview.setScaleType(ScaleType.CENTER_CROP);
imageview.setImageBitmap(bm);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
}
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.main_alllatestnewslist, from, to);
lv.setAdapter(adapter);
Here is to initialize it
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_alllatestnews);
lv = (ListView) findViewById(android.R.id.list);
RelativeLayout temp = (RelativeLayout)findViewById(R.id.layout_temp);
LayoutInflater liInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
temp.addView(liInflater.inflate(R.layout.main_alllatestnewslist, null));
Here is the main_alllatestnews.xml
<LinearLayout
android:id="#+id/layout_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/layout_menu"
android:layout_below="#id/layout_title"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Here is the main_alllatestnewslist.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_temp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/background_news_list" >
<LinearLayout
android:id="#+id/layout_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10px"
android:layout_marginTop="10px" >
<ImageView
android:id="#+id/image_alllatestnewstitle"
android:layout_width="134px"
android:layout_height="80px"
android:src="#drawable/image_loading_failed_1"
android:visibility="invisible" />
</LinearLayout>
When i run this, it gave me Nullpointerexception at line
temp.addView(liInflater.inflate(R.layout.main_alllatestnewslist, null)); <-- inflater still null...
How to solve this?

Change
setContentView(R.layout.main_alllatestnews);
to
setContentView(R.layout.main_alllatestnewslist);
because layout_image is in layout main_alllatestnewslist
Edited:
LayoutInflater liInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
yourView.addView(liInflater.inflate(R.layout.main_alllatestnewslist, null))
something like that.
;

Related

JSon array response on android imagebuttons with onclick

I'm sorry, my question was just one row appear
and in my project image_url1,2,3,4,5 is act on another activity by intent, and it works well already
i can't upload image, please look below picture
┌──────┐┌──────┐┌──────┐┌──────┐┌──────┐
│■■■■■■││ ││ ││ ││ │
│■■■■■■││ ││ ││ ││ │
└──────┘└──────┘└──────┘└──────┘└──────┘
only first url parsing works another didn't....
(first box parsed to image_url, when it clicks image_url1,2,3,4,5 appear)
i want all rows appear, not one row
before i ask question, i need to learn English more......
I want these json array response on my application imagebuttons(or gridview)
i get an array of images from WAS and each row data act as button
json array is here
{
"total" : 2,
"row" : [
{
"id": "c3asfasfas35sd4a35as5d4a3",
"image_name": "20150913151562135",
"image_url": "http://myurl/imagelocation.jpg",
"flag": null,
"price": "1200000",
"image_url1": "http://image_url1/imagelocation.jpg",
"image_url2": "http://image_url2/imagelocation.jpg",
"image_url3": "http://image_url3/imagelocation.jpg",
"image_url4": "http://image_url4/imagelocation.jpg",
"image_url5": "http://image_url5/imagelocation.jpg",
"image_url6": "http://image_url6/imagelocation.jpg",
},
{
"id": "c3asfasfas35sd4a35as5d4a3",
"image_name": "20150913151562135",
"image_url": "http://myurl/imagelocation.jpg",
"flag": null,
"price": "1200000",
"image_url1": "http://image_url7/imagelocation.jpg",
"image_url2": "http://image_url8/imagelocation.jpg",
"image_url3": "http://image_url9/imagelocation.jpg",
"image_url4": "http://image_url10/imagelocation.jpg",
"image_url5": "http://image_url11/imagelocation.jpg",
"image_url6": "http://image_url12/imagelocation.jpg",
}
here is my class get data
this is my activity about receive data
private class SearchThread implements Runnable {
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(imageSearchUrl);
MultipartEntity reqEntity = new MultipartEntity();
StringBody part1 = new StringBody(imageId, Charset.forName("UTF-8"));
reqEntity.addPart("imageId", part1);
//pages =1 :0-2 2:5-6 3:6-8
StringBody pages = new StringBody("1");
reqEntity.addPart("pages", pages);
post.setEntity(reqEntity);
post.setHeader("enctype", "multipart/form-data;");
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {// success
HttpEntity entity = response.getEntity();
String resJson = EntityUtils.toString(entity);
System.out.println("**** = " + resJson);
jsonStr = resJson;
JSONTokener jsonParser = new JSONTokener(resJson);
JSONObject itemList = (JSONObject) jsonParser.nextValue();
int total = itemList.getInt("total");
int currentPage = itemList.getInt("currentPage");
JSONArray jsonObjs = itemList.getJSONArray("rows");
String demoUrl = "";
String s = "";
List<String> imageUrlList = new ArrayList<String>();
for (int i = 0; i < jsonObjs.length(); i++) {
JSONObject jsonObj = jsonObjs.getJSONObject(i);
// String id = jsonObj.getInt("id");
String image_name = jsonObj.getString("image_name");
String image_url = jsonObj.getString("image_url");
String image_url1 = jsonObj.getString("image_url1");
String image_url2 = jsonObj.getString("image_url2");
String image_url3 = jsonObj.getString("image_url3");
String image_url4 = jsonObj.getString("image_url4");
String image_url5 = jsonObj.getString("image_url5");
String image_url6 = jsonObj.getString("image_url6");
String price = jsonObj.getString("price");
imageUrlList.add(image_url);
// s += " image_name = " + image_name + "image_url = " +
// image_url;
if (i == 0) {
urlStr = image_url1 +","+ image_url2 +","+ image_url3 +","+
image_url4 +","+ image_url5 +","+ image_url6;
demoUrl = image_url;
System.out.println("########### " + image_url1 + " ---" + image_url2 + "---" + image_url3 + " ---" + image_url4 + "---" + image_url5 + " ---"
+ image_url6 + "---");
}
}
String s1 = demoUrl.replaceAll("127.0.0.1", "url");
mHandler.obtainMessage(0, s1).sendToTarget();
} else {
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("%%%%%%%%%%%5" + e.toString());
}
}
}
public String uploadImage(String url, String filepath) {
File file = new File(filepath);
if (!file.exists()) {
return null;
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
FileBody fileBody = new FileBody(file, "image/jpeg");
MultipartEntity entity = new MultipartEntity();
entity.addPart("image", fileBody);
post.setEntity(entity);
try {
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
String result = EntityUtils.toString(response.getEntity(), "utf-8");
if (statusCode == 201) {
// upload success
// do something
}
return result;
} catch (Exception e) {
System.out.println(e.toString());
}
return null;
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
try {
URL url = new URL(msg.obj.toString());
et3.setText(msg.obj.toString());
new Thread(new ImageRunnable()).start();
} catch (Exception e) {
System.out.println("^^^^^^^" + e.toString());
}
break;
case 1:
Toast.makeText(getApplication(), "failed", Toast.LENGTH_LONG).show();
break;
}
}
};
private class ImageRunnable implements Runnable {
#Override
public void run() {
// get the image by use url
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(et3.getText().toString());
final Bitmap bm;
try {
HttpResponse hr = hc.execute(hg);
bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
} catch (Exception e) {
mHandler2.obtainMessage(1).sendToTarget();
return;
}
mHandler2.obtainMessage(0, bm).sendToTarget();
}
};
private Handler mHandler2 = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
//ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
// iv2.setImageBitmap((Bitmap) msg.obj);//
imageButton1.setImageBitmap((Bitmap) msg.obj);
Toast.makeText(getApplication(), "success", Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(getApplication(), "failed", Toast.LENGTH_LONG).show();
break;
}
}
};
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (event.getAction()) {
case KeyEvent.ACTION_UP: {
}
case KeyEvent.ACTION_DOWN: {
}
default:
break;
}
return false;
}
my xml code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_alignParentTop="true"
>
<ImageButton
android:id="#+id/picButton"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:padding="0sp"
android:scaleType="centerCrop"
android:background="#drawable/ic_launcher1" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout2">
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get"
/>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.66"
android:text="c2db6c9be8e5407c8a226ba8a0851368"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout5" >
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/white"
android:ems="10"
android:paddingTop="33px"
android:inputType="textMultiLine"
android:hint="comment" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IP:" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=""
/>
</LinearLayout>
<EditText
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:visibility="gone" >
<requestFocus />
</EditText>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:weightSum="10"
android:paddingBottom="59px"
android:paddingTop="10dp">
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="3"
android:text="POST"
android:paddingLeft="100px"
android:paddingRight="100px"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="60px"
android:textColor="#android:color/white"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout4"
android:layout_alignParentLeft="true"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/resultButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageButton
android:id="#+id/resultButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1"/>
<ImageButton
android:id="#+id/resultButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageButton
android:id="#+id/resultButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
<ImageButton
android:id="#+id/resultButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher1" />
</LinearLayout>
but i try this code, only the first image show, another didn't appear
help me!!
receive just one data sheet (one row) is success. i don't know how to receive total row data.... please help me. save my life please
Try this Code Its Work..
HttpEntity entity = response.getEntity();
String resJson = EntityUtils.toString(entity);
System.out.println("**** = " + resJson);
jsonStr = resJson;
JSONTokener jsonParser = new JSONTokener(resJson);
JSONObject itemList = (JSONObject) jsonParser.nextValue();
int total = itemList.getInt("total");
int currentPage = itemList.getInt("currentPage");
JSONArray jsonObjs = itemList.getJSONArray("rows");
String demoUrl = "";
String s = "";
List<String> imageUrlList = new ArrayList<String>();
for (int i = 0; i < jsonObjs.length(); i++) {
JSONObject jsonObj = jsonObjs.getJSONObject(i);
// String id = jsonObj.getInt("id");
String image_name = jsonObj.getString("image_name");
String image_url = jsonObj.getString("image_url");
String image_url1 = jsonObj.getString("image_url1");
String image_url2 = jsonObj.getString("image_url2");
String image_url3 = jsonObj.getString("image_url3");
String image_url4 = jsonObj.getString("image_url4");
String image_url5 = jsonObj.getString("image_url5");
String image_url6 = jsonObj.getString("image_url6");
String price = jsonObj.getString("price");
imageUrlList.add(image_url);
imageUrlList.add(image_url1);
imageUrlList.add(image_url2);
imageUrlList.add(image_url3);
imageUrlList.add(image_url4);
imageUrlList.add(image_url5);
imageUrlList.add(image_url6);
Because you add just one image_url in your list.
If you want to add all url in list you have to do like below,
imageUrlList.add(image_url);
imageUrlList.add(image_url1);
imageUrlList.add(image_url2);
imageUrlList.add(image_url3);
imageUrlList.add(image_url4);
imageUrlList.add(image_url5);
imageUrlList.add(image_url6);
But Instead of this,
Better way is to create JSONArray of your all Images.

Android:image animation using separate layout

I am building an app for wallpaper. I am trying get image from server. I am able to get image from server but when I am trying to animate and change image of imageview and it is work but it work in only in last 13 images not on all images. So how can I set animation for all the images? Here is my code:
MainActivity.java
package com.example.featuredwallpaper;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import android.view.animation.AnimationUtils;
public class MainActivity extends Activity {
public static final String TAG_SUCCESS = "status_code";
public static final String TAG_ARRAY = "info";
JSONArray images = null;
LinearLayout ResultDisplayLayout;
JSONParser jParser = new JSONParser();
String projectName = "Heart";
public static String url = "http://frontlinkinfotech.com/lwp/c_wall/get_images";
private ProgressDialog pDialog;
SquareImageViewHalf image1,image2, image4, image5, image7, image8,
image12, image13;
SquareImageView image3, image6, image9, image10, image11;
ArrayList<SquareImageViewHalf> image1animation = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
ResultDisplayLayout = (LinearLayout) findViewById(R.id.ResultDisplayLayout);
new LoadImages().execute();
handleChangeImage(R.id.imageView1);
}
#SuppressWarnings("static-access")
private Animation selectAnimation(int index) {
switch (index) {
case 0:
return new AnimationUtils().loadAnimation(this, R.anim.fade);
case 1:
return new AnimationUtils().loadAnimation(this, R.anim.slide_left);
case 2:
return new AnimationUtils().loadAnimation(this, R.anim.wave_scale);
case 3:
return new AnimationUtils().loadAnimation(this, R.anim.hold);
case 4:
return new AnimationUtils().loadAnimation(this, R.anim.zoom_enter);
}
return null;
}
void handleChangeImage(final int id) {
Handler hand = new Handler();
hand.postDelayed(new Runnable() {
#Override
public void run() {
Random rand = new Random();
int index = rand.nextInt(CC.IMAGES_POPULAR.length);
// handleChangeImage();
switch (id) {
case R.id.imageView1:
UrlImageViewHelper.setUrlDrawable(image1,
CC.IMAGES_POPULAR[index], R.drawable.ima);
image1.startAnimation(selectAnimation((int) (Math
.random() * 5)));
handleChangeImage(R.id.imageView2);
break;
case R.id.imageView2:
UrlImageViewHelper.setUrlDrawable(image2,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image2.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView3);
break;
case R.id.imageView3:
UrlImageViewHelper.setUrlDrawable(image3,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image3.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView4);
break;
case R.id.imageView4:
UrlImageViewHelper.setUrlDrawable(image4,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image4.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView5);
break;
case R.id.imageView5:
UrlImageViewHelper.setUrlDrawable(image5,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image5.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView6);
break;
case R.id.imageView6:
UrlImageViewHelper.setUrlDrawable(image6,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image6.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView7);
break;
case R.id.imageView7:
UrlImageViewHelper.setUrlDrawable(image7,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image7.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView8);
break;
case R.id.imageView8:
UrlImageViewHelper.setUrlDrawable(image8,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image8.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView9);
break;
case R.id.imageView9:
UrlImageViewHelper.setUrlDrawable(image9,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image9.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView10);
break;
case R.id.imageView10:
UrlImageViewHelper.setUrlDrawable(image10,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image10.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView11);
break;
case R.id.imageView11:
UrlImageViewHelper.setUrlDrawable(image11,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image11.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView12);
break;
case R.id.imageView12:
UrlImageViewHelper.setUrlDrawable(image12,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image12.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView13);
break;
case R.id.imageView13:
UrlImageViewHelper.setUrlDrawable(image13,
CC.IMAGES_POPULAR[rand
.nextInt(CC.IMAGES_POPULAR.length)],
R.drawable.ima);
image13.startAnimation(selectAnimation((int) (Math.random() * 5)));
handleChangeImage(R.id.imageView1);
break;
}
}
}, 4000);
}
class LoadImages extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
Log.d("back", "in background");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cat_name", projectName));
String uuu = "http://frontlinkinfotech.com/lwp/c_wall/get_all_images";
JSONObject json = jParser.makeHttpRequest(uuu, "POST", params);
Log.d("back", "get image");
try {
int success = json.getInt(TAG_SUCCESS);
ArrayList<String> list1 = new ArrayList<String>();
if (success == 200) {
Log.d("back", "success");
images = json.getJSONArray(TAG_ARRAY);
for (int i = 0; i < images.length(); i++) {
String jkr = images.getString(i);
String front = jkr.replace("jkrdevelopers",
"frontlinkinfotech");
list1.add(front);
}
CC.IMAGES_POPULAR = list1.toArray(new String[list1.size()]);
// Collections.shuffle(list1);
Log.d("Array", CC.IMAGES_POPULAR.toString());
Log.d("Array", list1.toString());
// CC.IMAGES_NEW = list1.toArray(new String[list1.size()]);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
Log.d("back", "in post");
ResultDisplayLayout.removeAllViews();
Log.d("Size", CC.IMAGES_POPULAR.length + "");
Log.d("Size", CC.IMAGES_POPULAR.length / 13 + "");
for (int i = 0; i < CC.IMAGES_POPULAR.length / 13; i++) {
// Display_Toast_Message(collect_rs_rd_value.get(i));
LayoutInflater inflater = (LayoutInflater) getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.image_listview, null);
for (int j = 0; j < 13; j++) {
image1 = (SquareImageViewHalf) view
.findViewById(R.id.imageView1);
UrlImageViewHelper.setUrlDrawable(image1,
CC.IMAGES_POPULAR[i], R.drawable.ima);
image2 = (SquareImageViewHalf) view
.findViewById(R.id.imageView2);
UrlImageViewHelper.setUrlDrawable(image2,
CC.IMAGES_POPULAR[i + 1], R.drawable.ima);
image3 = (SquareImageView) view
.findViewById(R.id.imageView3);
UrlImageViewHelper.setUrlDrawable(image3,
CC.IMAGES_POPULAR[i + 2], R.drawable.ima);
image4 = (SquareImageViewHalf) view
.findViewById(R.id.imageView4);
UrlImageViewHelper.setUrlDrawable(image4,
CC.IMAGES_POPULAR[i + 3], R.drawable.ima);
image5 = (SquareImageViewHalf) view
.findViewById(R.id.imageView5);
UrlImageViewHelper.setUrlDrawable(image5,
CC.IMAGES_POPULAR[i + 4], R.drawable.ima);
image6 = (SquareImageView) view
.findViewById(R.id.imageView6);
UrlImageViewHelper.setUrlDrawable(image6,
CC.IMAGES_POPULAR[i + 5], R.drawable.ima);
image7 = (SquareImageViewHalf) view
.findViewById(R.id.imageView7);
UrlImageViewHelper.setUrlDrawable(image7,
CC.IMAGES_POPULAR[i + 6], R.drawable.ima);
image8 = (SquareImageViewHalf) view
.findViewById(R.id.imageView8);
UrlImageViewHelper.setUrlDrawable(image8,
CC.IMAGES_POPULAR[i + 7], R.drawable.ima);
image9 = (SquareImageView) view
.findViewById(R.id.imageView9);
UrlImageViewHelper.setUrlDrawable(image9,
CC.IMAGES_POPULAR[i + 8], R.drawable.ima);
image10 = (SquareImageView) view
.findViewById(R.id.imageView10);
UrlImageViewHelper.setUrlDrawable(image10,
CC.IMAGES_POPULAR[i + 9], R.drawable.ima);
image11 = (SquareImageView) view
.findViewById(R.id.imageView11);
UrlImageViewHelper.setUrlDrawable(image11,
CC.IMAGES_POPULAR[i + 10], R.drawable.ima);
image12 = (SquareImageViewHalf) view
.findViewById(R.id.imageView12);
UrlImageViewHelper.setUrlDrawable(image12,
CC.IMAGES_POPULAR[i + 11], R.drawable.ima);
image13 = (SquareImageViewHalf) view
.findViewById(R.id.imageView13);
UrlImageViewHelper.setUrlDrawable(image13,
CC.IMAGES_POPULAR[i + 12], R.drawable.ima);
}
ResultDisplayLayout.addView(view);
}
Toast.makeText(getApplicationContext(), "post",
Toast.LENGTH_SHORT).show();
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.featuredwallpaper.MainActivity" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/ResultDisplayLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</RelativeLayout>
image_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="NestedWeights,DisableBaselineAlignment" >
<!-- start first layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:orientation="vertical" >
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:background="#drawable/border"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:padding="5dp"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:orientation="vertical" >
<com.example.featuredwallpaper.SquareImageView
android:id="#+id/imageView3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/border"
android:padding="5dp"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:orientation="vertical" >
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView4"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.50"
android:background="#drawable/border"
android:padding="5dp"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView5"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.50"
android:padding="5dp"
android:background="#drawable/border"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#android:color/black"
></LinearLayout>
<!-- end second layout -->
<!-- start third layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:orientation="vertical" >
<com.example.featuredwallpaper.SquareImageView
android:id="#+id/imageView6"
android:layout_width="fill_parent"
android:padding="5dp"
android:background="#drawable/border"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:orientation="vertical" >
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView7"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:background="#drawable/border"
android:layout_weight="0.50"
android:padding="5dp"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView8"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:background="#drawable/border"
android:layout_weight="0.50"
android:padding="5dp"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.50"
android:orientation="vertical" >
<com.example.featuredwallpaper.SquareImageView
android:id="#+id/imageView9"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/border"
android:scaleType="fitXY"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#android:color/black"
></LinearLayout>
<!-- end third layout -->
<!-- start fourth Layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="0.50" >
<com.example.featuredwallpaper.SquareImageView
android:id="#+id/imageView10"
android:layout_width="fill_parent"
android:padding="5dp"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:background="#drawable/border"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="0.50" >
<com.example.featuredwallpaper.SquareImageView
android:id="#+id/imageView11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:scaleType="fitXY"
android:background="#drawable/border"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.50"
android:orientation="vertical" >
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView12"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.50"
android:padding="5dp"
android:scaleType="fitXY"
android:background="#drawable/border"
android:src="#drawable/ic_launcher" />
<com.example.featuredwallpaper.SquareImageViewHalf
android:id="#+id/imageView13"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="0.50"
android:scaleType="fitXY"
android:background="#drawable/border"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#android:color/black"
></LinearLayout>
<!-- end fourth Layout -->
</LinearLayout>
JSONParser.java
package com.example.featuredwallpaper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
CC.java
package com.example.featuredwallpaper;
public class CC {
public static String[] IMAGES_POPULAR;
public static String[] IMAGES_NEW;
public static int pos=0;
public static String imageName;
public static int totalClick;
public static class Extra {
public static final String IMAGES = "com.nostra13.example.universalimageloader.IMAGES";
public static final String IMAGE_POSITION = "com.nostra13.example.universalimageloader.IMAGE_POSITION";
}
}
SquareImageView.java
package com.example.featuredwallpaper;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class SquareImageView extends ImageView
{
public SquareImageView(Context context)
{
super(context);
}
public SquareImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
SquareImageViewHalf.java
package com.example.featuredwallpaper;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class SquareImageViewHalf extends ImageView
{
public SquareImageViewHalf(Context context)
{
super(context);
}
public SquareImageViewHalf(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public SquareImageViewHalf(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()/2);
}
}
Loading images to view in Android is a big problem. Because of the limited cache size. I think this tutorial may help you.

android basic image gallery code error?

i am developing the main activity at the moment that displays multiple images vertically that can be scrolled down. later i would use each image as a thumbnail to a video.
but imageview displays one image only
can someone guide me through it.
Resources res = getResources(); //if you are in an activity
AssetManager am = res.getAssets();
//String temp="";
String fileList[];
try {
fileList = am.list("thumbs");
if (fileList != null)
{
for ( int i = 0;i<fileList.length;i++)
{
Log.d("",fileList[i]);
//temp = temp + fileList[i] + ", ";
if (i == 0)
{
mImage = (ImageView)findViewById(R.id.imageView1);
Drawable d = fetchThumb(fileList[0]);
mImage.setImageDrawable(d);
}
else if(i == 1)
{
mImage = (ImageView)findViewById(R.id.imageView2);
Drawable d = fetchThumb(fileList[1]);
mImage.setImageDrawable(d);
}
else if(i == 2)
{
mImage = (ImageView)findViewById(R.id.imageView3);
Drawable d = fetchThumb(fileList[2]);
mImage.setImageDrawable(d);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Drawable fetchThumb(String filename)
{
try
{
InputStream ims = getAssets().open(filename);
Drawable d = Drawable.createFromStream(ims, null);
return d;
}
catch(IOException ex)
{return null;}
}
xml file to display images:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:isScrollContainer="true"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>

Searching of Customlist view not working

I am trying to built search functionality on custom listView but it is not working..list is not changing according to EditText words changes..
listplaceholder.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/edtSearch"
android:hint="Search"/>
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
</LinearLayout>
my_custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/icon" />
<FrameLayout
android:id="#+id/frame"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Button"
/>
<LinearLayout
android:id="#+id/ll1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/a"
android:orientation="vertical" >
<TextView
android:id="#+id/from_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<TextView
android:id="#+id/from_user_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
Main.java
public class Main extends ListActivity {
/** Called when the activity is first created. */
ImageView img, img1;
private AdapterClass adapter;
private String reviewImageLink;
private static final String TAG = "PRANJAL";
private boolean isImage = false;
String fileName[] = new String[10];
private String imgurl;
ArrayList<HashMap<String, String>> searchResult;
private EditText edtSearch;
private ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
edtSearch = (EditText) findViewById(R.id.edtSearch);
list = (ListView) findViewById(android.R.id.list);
// list = (LinearLayout) findViewById(R.id.list);
final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://23.21.228.8/PlutoApp_Beta/consumer_dash/"
+ "checkIn_confirmation_related_record.php?lat=18.535787&lng=73.891889");
try {
JSONArray earthquakes = json.getJSONArray("Display");
for (int i = 0; i < earthquakes.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("Name", e.getString("name"));
map.put("Vicinity", e.getString("vicinity"));
map.put("logo", e.getString("logo"));
imgurl = e.getString("logo");
// Toast.makeText(getApplicationContext(), imgurl,
// Toast.LENGTH_SHORT).show();
imgurl = e.getString("logo");
// Toast.makeText(getApplicationContext(), imgurl,
// Toast.LENGTH_SHORT).show();
DownloadFromUrl(imgurl, i + ".jpg");
reviewImageLink = imgurl;// getString(R.string.ImageURI);
URL reviewImageURL;
fileName[i] = reviewImageLink.substring(reviewImageLink
.lastIndexOf("/") + 1);
// map.put("profile_image_url", fileName[i]);
map.put("logo", i + ".jpg");
list.setTextFilterEnabled(true);
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
/*final ListView lv = getListView();
lv.setTextFilterEnabled(true);*/
searchResult = new ArrayList<HashMap<String, String>>(mylist);
// adapter = new AdapterClass(Main.this, R.layout.main, mylist);
adapter = new AdapterClass(Main.this, R.layout.my_custom_layout, mylist);
// list.setAdapter(adapter);
setListAdapter(adapter);
edtSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// get the text in the EditText
String searchString = edtSearch.getText().toString();
int textLength = searchString.length();
searchResult.clear();
for (int i = 0; i < mylist.size(); i++) {
String playerName = mylist.get(i).get("Name").toString();
if (textLength <= playerName.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(
0, textLength)))
Toast.makeText(getApplicationContext(),
"Inside if of : " + playerName, 1000)
.show();
searchResult.add(mylist.get(i));
}
}
adapter.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
/*
* final ListView lv = getListView(); //lv.setTextFilterEnabled(true);
* lv.setOnItemClickListener(new OnItemClickListener() { public void
* onItemClick(AdapterView<?> parent, View view, int position, long id)
* {
*
* #SuppressWarnings("unchecked") HashMap<String, String> o =
* (HashMap<String, String>) lv .getItemAtPosition(position);
*
* } });
*/
}
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File dir = new File("/sdcard/pluto");
if (dir.exists() == false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); // you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
}
Please Help me.
You are not setting the adapter again in onTextChange. Add this inside onTextChange at the end:
setListAdapter(searchResult);
and remove
adapter.notifyDataSetChanged();

Inserting image from assets folder into a ListView

ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
JSONObject json = jParser.getJSONFromUrl("http://domain.com/directory/database/retrieveComments.php?placeId=" + stringPlaceId);
try
{
commentsRatingsArray = json.getJSONArray("commentsRatings");
for(int i = 0; i < commentsRatingsArray.length(); i++)
{
JSONObject jsonObject = commentsRatingsArray.getJSONObject(i);
String dbUserFullName = jsonObject.getString(TAG_FULLNAME);
String dbUserEmail = jsonObject.getString(TAG_EMAIL);
String dbComment = jsonObject.getString(TAG_COMMENT);
String dbRating = jsonObject.getString(TAG_RATING);
String dbDate = jsonObject.getString(TAG_DATE);
String dbTime = jsonObject.getString(TAG_TIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_FULLNAME, dbUserFullName);
map.put(TAG_EMAIL, dbUserEmail);
map.put(TAG_COMMENT, dbComment);
map.put(TAG_RATING, dbRating);
map.put(TAG_DATE, dbDate);
map.put(TAG_TIME, dbTime);
list.add(map);
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getBaseContext(), "Connection to the server is lost. Please check your internet connection.", Toast.LENGTH_SHORT).show();
}
ListAdapter adapter = new SimpleAdapter
(DisplayCommentsRatings.this, list, R.layout.commentrating,
new String[] { TAG_FULLNAME, TAG_EMAIL, TAG_COMMENT, TAG_DATE, TAG_TIME },
new int[] {R.id.tvUserFullName, R.id.tvUserEmail, R.id.tvUserComment, R.id.tvDate, R.id.tvTime });
setListAdapter(adapter);
Here's my code, I'm getting these JSON Array values from my database. I just want to know how to change an image's src inside a list view. Because I will only use 5 images, I decided to include these images in my assets folder instead of uploading them to the web.
Can someone give me an idea to make this possible?
Here's my XML code:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvUserFullName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="12dip"
android:textStyle="bold"/>
//This is the imageView where I will display the image from the assets folder
<ImageView
android:id="#+id/ivUserRating"
android:layout_width="100dip"
android:layout_height="fill_parent"
android:src="#drawable/zerostar"/>
</LinearLayout>
<TextView
android:id="#+id/tvUserEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EmailAddress#domain.com"
android:textSize="9dip"/>
<TextView
android:id="#+id/tvUserComment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text='"This is a comment. This is a comment. This is a comment. This is a comment. This is a comment."'
android:textSize="10dip"
android:layout_margin="3dip"
android:textColor="#000000"
android:maxLength="300"/>
<TextView
android:id="#+id/tvDate"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="August 1, 2010"
android:textColor="#000000"
android:textSize="8dip"
android:layout_gravity="right"/>
<TextView
android:id="#+id/tvTime"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="08:20 PM"
android:textColor="#000000"
android:textSize="8dip"
android:layout_gravity="right"/>
Use SimpleAdapter as normal, but be sure to override you "adapter"'s the setViewBinder method like:
adapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// Check wether it's ImageView and the data
if(view instanceof ImageView && data instanceof Bitmap){
ImageView iv = (ImageView) view;
iv.setImageBitmap((Bitmap) data);
return true;
}else
return false;
}
});
then use a getBitmap() to get the assert image
public Bitmap getBitmap( String path, int i ){
Bitmap mBitmap = null;
try {
AssetManager assetManager = getAssets();
String[] files = null;
files = assetManager.list( "smartmodel/" + path );
Log.i( "Assert List", files[1].toString() );
// Pass ur file path, here is one in assert/smartmodel/ filer
mBitmap = BitmapFactory.decodeStream( this.getAssets().open( "smartmodel/" + path + "/"+ files[i]) );
} catch (Exception e) {
e.printStackTrace();
}
return mBitmap;
}
Last, in your Simple adapter List parameter, put
map.put( "ItemImage", getBitmap( gridItemName, i ));
Your passed getBitmap(...) will be show.
check position and use like,
Bitmap bmp=null;
if(position==0){
bitmap=getBitmap("img0.png");
}else if (position==1){
bitmap=getBitmap("img1.png");
}
.
.
.
Method::
private Bitmap getBitmap(String name) throws IOException
{
AssetManager asset = getAssets();
InputStream is = asset.open(name);
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}

Categories

Resources