Inserting image from assets folder into a ListView - android

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

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 while using cardview image is loading very lazy

I am loading pictures (below ~3MB in size) into Cardview from a database and it was infalte in Listviewstview.
The loading and browsing of these pictures is way too slow.
Is there any method to downscale these pictures to speed up & sometimes dispalyind [Duplicate] images on other card view?
cardview xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="140dp"
android:alpha="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
card_view:cardBackgroundColor="#FFFFFF"
card_view:cardCornerRadius="10dp">
<RelativeLayout
android:id="#+id/r1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img_product"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginLeft="#dimen/activity_vertical_margin"
android:layout_marginTop="20dp" />
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:inputType="textMultiLine"
android:text="Parvana Fancy Necklace Set"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:text="RS.234"
android:textSize="20dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_remove"
android:layout_width="32dp"
android:layout_height="wrap_content"
android:background="#drawable/wishlistddelete_selector"
android:drawableLeft="#drawable/delete_icon"
android:layout_alignTop="#+id/txt_total"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
listview xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/home_bground">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/topbar1"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#drawable/top">
<ImageView
android:id="#+id/btn_hme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:src="#drawable/home_icon" />
<TextView
android:id="#+id/txt_pro_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center_horizontal"
android:text="Shopping Cart"
android:textColor="#ffffff"
android:textSize="18dp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/topbar1"
android:animationCache="false"
android:dividerHeight="0dp"
android:listSelector="#00000000"
android:scrollingCache="false"
android:smoothScrollbar="true" />
</RelativeLayout>
</RelativeLayout>
by using sqllite access the data from database
public class Wishlist extends Activity {
Button checkout;
ListView ListCart;
String name, cusid, ffname, llname, phone, fax, password, email;
String[] qu, s;
int[] g;
int k = 0;
String cost;
ProgressDialog pDialog = null;
List<CartProducts> product_list;
Context ctx;
Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
SQLiteDatabase FavData;
private Context context;
Integer i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifywishlist);
Intent page1 = getIntent();
cusid = page1.getStringExtra("cus_id");
ffname = page1.getStringExtra("fname");
llname = page1.getStringExtra("lname");
phone = page1.getStringExtra("ph");
fax = page1.getStringExtra("fax");
password = page1.getStringExtra("password");
email = page1.getStringExtra("email");
ListCart = (ListView) findViewById(R.id.list_item);
ListCart.setScrollingCacheEnabled(false);
Intent page2 = getIntent();
i = page2.getIntExtra("kvalue",1);
pDialog = new ProgressDialog(this);
ctx = this;
FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
final String[] productID = new String[crsr.getCount()];
final String[] ProductName = new String[crsr.getCount()];
final String[] ProductPrice = new String[crsr.getCount()];
final String[] ProductQuantity = new String[crsr.getCount()];
final String[] ProductModel = new String[crsr.getCount()];
final String[] ProductImage = new String[crsr.getCount()];
final String[] ProductManufacturer = new String[crsr.getCount()];
int j = 0;
while (crsr.moveToNext()) {
String id = crsr.getString(crsr.getColumnIndex("product_id"));
productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
name = crsr.getString(crsr.getColumnIndex("name"));
ProductName[j] = name;
String price = crsr.getString(crsr.getColumnIndex("price"));
ProductPrice[j] = price;
String s = ProductPrice[j].toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");
total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
ProductQuantity[j] = qnty;
String s2 = ProductQuantity[j].toString();
total1 = Integer.parseInt(s2);
sum = total * total1;
String model = crsr.getString(crsr.getColumnIndex("model"));
ProductModel[j] = model;
String image = crsr.getString(crsr.getColumnIndex("image"));
ProductImage[j] = image;
String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
ProductManufacturer[j] = manufacturer;
myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
gtot = gtot + sum;
j++;
}
ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
String s1 = ProductPrice.toString();
}
}
adapter class
public class Wishlist_Listadapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll, name,totalps;
SQLiteDatabase FavData;
Integer total = 0, quanty = 1, grandtot = 0, i = 0;
String it;
Button addbtn, minbtn;
EditText editqu;
int total1 = 0, quantity=0, fulltotal = 0, sum;
SQLiteOpenHelper dbhelper;
Wishlist_Listadapter cart = Wishlist_Listadapter.this;
private int resource;
private LayoutInflater inflater;
private Context context;
int count=1 ;
public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* create a new view of my layout and inflate it in the row */
convertView = (RelativeLayout) inflater.inflate(resource, null);
final ViewHolder viewholder;
viewholder = new ViewHolder();
final CartProducts banqt = getItem(position);
totalps=(banqt.getPrice());
String s = totalps.toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
total = Integer.parseInt(part1);
quanty = Integer.parseInt(banqt.getQuantity());
grandtot = total *quanty;
viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
viewholder.total.setText(String.valueOf(grandtot));
Button delet = (Button) convertView.findViewById(R.id.btn_remove);
delet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*delete function*/
it = banqt.getProduct_id();
FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
Intent intent = ((Wishlist) context).getIntent();
((Wishlist) context).finish();
context.startActivity(intent);
}
});
viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
viewholder.txtName.setText(banqt.getName());
img = (ImageView) convertView.findViewById(R.id.img_product);
urll = banqt.getImage().toString();
urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
new LoadImage().execute(urll);
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView total;
EditText editqu;
TextView txtprice;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
img.setImageBitmap(image);
// pDialog.dismiss();
} else {
// pDialog.dismiss();
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Try scale your bitmap to lower its actual resolution, I've used the following codes to reduce bitmap's size.
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
For you case, add the following codes into your adapter class AsyncTask's doInBackground method
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
} catch (Exception e) {
e.printStackTrace();
}
return scaled;
Return scaled bitmap instead of original bitmap.

Display full screen image in ImageView

I want to display full screen image on another activity after clicking an imageview. I have 6 ImageViews in my layout and each ImageView is getting image from Parse backend. How can I display image on fetching the imagepath ?
public ImageLoader imgl;
ImageView ad1,ad2,ad3,ad4,ad5,ad6;
List<ParseObject> ob;
private ImageView[] imgs = new ImageView[5];
int k=0;
ad1=(ImageView) findViewById(R.id.ad1);
ad2=(ImageView) findViewById(R.id.ad2);
ad3=(ImageView) findViewById(R.id.ad3);
ad4=(ImageView) findViewById(R.id.ad4);
ad5=(ImageView) findViewById(R.id.ad5);
ad6=(ImageView) findViewById(R.id.ad6);
imgs[0] = ad2;
imgs[1] = ad3;
imgs[2] = ad4;
imgs[3] = ad5;
imgs[4] = ad6;
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Adverts");
query.orderByDescending("updatedAt");
query.whereEqualTo("Status", true);
try {
ob = query.find();
System.out.println("the urls areeee "+ob);
for (ParseObject country : ob) {
ParseFile image = (ParseFile) country.get("imageFile");
imgl.DisplayImage(image.getUrl(), imgs[k]);
k=k+1;
System.out.println("the urls are"+image.getUrl());
pd.dismiss();
}
} catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
pd.dismiss();
e.printStackTrace();
}
ad1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent ent= new Intent(HomeActivity.this,AdvertsActivity.class);
startActivity(ent);
}
});
}
Set click listener on your ImageView and pass your image url in argument and call method
private void viewImage(String url)
{
final Dialog nagDialog = new Dialog(ProjectDetailActivity.this,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
nagDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
nagDialog.setCancelable(false);
nagDialog.setContentView(R.layout.dialog_full_image);
ivPreview = (ImageView)nagDialog.findViewById(R.id.imageView1);
BitmapDrawable bmd = (BitmapDrawable)getDrawableFromUrl(url)
Bitmap bitmap = bmd.getBitmap();
ivPreview.setImageBitmap(bitmap);
nagDialog.show();
}
public Drawable getDrawableFromUrl(String imgUrl)
{
if(imgUrl == null || imgUrl.equals(""))
return null;
try
{
URL url = new URL(imgUrl);
InputStream in = url.openStream();
Drawable d = Drawable.createFromStream(in, imgUrl);
return d;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
use xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white"
android:layout_gravity="center" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="#string/hello_world"
android:src="#android:color/white"
android:layout_margin="5dp"
android:scaleType="centerInside"/>
</RelativeLayout>

How to dynamically add suggestions to autocompletetextview with preserving character status along with images

Currently I am using code to give text suggestion. I would like to add another text and image. How do I do that? Currently, I am using the code below.I shows text but image is not displayed .How do I set the image ?
public class AutoCompleteTextViewActivity extends Activity{
ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
// String a=constraint;
JSONObject json=JSONfunctions.getJSONfromURL("http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist="+ constraint +"&api_key=63692beaaf8ba794a541bca291234cd3&format=json");
JSONObject js1=json.getJSONObject("artist");
JSONObject js=js1.getJSONObject("similar");
JSONArray resultArray = js.getJSONArray("artist");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
String data = resultArray.getJSONObject(i).getString("name");
String dataimage = resultArray.getJSONObject(i).getJSONArray("image").getJSONObject(i).getString("#text");
cursor.newRow().add(i)
.add(data)
.add(data)
.add(data);
String link = dataimage;
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
public void run() {
String TAG="log";
// TODO do real network request
// simulate network delay
// Log.d(TAG, "getting " + mUrl);
// try {
// Thread.sleep(2000 + (long) (4000 * Math.random()));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Bitmap b = imageLoader.loadImageSync(mUrl.toString());
// Bitmap b = BitmapFactory.decodeResource(getResources(), mUrl.toString());
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
}
}
///////////////
MyMatrixCursor
//////////
public class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}
////////
JSONfunctions
///////
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = 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(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.w("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.w("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
////////
main.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="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Artist"
android:textAppearance="?android:attr/textAppearanceLarge" />
<AutoCompleteTextView
android:id="#+id/actv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"> <requestFocus />
</AutoCompleteTextView>
<TextView
android:id="#+id/selection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
/////
list_row.xml
///
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left sied Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/list_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="42dp"
android:maxHeight="42dp"
android:src="#drawable/ic_launcher"
android:scaleType="fitCenter"
android:layout_marginLeft="3dp"/>
</LinearLayout>
<!-- Title Of Song-->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<!-- Artist Name -->
<!-- Rightend Duration -->
<!-- Rightend Arrow -->
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_centerVertical="true"
android:text="test"
android:textColor="#040404"
android:textSize="5dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="test"
android:textColor="#040404"
android:textSize="15dip"
android:textStyle="bold"
android:typeface="sans" />
</RelativeLayout>
///
Manifest
///
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".AutoCompleteTextViewActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ok try this:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
String[] from = {"name"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to) {
// required for Spanned data
#Override
public void bindView(View view, Context context, Cursor cursor) {
MyCursor c = (MyCursor) cursor;
TextView tv = (TextView) view;
tv.setText(c.getSpanned());
}
// required for Spanned data
#Override
public CharSequence convertToString(Cursor cursor) {
MyCursor c = (MyCursor) cursor;
return c.getSpanned();
}
};
FilterQueryProvider provider = new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
MyCursor c = new MyCursor();
// fake web service responses
List<String> names = callFakeWebService(constraint);
int i = 0;
for (String name: names) {
SpannableStringBuilder ssb = new SpannableStringBuilder(name);
int start = name.indexOf(" ");
ForegroundColorSpan what = new ForegroundColorSpan(0xffff0000);
ssb.setSpan(what, start + 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
c.newRow().add(i++).add(name);
c.addSpanned(ssb);
}
return c;
}
// fake web service request
private List<String> callFakeWebService(CharSequence constraint) {
Log.d(TAG, "callFakeWebService for: " + constraint);
String[] namesArr = {
"Mark Smith",
"Monica Thompson",
"John White",
"Jane Brown"
};
String stringConstraint = constraint.toString().toLowerCase();
List<String> names = new ArrayList<String>();
for (int i = 0; i < namesArr.length; i++) {
String name = namesArr[i];
if (name.toLowerCase().startsWith(stringConstraint)) {
names.add(name);
}
}
return names;
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
ll.addView(actv);
TextView tv = new TextView(this);
tv.setTextSize(32);
tv.setTextColor(0xffff0000);
tv.setText("type one of:\n mark,\n monica,\n john\n jane");
ll.addView(tv);
setContentView(ll);
where custom Cursor could look like this (it is minimalistic version supporting only one Spanned in a row):
static class MyCursor extends MatrixCursor {
private static final String[] NAMES = {BaseColumns._ID, "name"};
private ArrayList<Spanned> mSpannedList;
public MyCursor() {
super(NAMES);
mSpannedList = new ArrayList<Spanned>();
}
public void addSpanned(Spanned s) {
mSpannedList.add(s);
}
public Spanned getSpanned() {
return mSpannedList.get(mPos);
}
}
EDIT with no Spanned text:
AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
final String[] from = {BaseColumns._ID, "name", "artist", "title"};
int[] to = {R.id.list_image, R.id.textView1, R.id.textView2, R.id.textView3};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_row, null, from, to);
adapter.setStringConversionColumn(1);
ViewBinder viewBinder = new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 0) {
ImageView iv = (ImageView) view;
Bitmap bitmap = cursor.getExtras().getParcelable("image");
if (bitmap != null) {
iv.setImageBitmap(bitmap);
}
return true;
}
return false;
}
};
adapter.setViewBinder(viewBinder);
FilterQueryProvider provider = new FilterQueryProvider() {
ExecutorService mPool = Executors.newCachedThreadPool();
Uri URI = Uri.parse("adapter://autocomplete");
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
try {
return callWebService(constraint, from);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
// here you make the web request
private Cursor callWebService(CharSequence constraint, String[] columnNames) throws JSONException {
Log.d("TAG", "callWebService for: " + constraint);
MatrixCursor cursor = new MyMatrixCursor(columnNames);
// TODO do real network request
// call web service here and keep the result in "jsonStr"
String jsonStr = "{\"ResultArray\":[{\"data\":{ \"sno\":\"sno1\", \"date\":\"2011-08-21 14:27:09\", \"user\":\"1\", \"link\":\"http://scm-l3.technorati.com/11/11/17/56749/google-docs-revision.jpg?t=20111117074048\", \"name\":\"Aa\" }},{\"data\":{ \"sno\":\"sno2\", \"date\":\"2011-08-21 14:28:09\", \"user\":\"2\", \"link\":\"http://kcclaveria.com/wp-content/uploads/2013/02/google-panda-penguin.jpg\", \"name\":\"Bb\" }}]}";
JSONObject json = new JSONObject(jsonStr);
JSONArray resultArray = json.getJSONArray("ResultArray");
int length = resultArray.length();
for (int i = 0; i < length; i++) {
JSONObject data = resultArray.getJSONObject(i).getJSONObject("data");
cursor.newRow().add(i)
.add(data.getString("name"))
.add(data.getString("user"))
.add(data.getString("sno"));
String link = data.getString("link");
// get cached Bundle based on "link" (use HashMap<String, Bundle>)
// or if new link initiate async request for getting the bitmap
// TODO implement HashMap caching
// new async request
Bundle extras = new Bundle();
try {
mPool.submit(new ImageRequest(link, extras));
} catch (MalformedURLException e) {
e.printStackTrace();
}
cursor.respond(extras);
}
cursor.setNotificationUri(getContentResolver(), URI);
return cursor;
}
class ImageRequest implements Runnable {
private URL mUrl;
private Bundle mExtra;
public ImageRequest(String link, Bundle extra) throws MalformedURLException {
mUrl = new URL(link);
mExtra = extra;
}
#Override
public void run() {
// TODO do real network request
// simulate network delay
Log.d(TAG, "getting " + mUrl);
try {
Thread.sleep(2000 + (long) (4000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
mExtra.putParcelable("image", b);
getContentResolver().notifyChange(URI, null);
Log.d(TAG, "run got a bitmap " + b.getWidth() + "x" + b.getHeight());
}
}
};
adapter.setFilterQueryProvider(provider);
actv.setAdapter(adapter);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setContentView(actv, params);
and the custom MatrixCursor:
class MyMatrixCursor extends MatrixCursor {
List<Bundle> mBundles = new ArrayList<Bundle>();
public MyMatrixCursor(String[] columnNames) {
super(columnNames);
}
#Override
public Bundle respond(Bundle extras) {
mBundles.add(extras);
return extras;
}
#Override
public Bundle getExtras() {
return mBundles.get(mPos);
}
}

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

Categories

Resources