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.
Related
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.
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.
Problem Is that i am not able to fit the graph according to screen. some of the portion of graph is cutting by right side.I tried lot to set the margin from Right but nothing works for me.As You can see in attached image the last bar is cutting by half. Please anyone help me.
*layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:orientation="vertical" >
<TableLayout
android:id="#+id/table1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:shrinkColumns="6"
android:stretchColumns="*" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#4CC1D2"
android:padding="4dip" >
<ImageButton
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="left"
android:layout_span="1"
android:onClick="gotoback"
android:background="#4CC1D2"
android:src="#drawable/backb" />
<TextView
android:id="#+id/currentMonth"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_span="5"
android:gravity="left"
android:text="How You want to Track"
android:textColor="#ffffff"
android:layout_marginLeft="-18dp"
android:textSize="21sp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/table2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:shrinkColumns="9"
android:stretchColumns="*" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E6E6E6"
android:padding="5dip" >
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_span="3"
android:background="#FFFFFF"
android:gravity="center"
android:src="#drawable/lstweek" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_span="3"
android:background="#FFFFFF"
android:clickable="true"
android:onClick="getmonth"
android:src="#drawable/lstm" />
<ImageButton
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginRight="10dp"
android:layout_span="3"
android:background="#4CC1D2"
android:gravity="center"
android:onClick="getmonth1"
android:src="#drawable/all" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/chart_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical" >
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/logs7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#4CC1D2"
android:onClick="alllogs"
android:text="View Logs"
android:textColor="#FFFFFF"
android:textSize="22dp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>*
Activity Java file.
public class CalorieConsumedTrackerActivity extends Activity {
private GraphicalView mChart;
JSONArray dailydata = null;
private ProgressDialog progressDialog;
private static String url_display_user ;
JSONParser jsonParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_RESPONSE = "getdata";
JSONArray graphdatas = null;
ArrayList<HashMap<String, String>> getdata;
private static final String TAG_MESSAGE = "message";
String userid=null;
String[] mMonth = new String[7] ;
String[] datefromdb = new String[7] ;
int[] x = {1,2,3,4,5,6,7};
int[] target = new int[7];
int[] consumed = new int[7];
int[]showtarget=new int[7];
int[]showconsumed=new int[7];
XYSeries incomeSeries = new XYSeries("Target");
// Creating an XYSeries for Expense
XYSeries expenseSeries = new XYSeries("Consumed");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calories_consumed );
getdata=new ArrayList<HashMap<String,String>>();
DatabaseHandler db=new DatabaseHandler(getApplicationContext());
HashMap<String,String> user = new HashMap<String,String>();
user=db.getUserDetails();
userid=user.get("userid");
Calendar myCalendar = Calendar.getInstance();
myCalendar.set(myCalendar.getTime().getYear()+1900,myCalendar.getTime().getMonth() , myCalendar.getTime().getDate());
for (int i = 6; i >=0; i--) {
myCalendar.add(Calendar.DAY_OF_YEAR, -1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(myCalendar.getTime());
System.out.println(date);
mMonth[i]=date;
}
new GetGraphData().execute();
}
private void openChart(){
}
class GetGraphData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(CalorieConsumedTrackerActivity.this, "wait", "Fetching...");
}
#Override
protected String doInBackground(String... params) {
url_display_user = "http://www.bharatwellness.com/getGraphData.php";
// Building Parameters
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
parametres.add(new BasicNameValuePair("userid", userid));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_display_user,
"GET", parametres);
// Check your log cat for JSON reponse
Log.d("All data : ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
JSONObject c=null;
if (success == 1) {
int i;
int cal=0;
// products found
// Getting Array of Products
graphdatas = json.getJSONArray(TAG_RESPONSE);
// looping through All RESPONSE
for (i = 0; i < graphdatas.length(); i++) {
c = graphdatas.getJSONObject(i);
// Storing each json item in variable
String createddate = c.getString("createddate");
datefromdb[i]=createddate;
String caloriegoal = c.getString("caloriegoal");
String calorieconsumed = c.getString("calorieconsumed");
double cgoal=Double.parseDouble(caloriegoal);
cal=(int) Math.round(cgoal);
target[i]=cal;
double csumed=Double.parseDouble(calorieconsumed);
int calc=(int) Math.round(csumed);
consumed[i]=calc;
}
for(int x=0;x<mMonth.length;x++){
for(int y=0;y<datefromdb.length;y++){
if(mMonth[x].equals(datefromdb[y])){
showconsumed[x]=consumed[y];
showtarget[x]=target[y];
}
if(showtarget[x]==0){
showtarget[x]=cal;
}
}
}
// Creating an XYSeries for Income
// Adding data to Income and Expense Series
for(int j=0;j<x.length;j++){
incomeSeries.add(x[j], showtarget[j]);
expenseSeries.add(x[j],showconsumed[j]);
}
runOnUiThread(new Runnable() {
public void run() {
// Creating a dataset to hold each series
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Income Series to the dataset
dataset.addSeries(incomeSeries);
// Adding Expense Series to dataset
dataset.addSeries(expenseSeries);
// Creating XYSeriesRenderer to customize incomeSeries
XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
incomeRenderer.setColor(Color.parseColor("#04B431"));
incomeRenderer.setPointStyle(PointStyle.CIRCLE);
incomeRenderer.setFillPoints(true);
incomeRenderer.setLineWidth(2);
incomeRenderer.setChartValuesTextSize(20);
incomeRenderer.setDisplayChartValues(true);
// Creating XYSeriesRenderer to customize expenseSeries
XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
expenseRenderer.setColor(Color.parseColor("#FF8000"));
expenseRenderer.setPointStyle(PointStyle.CIRCLE);
expenseRenderer.setFillPoints(true);
expenseRenderer.setLineWidth(2);
expenseRenderer.setChartValuesTextSize(20);
expenseRenderer.setDisplayChartValues(true);
for(int z=0;z<mMonth.length;z++){
String createddate=mMonth[z];
String month=createddate.substring(5, 7);
System.out.println(month);
int m=Integer.parseInt(month);
System.out.println(m);
switch (m) {
case 1:
month="Jan";
break;
case 2:
month="Feb";
break;
case 3:
month="Mar";
break;
case 4:
month="Apr";
break;
case 5:
month="May";
break;
case 6:
month="June";
break;
case 7:
month="July";
break;
case 8:
month="Aug";
break;
case 9:
month="Sep";
break;
case 10:
month="Oct";
break;
case 11:
month="Nov";
break;
case 12:
month="Dec";
break;
}
String day=createddate.substring(8, 10);
String finaldate= day+" "+month;
mMonth[z]=finaldate ;
}
// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setAxisTitleTextSize(30);
multiRenderer.setBackgroundColor(Color.WHITE);
multiRenderer.setAxesColor(Color.WHITE);
multiRenderer.setApplyBackgroundColor(true);
multiRenderer.setXLabels(0);
multiRenderer.setChartTitle("Calories Consumed Progress Chart");
multiRenderer.setGridColor(Color.WHITE);
multiRenderer.setXTitle("");
multiRenderer.setYTitle("Calories");
multiRenderer.setZoomButtonsVisible(true);
multiRenderer.setBarSpacing(4);
multiRenderer.setPanEnabled(false, false);
multiRenderer.setLabelsTextSize(20);
multiRenderer.setAxesColor(Color.BLACK);
multiRenderer.setXLabelsColor(Color.BLACK);
multiRenderer.setYAxisMax(3000);
multiRenderer.setYAxisMin(0);
multiRenderer.setYLabelsColor(0, Color.BLACK);
double panLimits[]={20,20,20,20};
multiRenderer.setPanLimits(panLimits);
multiRenderer.setMarginsColor(Color.WHITE);
for(int i=0;i<mMonth.length;i++){
multiRenderer.addXTextLabel(i+1, mMonth[i]);
multiRenderer.setAxisTitleTextSize(20);
int mar[]={20,20,20,20};
multiRenderer.setMargins(mar);
multiRenderer.setGridColor(Color.LTGRAY);
}
// Adding incomeRenderer and expenseRenderer to multipleRenderer
// Note: The order of adding dataseries to dataset and renderers to multipleRenderer
// should be same
multiRenderer.addSeriesRenderer(incomeRenderer);
multiRenderer.addSeriesRenderer(expenseRenderer);
multiRenderer.setPanEnabled(false);
// Getting a reference to LinearLayout of the MainActivity Layout
LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart_container);
chartContainer.setBackgroundColor(Color.WHITE);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout con = (LinearLayout) findViewById(R.id.linear1);
con.setBackgroundColor(Color.WHITE);
// Specifying chart types to be drawn in the graph
// Number of data series and number of types should be same
// Order of data series and chart type will be same
String[] types = new String[] { LineChart.TYPE, BarChart.TYPE };
// Creating a combined chart with the chart types specified in types array
mChart = (GraphicalView) ChartFactory.getCombinedXYChartView(getBaseContext(), dataset, multiRenderer, types);
mChart.setBackgroundColor(Color.WHITE);
multiRenderer.setClickEnabled(true);
multiRenderer.setSelectableBuffer(10);
multiRenderer.setPanEnabled(false);
mChart.setMinimumWidth(100);
// Adding the Combined Chart to the LinearLayout
chartContainer.addView(mChart,layoutParams);
}});
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog after getting all products
progressDialog.dismiss();
// updating UI from Background Thread
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
}
![enter image description here][2]
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.
Here is to control visibility of the layout
if (!(imagepath[i].toString().equals("no picture"))) {
try {
aURL = new URL("http://www.orientaldaily.com.my/"
+ imagepath[i]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
layout_image.setVisibility(View.VISIBLE);
imageview.setVisibility(View.VISIBLE);
imageview.setScaleType(ScaleType.CENTER_CROP);
imageview.setImageBitmap(bm);
} catch (IOException e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
}
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.main_alllatestnewslist, from, to);
lv.setAdapter(adapter);
Here is to initialize it
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_alllatestnews);
lv = (ListView) findViewById(android.R.id.list);
RelativeLayout temp = (RelativeLayout)findViewById(R.id.layout_temp);
LayoutInflater liInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
temp.addView(liInflater.inflate(R.layout.main_alllatestnewslist, null));
Here is the main_alllatestnews.xml
<LinearLayout
android:id="#+id/layout_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/layout_menu"
android:layout_below="#id/layout_title"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Here is the main_alllatestnewslist.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_temp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/background_news_list" >
<LinearLayout
android:id="#+id/layout_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10px"
android:layout_marginTop="10px" >
<ImageView
android:id="#+id/image_alllatestnewstitle"
android:layout_width="134px"
android:layout_height="80px"
android:src="#drawable/image_loading_failed_1"
android:visibility="invisible" />
</LinearLayout>
When i run this, it gave me Nullpointerexception at line
temp.addView(liInflater.inflate(R.layout.main_alllatestnewslist, null)); <-- inflater still null...
How to solve this?
Change
setContentView(R.layout.main_alllatestnews);
to
setContentView(R.layout.main_alllatestnewslist);
because layout_image is in layout main_alllatestnewslist
Edited:
LayoutInflater liInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
yourView.addView(liInflater.inflate(R.layout.main_alllatestnewslist, null))
something like that.
;