JSon array response on android imagebuttons with onclick - android

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.

Related

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.

How to remove Space between row of gridview with images fetched from flickr?

I have integrated flickr in my app but the images in gridview shows lot of space in between rows.I am unable to find out why so much space is appearing between rows..
PhotosFragment.java
public class PhotosFragment extends Fragment {
private FragmentActivity myContext;
String FlickrPhotoPath, FlickrPhotoPath2;
Bitmap bmFlickr, bmFlickr2;
String FlickrQuery_url = "https://api.flickr.com/services/rest/?method=flickr.photos.search";
String FlickrQuery_per_page = "&per_page=2";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuer
y_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
ArrayList<String> imageUrls = new ArrayList<String>();
String FlickrApiKey = "xyz";
#Override
public void onAttach(Activity activity) {
if (activity instanceof FragmentActivity) {
myContext = (FragmentActivity) activity;
}
super.onAttach(activity);
}
DisplayImageOptions options;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.photos, container, false);
ImageView img2 = (ImageView) rootView.findViewById(R.id.imageView3);
ImageView img3 = (ImageView) rootView.findViewById(R.id.imageView1);
rootView.setVerticalScrollBarEnabled(false);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.icon)
.showImageForEmptyUri(R.drawable.icon)
.showImageOnFail(R.drawable.icon)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
String searchResult = QueryFlickr("Java");
String jsonResult = ParseJSON(searchResult);
String searchResult2 = QueryFlickr("Android");
String jsonResult2 = ParseJSON2(searchResult2);
if (bmFlickr != null) {
img2.setImageBitmap(bmFlickr);
}
if (bmFlickr2 != null) {
img3.setImageBitmap(bmFlickr2);
}
GridView grid = (GridView) rootView.findViewById(R.id.gridView);
((GridView) grid).setAdapter(new ImageAdapter());
grid.setFocusable(false);
GridView grid2 = (GridView) rootView.findViewById(R.id.gridView2);
grid2.setFocusable(false);
((GridView) grid2).setAdapter(new ImageAdapter());
return rootView;
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
ImageAdapter() {
inflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.grid_single, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.grid_image);
// holder.progressBar = (ProgressBar) view.findViewById(R.id.progress);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ImageLoader.getInstance()
.displayImage(imageUrls.get(position).toString(), holder.imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
// holder.progressBar.setProgress(Math.round(100.0f * current / total));
}
});
return view;
}
}
static class ViewHolder {
ImageView imageView;
ProgressBar progressBar;
}
private String QueryFlickr(String q) {
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null) {
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private String ParseJSON(String json) {
String jResult = null;
// String jResult2 = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
//We have only one photo in this exercise
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
jResult = "\nid: " + flickrId + "\n"
+ "owner: " + flickrOwner + "\n"
+ "secret: " + flickrSecret + "\n"
+ "server: " + flickrServer + "\n"
+ "farm: " + flickrFarm + "\n"
+ "title: " + flickrTitle + "\n";
/* jResult2 = "\nid: " + flickrId + "\n"
+ "owner: " + flickrOwner + "\n"
+ "secret: " + flickrSecret + "\n"
+ "server: " + flickrServer + "\n"
+ "farm: " + flickrFarm + "\n"
+ "title: " + flickrTitle + "\n"; */
bmFlickr = LoadPhotoFromFlickr(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jResult;
}
private String ParseJSON2(String json) {
String jResult = null;
// String jResult2 = null;
bmFlickr2 = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
//We have only one photo in this exercise
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
jResult = "\nid: " + flickrId + "\n"
+ "owner: " + flickrOwner + "\n"
+ "secret: " + flickrSecret + "\n"
+ "server: " + flickrServer + "\n"
+ "farm: " + flickrFarm + "\n"
+ "title: " + flickrTitle + "\n";
/* jResult2 = "\nid: " + flickrId + "\n"
+ "owner: " + flickrOwner + "\n"
+ "secret: " + flickrSecret + "\n"
+ "server: " + flickrServer + "\n"
+ "farm: " + flickrFarm + "\n"
+ "title: " + flickrTitle + "\n"; */
bmFlickr2 = LoadPhotoFromFlickr2(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jResult;
}
private Bitmap LoadPhotoFromFlickr(
String id, String owner, String secret,
String server, String farm, String title) {
Bitmap bm = null;
FlickrPhotoPath =
"http://farm" + farm + ".static.flickr.com/"
+ server + "/" + id + "_" + secret + "_m.jpg";
imageUrls.add(FlickrPhotoPath);
imageUrls.add(FlickrPhotoPath);
imageUrls.add(FlickrPhotoPath);
imageUrls.add(FlickrPhotoPath);
imageUrls.add(FlickrPhotoPath);
imageUrls.add(FlickrPhotoPath);
imageUrls.add(FlickrPhotoPath);
imageUrls.add(FlickrPhotoPath);
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
private Bitmap LoadPhotoFromFlickr2(
String id, String owner, String secret,
String server, String farm, String title) {
Bitmap bm = null;
FlickrPhotoPath2 =
"http://farm" + farm + ".static.flickr.com/"
+ server + "/" + id + "_" + secret + "_m.jpg";
imageUrls.add(FlickrPhotoPath2);
imageUrls.add(FlickrPhotoPath2);
imageUrls.add(FlickrPhotoPath2);
imageUrls.add(FlickrPhotoPath2);
imageUrls.add(FlickrPhotoPath2);
imageUrls.add(FlickrPhotoPath2);
imageUrls.add(FlickrPhotoPath2);
imageUrls.add(FlickrPhotoPath2);
URL FlickrPhotoUrl2 = null;
try {
FlickrPhotoUrl2 = new URL(FlickrPhotoPath2);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl2.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
}
photos.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<RelativeLayout
android:id="#+id/layout4"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:cropToPadding="false"
android:scaleType="fitXY"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/layout2"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/layout1"
>
<ImageView
android:id="#+id/imageView1"
android:layout_width="180dp"
android:layout_height="210dp"
android:layout_alignParentLeft="true"
android:adjustViewBounds="true"
android:cropToPadding="false"
android:paddingTop="1dp"
android:scaleType="fitXY"
/>
<GridView
android:id="#+id/gridView"
android:layout_width="180dp"
android:layout_height="210dp"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/imageView1"
android:adjustViewBounds="true"
android:cropToPadding="false"
android:numColumns="2"
android:scaleType="fitXY"
></GridView>
</RelativeLayout>
<RelativeLayout
android:id="#+id/layout3"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/layout2"
android:padding="15dp">
<com.pepup.league.ui.fonts.AvenirNextLtRegular
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="JULY-2014"
android:textColor="#b2b2b2"
android:textSize="15sp" />
<View
android:id="#+id/line1"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:layout_toLeftOf="#+id/textView"
android:background="#b2b2b2" />
<View
android:id="#+id/line2"
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/textView"
android:background="#b2b2b2" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/layout5"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/layout3">
<GridView
android:id="#+id/gridView2"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:adjustViewBounds="true"
android:cropToPadding="false"
android:horizontalSpacing="0dp"
android:numColumns="5"
android:scaleType="fitXY"
android:stretchMode="columnWidth"
android:verticalSpacing="0dp"></GridView>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
grid_single.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/grid_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"></ImageView>
</LinearLayout>
It is because you use android:padding="5dp" in grid_single.xm in LinearLayout. If you want remove spaces you need use xml like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/grid_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"></ImageView>
</LinearLayout>

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

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

Scrolling is not perform in Listview in android

I have a problem that, I am adding listview in LinearLayout dynamically through code and set the EndlessAdapter into that, Data is shown correctly but we are unable to scroll from top to bottom in the list. I don't know why? please suggest me any solution regarding the same.
Code:
public void setValuesInCategoryChild(String url, final String filter, final String from, final String to) {
if (isOnline()) {
final ProgressDialog dialog = ProgressDialog.show(ResearchList.this, "Research List ", "Please wait... ", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// System.out.println("The id after Save:"+id.get(0).toString());
// catagory.addAll(keyword_vector1);
linear_Category_Child.setVisibility(View.GONE);
linear_Category_Child_Child.setVisibility(View.VISIBLE);
// tv_Child_Header.setText("Volvo");
tv_CategoryChildHeader.setText(from);
setHeaderImage(tv_CategoryChildHeader.getText().toString());
System.out.println("The size of Cat Display names:" + coll.getDisplayNames().size());
System.out.println("The size of Cat Images:" + coll.getImages().size());
System.out.println("The size of Cat price:" + coll.getPrice().size());
System.out.println("The size of Cat Year:" + coll.getYears().size());
System.out.println("The size of Cat Rating:" + coll.getRating().size());
System.out.println("The size of Cat Mpg:" + coll.getMpg().size());
setHeaderImage(tv_CategoryChildHeader.getText().toString());
if(coll.getDisplayNames().size()!=0) {
lvCategory = new ListView(ResearchList.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lvCategory.setLayoutParams(params);
// Adapter for MPG Search
demoAdapterCat = new DemoAdapterCat();
lvCategory.setAdapter(demoAdapterCat);
layout_ResearchList_BrandList.addView(lvCategory);
Utility.setListViewHeightBasedOnChildren(lvCategory);
}else {
/*lvCategory.invalidate();
lvCategory.setAdapter(null);*/
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("No Data Available for the Particular Search.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
dialog.dismiss();
}
};
final Thread checkUpdate = new Thread() {
public void run() {
try {
String sortEncode = URLEncoder.encode("mpg");
String filterEncode = URLEncoder.encode(filter);
String clientEncode = URLEncoder.encode("10030812");
String fromEncode = URLEncoder.encode(from);
String toEncode = URLEncoder.encode(to);
String catUrl = "/v1/vehicles/get-make-models.json?sort=" + sortEncode + "&filter=" + filterEncode + "&client-id=" + clientEncode + "&from=" + fromEncode;
genSig = new GetSignature(catUrl, "acura");
try {
signature = genSig.getUrlFromString();
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// jsonString =
// getJsonSring("http://api.highgearmedia.com/v1/vehicles/get-models.json?make=acura&client-id=10030812&signature=LWQbdAlJVxlXZ1VO2mfqAA==");
// String signatureEncode =
// URLEncoder.encode(signature);
String urlEncode = URLEncoder.encode(catUrl + "&signature=" + signature);
jsonString = getJsonSring("http://apibeta.highgearmedia.com" + catUrl + "&signature=" + signature);
System.out.println("The json category:===>" + jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParse json = new JsonParse(jsonString);
json.parseCat();
LIST_SIZE = coll.getDisplayNames().size();
for (int i = 0; i <= BATCH_SIZE; i++) {
// countriesSub.add(COUNTRIES[i]);
countriesSubCat.add(coll.getDisplayNames().get(i));
imagesSubCat.add(coll.getImages().get(i));
YearSubCat1.add(coll.getYears().get(i));
YearSubCat2.add(coll.getYears().get(i + 1));
mpgSubCat1.add(coll.getMpg().get(i));
mpgSubCat2.add(coll.getMpg().get(i + 1));
priceSubCat1.add(coll.getPrice().get(i));
priceSubCat2.add(coll.getPrice().get(i + 1));
ratingSubCat1.add(coll.getRating().get(i));
ratingSubCat2.add(coll.getRating().get(i + 1));
}
setLastOffset(BATCH_SIZE);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
} else {
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("Network Connection unavailable.");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
}
Layout:
<LinearLayout
android:id="#+id/linear_ResearchListCategoryChild_Child"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="gone" >
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_HeaderBlock"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/catagory_bar"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_ResearchListCategoryChild_Child_Header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="Work in Progress"
android:textColor="#ffffff"
android:textStyle="bold" android:layout_marginLeft="60dip"/>
<ImageView
android:id="#+id/img_ResearchListCategory_ChildHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dip"
android:src="#drawable/up_arrow" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/list_arrow_up" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/linear_ResearchListCategoryChild_Child_Header"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="#drawable/nav_bg"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:clickable="true"
android:text="Highest Rated"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView5"
android:layout_alignBottom="#+id/textView5"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/textView5"
android:clickable="true"
android:text="A-Z"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView6"
android:layout_alignBottom="#+id/textView6"
android:layout_marginLeft="40dp"
android:layout_toRightOf="#+id/textView6"
android:clickable="true"
android:text="Price"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView7"
android:layout_alignBottom="#+id/textView7"
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:clickable="true"
android:text="MPG"
android:textColor="#ffffff"
android:textStyle="bold" android:gravity="center"/>
</RelativeLayout>
<!--
<RelativeLayout
android:id="#+id/relative_down_arrow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
>
</RelativeLayout>
-->
<LinearLayout
android:id="#+id/linearArrowLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:visibility="visible">
<ImageView
android:id="#+id/Highly_rated"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="51dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/AZ_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="78dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/Price_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="59dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
<ImageView
android:id="#+id/MPG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="55dp"
android:src="#drawable/selector_arrow"
android:visibility="invisible" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dip"
android:layout_marginRight="12dip" android:background="#ffffff" android:id="#+id/layout_ResearchList_BrandList">
</LinearLayout>
</LinearLayout>
DemoAdapterCat:
class DemoAdapterCat extends EndlessAdapter {
ImageLoader image = new ImageLoader(ResearchList.this);
private RotateAnimation rotate = null;
ArrayList<String> tempListNamesCat = new ArrayList<String>();
ArrayList<String> tempListImagesCat = new ArrayList<String>();
ArrayList<String> tempListYearCat1 = new ArrayList<String>();
ArrayList<String> tempListYearCat2 = new ArrayList<String>();
ArrayList<String> tempListmpgCat1 = new ArrayList<String>();
ArrayList<String> tempListmpgCat2 = new ArrayList<String>();
ArrayList<String> tempListpriceCat1 = new ArrayList<String>();
ArrayList<String> tempListpriceCat2 = new ArrayList<String>();
ArrayList<String> tempListRatingCat1 = new ArrayList<String>();
ArrayList<String> tempListRatingCat2 = new ArrayList<String>();
DemoAdapterCat() {
super(new CategoryListLazyAdapter(ResearchList.this,
countriesSubCat, imagesSubCat, YearSubCat1, YearSubCat2,
mpgSubCat1, mpgSubCat2, priceSubCat1, priceSubCat2,
ratingSubCat1, ratingSubCat2));
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
rotate = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
/*
* #Override public int getCount() { return
* brandList.getDisplayNames().size(); //return count+=10; }
*/
#Override
protected View getPendingView(ViewGroup parent) {
row = getLayoutInflater().inflate(R.layout.categorylist, null);
child = row.findViewById(R.id.tv_CategoryItem_Name);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.linear_CategoryList_itemlayer2);
child.setVisibility(View.GONE);
/*
* child = row.findViewById(R.id.img_CategoryItem);
* child.setVisibility(View.GONE); child =
* row.findViewById(R.id.img_CategoryItem_Arrow);
* child.setVisibility(View.GONE);
*/
/*
* child = row.findViewById(R.id.linear_main_MPG);
* child.setVisibility(View.GONE);
*/
child = row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return (row);
}
#Override
protected boolean cacheInBackground() {
//count += 10;
SystemClock.sleep(100000);
tempListNamesCat.clear();
tempListImagesCat.clear();
tempListmpgCat1.clear();
tempListmpgCat2.clear();
tempListpriceCat1.clear();
tempListpriceCat2.clear();
tempListYearCat1.clear();
tempListYearCat2.clear();
tempListRatingCat1.clear();
tempListRatingCat2.clear();
// countriesSubCat.clear();
// imagesSubCat.clear();
// YearSubCat1.clear();
// YearSubCat2.clear();
// mpgSubCat1.clear();
// mpgSubCat2.clear();
// priceSubCat1.clear();
// priceSubCat2.clear();
// ratingSubCat1.clear();
// ratingSubCat2.clear();
int lastOffset = getLastOffset();
if (lastOffset < LIST_SIZE) {
int limit = lastOffset + BATCH_SIZE;
for (int i = (lastOffset + 1); (i <= limit && i < LIST_SIZE); i++) {
tempListNamesCat.add(coll.getDisplayNames().get(i));
tempListImagesCat.add(coll.getImages().get(i));
tempListmpgCat1.add(coll.getMpg().get(i));
tempListmpgCat2.add(coll.getMpg().get(i + 1));
tempListpriceCat1.add(coll.getPrice().get(i));
tempListpriceCat2.add(coll.getPrice().get(i + 1));
tempListRatingCat1.add(coll.getRating().get(i));
tempListRatingCat2.add(coll.getRating().get(i + 1));
tempListYearCat1.add(coll.getYears().get(i));
tempListYearCat2.add(coll.getYears().get(i + 1));
}
setLastOffset(limit);
if (limit < LIST_SIZE) {
// return true;
return (getWrappedAdapter().getCount() < coll
.getDisplayNames().size());
} else {
return false;
}
} else {
return false;
}
}
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
// Activity activity = this;
// ArrayAdapter<String> arrAdapterNew =
// (ArrayAdapter<String>)getWrappedAdapter();
CategoryListLazyAdapter arrAdapterNewCategory = (CategoryListLazyAdapter) getWrappedAdapter();
// int listLen = tempList.size();
// int listLen = tempListNames.size();
countriesSubCat.addAll(tempListNamesCat);
imagesSubCat.addAll(tempListImagesCat);
mpgSubCat1.addAll(tempListmpgCat1);
mpgSubCat2.addAll(tempListmpgCat2);
priceSubCat1.addAll(tempListpriceCat1);
priceSubCat2.addAll(tempListpriceCat2);
ratingSubCat1.addAll(tempListRatingCat1);
ratingSubCat2.addAll(tempListRatingCat2);
YearSubCat1.addAll(tempListYearCat1);
YearSubCat2.addAll(tempListYearCat2);
arrAdapterNewCategory.notifyDataSetChanged();
/*Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);*/
/*
* for(int i=0; i<listLen; i++){ //
* arrAdapterNew.add(tempList.get(i)); }
*/
}
}
Thanks in adavance.
Try adding a ScrollView in the xml file.

Categories

Resources