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.
Related
So I have an SQLite database. I try to update and there is no error in my android application. When I update only the name or the cost, it successfully updated but the image not showing in my gridview. But when I Update only the image, it is successfully updated.Can someone please help me out here!
this my Database Class:
public class Database extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydaringdb";
private static final int DATABASE_VERSION = 2;
public static final String TABLE_PRODUK = "produk";
public static final String KEY_ID_PRODUK = "id";
public static final String KEY_NAMA_PRODUK = "nama_produk";
public static final String KEY_HARGA_PRODUK = "harga_produk";
public static final String KEY_GAMBAR_PRODUK = "gambar_produk";
//for showing 1 product
public ModelProduk getnama(int selection) {
SQLiteDatabase db = this.getReadableDatabase();
String cb = "SELECT * FROM " + TABLE_PRODUK + " WHERE " + KEY_ID_PRODUK + "= '" + selection + "'";
Cursor cursor = db.rawQuery(cb, null);
if (cursor != null)
cursor.moveToFirst();
ModelProduk modelProduk = new ModelProduk();
modelProduk.set_id(Integer.parseInt(cursor.getString(0)));
modelProduk.set_nama(cursor.getString(1));
modelProduk.set_harga(Integer.parseInt(cursor.getString(2)));
modelProduk.set_gambar(cursor.getBlob(3));
return modelProduk;
}
//for update 1 product
public void update(ModelProduk modelProduk) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAMA_PRODUK, modelProduk.get_nama());
values.put(KEY_HARGA_PRODUK, modelProduk.get_harga());
values.put(KEY_GAMBAR_PRODUK, modelProduk.get_gambar());
String where = "id=?";
String[] whereArgs = new String[] {String.valueOf(modelProduk.get_id())};
// update baris
db.update(TABLE_PRODUK, values, where, whereArgs);
}
My update class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_produk);
init();
tambahgambaru.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showFileChooser();
}
});
simpandatau.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
modelProduk.set_nama(deskripsiu.getText().toString());
modelProduk.set_harga(Integer.parseInt(harga_produku.getText().toString()));
modelProduk.set_gambar(getImageByte(bitmap));
db.update(modelProduk);
Toast.makeText(getApplicationContext(), "Data Berhasil Diubah!", Toast.LENGTH_SHORT).show();
}
});
kembaliu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(UpdateProduk.this, Produk.class);
startActivity(i);
finish();
}
});
}
public void refresh(){
produklist = new ArrayList<>();
adapter = new ProdukAdapter( this, produklist);
produklist.clear();
produklist.addAll(db.getAllProduk());
adapter.notifyDataSetChanged();
}
private void init(){
pilih = getIntent().getIntExtra("id_produk", 0);
db = new Database(this);
modelProduk = db.getnama(pilih);
gambar_produku = (ImageView) findViewById(R.id.pilihgambaru);
tambahgambaru = (Button) findViewById(R.id.btaddu);
simpandatau = (Button) findViewById(R.id.btsimpanu);
deskripsiu = (EditText) findViewById(R.id.etdesku);
harga_produku = (EditText) findViewById(R.id.ethargau);
kembaliu = (Button) findViewById(R.id.btkembaliu);
deskripsiu.setText(modelProduk.get_nama());
harga_produku.setText(String.valueOf(modelProduk.get_harga()));
gambar_produku.setImageBitmap(bitmap(modelProduk.get_gambar()));
}
public void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Pilih Gambar"), 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode==RESULT_OK) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
gambar_produku.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public byte[] getImageByte(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[]=null;
if(bitmap!=null) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
imageInByte=stream.toByteArray();
}
return imageInByte;
}
public Bitmap bitmap (byte[] byteImage){
byte[] outImage = byteImage;
Bitmap image ;
if (outImage != null){
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
image = BitmapFactory.decodeStream(imageStream);
}else {
image= null;
}
return image;
}
}
my update.xml:
<ImageView
android:id="#+id/pilihgambaru"
android:layout_width="150dp"
android:layout_height="150dp"
android:src="#mipmap/ic_launcher"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/btaddu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/pilihgambaru"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="pilih gambar"
android:layout_centerHorizontal="true"
/>
<EditText
android:id="#+id/etdesku"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
android:layout_below="#id/btaddu"
android:layout_centerHorizontal="true"
android:hint="Masukkan Deskripsi Barang"
android:inputType="textMultiLine"
android:maxLength="100"
/>
<EditText
android:id="#+id/ethargau"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#id/etdesku"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:hint="Masukkan Harga Barang"
android:inputType="number"
android:maxLength="10"
/>
<Button
android:id="#+id/btsimpanu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ethargau"
android:layout_marginTop="10dp"
android:text="simpan"
android:layout_marginLeft="100dp"
android:layout_centerHorizontal="true"
/>
<Button
android:id="#+id/btkembaliu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/btsimpanu"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="ke produk"
/>
I have two images male and female. I want to set image male if my gender is contains male and set image female if my gender is contains female.
The string gender is getting from JSON array.
Here is my code.
public class Profile extends AppCompatActivity {
JSONArray jsonarray = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_ID= "id";
private static final String TAG_PROFILE= "user";
private static final String TAG_NAME = "name";
private static final String TAG_MOB = "phn_number";
private static final String TAG_PER_ADD= "permanent_address";
private static final String TAG_PRE_ADD = "present_address";
private static final String TAG_OFF_ADD = "office_address";
private static final String TAG_MRG_ANN = "anniversary";
private static final String TAG_CITY = "city";
private static final String TAG_DOB = "dob";
private static final String TAG_NATIONALITY = "nationality";
private static final String TAG_OCC = "occupation";
private static final String TAG_MRG_STATUS = "martial_status";
private static final String TAG_GENDER = "gender";
private static final String TAG_NOY = "no_of_years";
private static String TAG_EMAIL = "email";
ListView list;
TextView name, mobile, permanent_add, present_add, office_add,mrg_anni,city,date_of_birth,nationality,occupation,mrd_status,gender,no_of_yr,email;
ArrayList<HashMap<String, String>> profile;
ImageView male,female;
private ProgressDialog pDialog;
String url = "http://app.goholidays.info/user_login.php";
String uid;
View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_profile);
profile = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(android.R.id.list);
male = (ImageView) findViewById(R.id.profileimagemale);
female = (ImageView) findViewById(R.id.profileimagefemale);
name = (TextView) findViewById(R.id.name);
mobile = (TextView) findViewById(R.id.mob);
permanent_add = (TextView) findViewById(R.id.permanent_add);
present_add = (TextView) findViewById(R.id.present_add);
office_add = (TextView) findViewById(R.id.office_add);
mrg_anni = (TextView) findViewById(R.id.mrg_anni);
city = (TextView) findViewById(R.id.city);
date_of_birth = (TextView) findViewById(R.id.dob);
nationality = (TextView) findViewById(R.id.nationality);
occupation = (TextView) findViewById(R.id.o);
mrd_status = (TextView) findViewById(R.id.mrd_status);
gender = (TextView) findViewById(R.id.gender);
no_of_yr = (TextView) findViewById(R.id.no_of_years);
email = (TextView) findViewById(R.id.email);
new ReadJSON().execute();
}
private class ReadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profile.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... param) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Profile.this);
//String post_email = sp.getString("email", TAG_EMAIL);
String post_id = sp.getString("id",uid);
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("email", post_email));
params.add(new BasicNameValuePair("id",post_id));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
// Check your log cat for JSON response
try {
jsonarray = json.getJSONArray(TAG_PROFILE);
// looping through All Products
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
// Storing each json item in variable
uid = jsonobject.getString(TAG_ID);
String name = jsonobject.getString(TAG_NAME);
String phn_number = jsonobject.getString(TAG_MOB);
String permanent_address = jsonobject.getString(TAG_PER_ADD);
String present_address = jsonobject.getString(TAG_PRE_ADD);
String office_address = jsonobject.getString(TAG_OFF_ADD);
String anniversary = jsonobject.getString(TAG_MRG_ANN);
String city = jsonobject.getString(TAG_CITY);
String dob = jsonobject.getString(TAG_DOB);
String nationality = jsonobject.getString(TAG_NATIONALITY);
String occupation = jsonobject.getString(TAG_OCC);
String martial_status = jsonobject.getString(TAG_MRG_STATUS);
final String gender = jsonobject.getString(TAG_GENDER);
String no_of_years = jsonobject.getString(TAG_NOY);
String email = jsonobject.getString(TAG_EMAIL);
// creating new HashMap
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, uid);
contact.put(TAG_NAME, StringUtils.capitalize(name.toLowerCase().trim()));
contact.put(TAG_MOB, phn_number);
contact.put(TAG_PER_ADD, permanent_address);
contact.put(TAG_PRE_ADD, present_address);
contact.put(TAG_OFF_ADD, office_address);
contact.put(TAG_MRG_ANN, anniversary);
contact.put(TAG_CITY, city);
contact.put(TAG_DOB, dob);
contact.put(TAG_NATIONALITY, nationality);
contact.put(TAG_OCC, occupation);
contact.put(TAG_MRG_STATUS, StringUtils.capitalize(martial_status.toLowerCase().trim()));
contact.put(TAG_GENDER, StringUtils.capitalize(gender.toLowerCase().trim()));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (gender.equalsIgnoreCase("male"))
{
male.setVisibility(View.VISIBLE);
female.setVisibility(View.INVISIBLE);
}else{
male.setVisibility(View.INVISIBLE);
female.setVisibility(View.VISIBLE);
}
}
});
contact.put(TAG_NOY, no_of_years+" Years");
contact.put(TAG_EMAIL, email);
// adding HashList to ArrayList
profile.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Profile.this, profile,
R.layout.newpage, new String[] {TAG_NAME, TAG_MOB, TAG_PER_ADD, TAG_PRE_ADD, TAG_OFF_ADD, TAG_MRG_ANN, TAG_CITY, TAG_DOB, TAG_NATIONALITY, TAG_OCC, TAG_MRG_STATUS, TAG_GENDER, TAG_NOY, TAG_EMAIL},
new int[] {R.id.name, R.id.mob, R.id.permanent_add, R.id.present_add, R.id.office_add, R.id.mrg_anni, R.id.city, R.id.dob, R.id.nationality, R.id.o, R.id.mrd_status, R.id.gender, R.id.no_of_years, R.id.email });
list.setAdapter(adapter);
}
});
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences.Editor editor = prefs.edit();
//editor.putString("id",uid);
//editor.commit();
pDialog.dismiss();
}
}
}
and my xml file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1.2"
android:layout_gravity="center"
android:weightSum="1">
<RelativeLayout
android:layout_weight="1.2"
android:layout_width="match_parent"
android:layout_height="0dp">
<ImageView
android:layout_width="#dimen/_110sdp"
android:layout_height="#dimen/_121sdp"
android:src="#drawable/male"
android:id="#+id/profileimagemale"
android:contentDescription="#string/app_name" />
<ImageView
android:layout_width="#dimen/_110sdp"
android:layout_height="#dimen/_121sdp"
android:src="#drawable/female"
android:id="#+id/profileimagefemale"
android:contentDescription="#string/app_name" />
</RelativeLayout>
<View
android:id="#+id/view1"
android:layout_width="#dimen/_110sdp"
android:layout_height="#dimen/_1sdp"
android:layout_marginTop="#dimen/_2sdp"
android:background="#E6E6E6" />
<LinearLayout
android:id="#+id/ll11"
android:layout_width="#dimen/_110sdp"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginTop="#dimen/_5sdp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SEX:"
android:gravity="center"/>
<TextView
android:textColor="#000"
android:layout_marginLeft="#dimen/_5sdp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/gender"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1.8"
android:layout_gravity="center">
<LinearLayout
android:id="#+id/ll01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_5sdp"
android:layout_marginRight="#dimen/_10sdp"
android:orientation="vertical">
<TextView
android:drawableLeft="#drawable/faculties"
android:drawablePadding="#dimen/_10sdp"
android:gravity="center"
android:textColor="#000"
android:hint="000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"/>
</LinearLayout>
.........continued...................................
I am getting error nullpointerexception here is my logcat
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.hotel.yasmeenshaikh.GoHolidays.Profile$ReadJSON$1.run(Profile.java:156)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:807)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:574)
at dalvik.system.NativeStart.main(Native Method)
Please help me solve this issue.
line number 156 is male.setVisibility(View.VISIBLE);
Call new ReadJSON().execute(); after all views are initialized. Because it is executed before your views initialization.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_profile);
profile = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(android.R.id.list);
male = (ImageView) findViewById(R.id.profileimagemale);
female = (ImageView) findViewById(R.id.profileimagefemale);
name = (TextView) findViewById(R.id.name);
mobile = (TextView) findViewById(R.id.mob);
permanent_add = (TextView) findViewById(R.id.permanent_add);
present_add = (TextView) findViewById(R.id.present_add);
office_add = (TextView) findViewById(R.id.office_add);
mrg_anni = (TextView) findViewById(R.id.mrg_anni);
city = (TextView) findViewById(R.id.city);
date_of_birth = (TextView) findViewById(R.id.dob);
nationality = (TextView) findViewById(R.id.nationality);
occupation = (TextView) findViewById(R.id.o);
mrd_status = (TextView) findViewById(R.id.mrd_status);
gender = (TextView) findViewById(R.id.gender);
no_of_yr = (TextView) findViewById(R.id.no_of_years);
email = (TextView) findViewById(R.id.email);
new ReadJSON().execute(); // Call here
}
I have a listview where I have 50 elements being displayed. I have decided to paginate the view so on each part of the view there are 10 elements and then a next button is clicked to get to the next 10 elements. How can i set 10 data ? I follow this article
http://rakhi577.wordpress.com/2013/05/20/listview-pagination-ex-2/
Here is my code .Can you help me with my code or a link to a guide on how to implement this correctly?
public class MainActivity extends ListActivity {
Context context;
Button btnSearch ;
EditText txtSearch;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
//loadList(0);
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//loadList(j);
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
//String address = c.getString(TAG_ADDRESS);
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I change the code. When i click next button[like 2,3,4,5]. showing first page data. Here is my modified code.Any help Appreciated :
public class MainActivity extends ListActivity {
private TextView title;
Context context;
Button btnSearch ;
EditText txtSearch;
private ListView listview;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
title = (TextView)findViewById(R.id.title);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position%2==0)
{
view.setBackgroundColor(Color.parseColor("#F4FA58"));
}else
{
view.setBackgroundColor(Color.parseColor("#DA81F5"));
}
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
new GetContacts().execute();
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
title.setText("Page "+(index+1)+" of "+noOfBtns);
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int number = 0;
int start = number * NUM_ITEMS_PAGE;
// looping through All Contacts
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
//for (int i = 0; i < contacts.length(); i++) {
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
Below is my code to show list view with pagination. There is two blue button for change pages.
You can customize according to you need.
Create UserCategory.java
package com.UserCategory;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
public class UserCategory extends Activity implements OnClickListener{
private final int PAGE_SIZE = 5;
private int StartingIndex = 0;
ArrayList<String> userClass=new ArrayList<String>();
int textlength=0;
private String lv_arr[];
private ListView lv1;
EditText searchText;
//Button Previous;
private String Machine[]={"Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12","Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12"};
ImageView next,Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
searchText=(EditText)findViewById(R.id.et_Serchlist);
next=(ImageView)findViewById(R.id.btn_next);
Previous=(ImageView)findViewById(R.id.btn_previous);
next.setOnClickListener(this);
Previous.setOnClickListener(this);
//parsing();
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , Machine));
changeListViewModel(0);
}
private void changelist(int startingIndex) {
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}else if(startingIndex >= userClass.size())
startingIndex -= PAGE_SIZE;
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("ending index"+endingIndex);
if(StartingIndex!=0){
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
if(endingIndex > userClass.size()) endingIndex = userClass.size();
try {
String[] subSet = getDataSubset1(startingIndex, endingIndex);
System.out.println("subSet array"+subSet);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
} catch (Exception e) {
e.printStackTrace();
}
}
private String[] getDataSubset1(int startingIndex, int endingIndex){
String[] changeList = new String[endingIndex - startingIndex];
int index = -1;
for(int x = startingIndex; x < endingIndex; x++)
changeList[++index] = userClass.get(x);
return changeList;
}
private void changeListViewModel(int startingIndex){
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}
else if(startingIndex >= Machine.length){
startingIndex -= PAGE_SIZE;
}
System.out.println("strating"+startingIndex);
System.out.println("startingIndex"+startingIndex);
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("endingIndex"+endingIndex);
if(StartingIndex!=0)
{
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
System.out.println("ending index"+endingIndex);
if(endingIndex > Machine.length) {
endingIndex = Machine.length;
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
String[] subSet = getDataSubset(startingIndex, endingIndex);
System.out.println("subSet main array"+subSet.length);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
}
private String[] getDataSubset(int startingIndex, int endingIndex){
String[] toRet = new String[endingIndex - startingIndex];
int index = -1;
System.out.println("index"+index);
for(int x = startingIndex; x < endingIndex; x++)
toRet[++index] = Machine[x];
return toRet;
}
private void parsing() {
// TODO Auto-generated method stub
try {
URL url = new URL("http://10.10.1.100/DogEventsWebService/EventService.svc/categories/1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("UserCategory");
Machine = new String[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Machine[i] = new String();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("ClassDescription");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Machine[i]=((Node) nameList.item(0)).getNodeValue();
}
System.out.println("after for loop Machine"+Machine);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_next:
textlength=searchText.getText().length();
System.out.println("nextbutton"+textlength);
if(textlength==0){
changeListViewModel(StartingIndex + PAGE_SIZE);
}else{
changelist(StartingIndex + PAGE_SIZE);
}
break;
case R.id.btn_previous:
textlength=searchText.getText().length();
if(textlength==0){
changeListViewModel(StartingIndex - PAGE_SIZE);
}else{
changelist(StartingIndex - PAGE_SIZE);
}
break;
default:
break;
}
}
}
create main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<View android:layout_height="35dp"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<TextView android:id="#+id/tv_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:layout_alignParentTop="true"
android:layout_marginLeft="0dp"
android:textSize="25dp"/>
<EditText
android:id="#+id/et_Serchlist"
android:layout_height="35dp"
android:paddingLeft="19dp"
android:layout_marginLeft="60dp"
android:layout_toRightOf="#+id/tv_header"
android:maxLength="20"
android:maxLines="1"
android:inputType="text"
android:hint="Search"
android:textColor="#ffffff"
android:background="#drawable/my_border"
android:layout_width="100dip"/>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:textSize="4px"
android:layout_below="#+id/tv_header"
android:layout_above="#+id/btn_previous"
android:layout_height="wrap_content" />
<View android:layout_height="55dp"
android:layout_below="#+id/ListView0"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<ImageView
android:src="#drawable/grewprevious"
android:id="#+id/btn_Whiteprevious"
android:layout_width="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/right"
android:id="#+id/btn_grewforward"
android:layout_width="wrap_content"
android:layout_marginLeft="259dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/backward"
android:id="#+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:onClick="backButtonClicked"/>
<ImageView android:src="#drawable/forward"
android:id="#+id/btn_next"
android:layout_width="80dp"
android:layout_marginBottom="6dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/ListView0"
android:layout_marginLeft="249dp"
android:text="Next"
android:onClick="nextButtonClicked"/>
</RelativeLayout>
Create userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/tv_className"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Add my_border.xml into Drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dip" android:color="#ee777777" />
<solid android:color="#ee444444"/>
<padding
android:left="20dip"
android:top="2dip"
android:right="20dip"
android:bottom="2dip" />
<corners android:radius="15dip" />
![enter image description here][1]</shape>
If it give error for iamges then use any other images and run application.
Let me know it work for you.
Thanks
I have a custom gridVIew With an ImageView and a TextView in it, and I have set the gridView as a it show 2 coloumns. here is the code of custom_grid_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<ImageView
android:id="#+id/imgBookCover"
android:layout_width="88dp"
android:layout_height="102dp"
android:adjustViewBounds="true"
android:background="#drawable/rounded_image_borders"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:src="#drawable/book5" >
</ImageView>
<TextView
android:id="#+id/txt_BookTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center_horizontal"
android:lines="1"
android:text="TextView"
android:textColor="#color/White"
android:textColorHighlight="#656565" >
</TextView>
and here is the layout of gridview.xml
<GridView
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_below="#+id/Rel_Spinner"
android:layout_centerHorizontal="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
Its loading the images from server and showing the correct images and text for the first time, as I have implemented the EndlessScrollListner class in my project.
In the first itration im loading 12 images from the server, when i Scroll down the gridView to end it sends the second request to Load 12 more images and text from the server.
Here the actual problem starts its loading the same images and text.
Please have a look on my bulky code and tell where I am commeting the mistake.
public class Home extends Activity {
static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
static final String KEY_ITEM = "Book"; // parent node
static final String KEY_BOOKAUTHOR = "book_author";
static final String KEY_BOOKRATING = "BookRating";
static final String KEY_BOOKID = "BookID";
static final String KEY_BOOKDESC = "BookDescription";
static final String KEY_BOOKDATEPUBLISHED = "DatePublished";
static final String KEY_BOOKTITLE = "BookTitle";
static final String KEY_BOOKCODE = "BookCode";
static final String KEY_BOOKIMAGE = "BookImage";
static final String KEY_ITEM_BOOKs_LIMIT = "Result"; // parent node
static final String KEY_ITEM_TOTAL_BOOKS = "TotalBooks";
static ArrayList<String> BookTitle = null;
static ArrayList<Integer> BookRating = null;
static ArrayList<String> BookDescription = null;
static ArrayList<String> BookCoverPhotos = null;
static ArrayList<String> BookAuther = null;
static ArrayList<String> BookIDs = null;
static ArrayList<String> BookCode = null;
static ArrayList<String> BookPublishDate = null;
static ArrayList<String> ImageByte = null;
static ArrayList<Bitmap> bitmapArray = null;
static int initialIndex = 12;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
gridView = (GridView) findViewById(R.id.gridview);
gridView.setOnScrollListener(new EndlessScrollListener());
if (BookTitle == null) {
BookTitle = new ArrayList<String>();
BookRating = new ArrayList<Integer>();
BookDescription = new ArrayList<String>();
BookIDs = new ArrayList<String>();
BookCode = new ArrayList<String>();
BookCoverPhotos = new ArrayList<String>();
BookAuther = new ArrayList<String>();
BookPublishDate = new ArrayList<String>();
ImageByte = new ArrayList<String>();
bitmapArray = new ArrayList<Bitmap>();
new UIThread().execute(URL, initialIndex + "");
// Log.i("If", BookTitle + "");
} else {
// Log.i("else", BookTitle + "");
ImageAdapter adapter2 = new ImageAdapter(getBaseContext(),
act);
gridView.setAdapter(adapter2);
}
Im using AsynkTaks to download the images from server. here is the code
private class UIThread extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getParent(),
"Acumlating Books from server...",
"This may Take a few seconds.\nPlease Wait...");
}
#Override
protected String doInBackground(String... params) {
String URL = params[0];
int initialIndex = Integer.valueOf(params[1]);
Log.i("params", params[1] + "");
XMLParser parser = new XMLParser();
String XMLString = parser.getXmlFromUrl_FeaturedBooks(URL,
initialIndex);
Home.initialIndex = Home.initialIndex + 12;
Log.i("Home.initialIndex", Home.initialIndex + "");
Document doc = parser.getDomElement(XMLString);
NodeList nlBooksLimit = doc
.getElementsByTagName(KEY_ITEM_BOOKs_LIMIT);
Element eLimit = (Element) nlBooksLimit.item(0);
String totalBooks = parser.getValue(eLimit, KEY_ITEM_TOTAL_BOOKS);
Log.i("totalBooks", totalBooks + "");
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
Bitmap imageNotFound = BitmapFactory.decodeResource(getResources(),
R.drawable.defaultcoverphoto);
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
try {
BookRating.add(Integer.valueOf(parser.getValue(e,
KEY_BOOKRATING)));
// Log.i("Rating Try", BookRating.get(i) + "");
} catch (Exception e2) {
BookRating.add(0);
// Log.i("Rating Catch", BookRating + "");
}
BookDescription.add(parser.getValue(e, KEY_BOOKDESC));
BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
+ parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED));
BookIDs.add(parser.getValue(e, KEY_BOOKID));
BookCode.add(parser.getValue(e, KEY_BOOKCODE));
// Log.i("URLs & Desc", BookCoverPhotos.toString());
try {
bookImageURL = new URL(BookCoverPhotos.get(i));
} catch (MalformedURLException e1) {
e1.printStackTrace();
// Log.i("URL", "ERROR at image position" + i + "");
}
try {
bitMapImage = BitmapFactory.decodeStream(bookImageURL
.openConnection().getInputStream());
bitmapArray.add(bitMapImage);
publishProgress(i + 1);
} catch (IOException e2) {
e2.printStackTrace();
bitmapArray.add(imageNotFound);
// Log.i("File Not Found", bookImageURL + "");
}
}
Log.i("Book Title", BookTitle + "");
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progressDialog.setMessage(values[0]
+ " Book(s) found \nPlease wait...");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
gridView.setAdapter(adapter);
}
}
and here is the EndlessScrollListner.java code. which send the request to sever again to download when the scroll reaches to the bottom of the gridView.
private class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
new UIThread().execute(URL, Home.initialIndex + "");
Log.i("Reached", "End");
Log.i("Home.initialIndex", Home.initialIndex + "");
loading = true;
}
}
here are 2 pictures to make you more clear my question.
Although pretty late, but I just ran into the same problem. Its happening because of the adapter's getView method.
In your ImageAdapter, if the getView function reuses the view already created then this might be the reason for your image repetition. If the code looks like below, then it is supposed to be changed like the second code snippet to download new images coming from load more.
Snippet 1
public View getView(int position, View v, ViewGroup parent) {
ImageView imageview;
if(v == null)
{
imageview = new ImageView(mcontext);
imageview.setLayoutParams(new GridView.LayoutParams(250,250));
imageview.setPadding(0,0,10,10);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
new DownloadImageTask(imageview).execute(arr.get(position).imageUrl);
}
else
imageview = (ImageView) v;
return imageview;
}
Snippet 2
public View getView(int position, View v, ViewGroup parent) {
ImageView imageview;
if(v == null)
{
imageview = new ImageView(mcontext);
imageview.setLayoutParams(new GridView.LayoutParams(250,250));
imageview.setPadding(0,0,10,10);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
else
imageview = (ImageView) v;
new DownloadImageTask(imageview).execute(arr.get(position).imageUrl);
return imageview;
}
Or probably create a new view altogether but then you may need to handle virtualization and reusability of the gridView/listView by yourself.
I already tried references from similar question on SO, but hasn't got the appropriate solution.
I'm trying to fetch the data from a webpage and display it in format consisting of rows having 4 columns.
Data present on webpage:
SBIN ;1916.00;1886.85;1.54#LT ;1315.50;1310.30;0.40#TCS ;1180.00;1178.00;0.17#AXISBANK ;1031.30;1005.95;2.52#MARUTI ;1000.35;992.35;0.81#PNB ;931.90;916.35;1.70#GAIL ;400.00;398.45;0.39#
I want to diaplay it in the form
SBIN.........1916.00.....1886.85.....1.54
LT...........1315.50.....1310.30.....0.40 and so on.
Note that I don't want dots, I want each value to be a separate column within a row.
My Data consists of 7 rows.
When I run the below code, I get this output
i.e.
values[0] values[1] values[2] values[3]
values[1] values[2] values[3] values[4]
values[2] values[3] values[4] values[5]
(It prints all 4 cols of 1st row, then col 2-4 of 1st row and col1 of 2nd row, then cols 3-4 of 1st row and col 1-2 of 2nd row and so on...)
ReadWebpageAsyncTask.java
public class ReadWebpageAsyncTask extends Activity {
private EditText ed;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText) findViewById(R.id.ed);
lv = (ListView) findViewById(R.id.list);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://abc.com/default.aspx?id=G" });
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
int sub = result.lastIndexOf('#', result.length() - 1);
String s1 = result.substring(0, sub + 2);
String temp[];
String subarr[] = new String[100];
;
Log.v("data = ", s1);
// String s = s1.replace(";", " - ");
final String arr[] = s1.split("#");
for (int i = 0; i < arr.length; i++) {
Log.v("arr" + i, arr[i] + " " + arr.length);
}
for (int i = 0; i < arr.length - 1; i++)
{
temp = arr[i].split(";");
subarr[(4 * i)] = temp[0];
subarr[(4 * i) + 1] = temp[1];
subarr[(4 * i) + 2] = temp[2];
subarr[(4 * i) + 3] = temp[3];
}
lv.setAdapter(new MyAdapter(ReadWebpageAsyncTask.this, subarr));
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:id="#+id/ed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search">
</EditText>
<ListView android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
MyAdapter.java
public class MyAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private String item1, item2, item3, item0;
int x = 0, i = 1, y = 1;
public MyAdapter(Context context, String[] values) {
super(context, R.layout.row, values);
this.context = context;
this.values = values;
}
#Override
public String getItem(int position) {
return values[position];
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.row, parent, false);
TextView tv1 = (TextView) rowView.findViewById(R.id.col1);
TextView tv2 = (TextView) rowView.findViewById(R.id.col2);
TextView tv3 = (TextView) rowView.findViewById(R.id.col3);
TextView tv4 = (TextView) rowView.findViewById(R.id.col4);
if (y < 8) {
item0 = getItem(position);
Log.v("pos = ", "" + position);
item1 = getItem(position + 1);
item2 = getItem(position + 2);
item3 = getItem(position + 3);
tv1.setText(item0);
tv2.setText(item1);
tv3.setText(item2);
tv4.setText(item3);
} else {
Log.v("y= ", "" + y);
}
return rowView;
}
}
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView android:id="#+id/col1"
android:layout_width="150dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/col2"
android:layout_width="70dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/col3"
android:layout_width="70dip"
android:layout_height="wrap_content"/>
<TextView android:id="#+id/col4"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
ANY HELP APPRICIATED
Try using ListView
Instead of TableLayout add ListView to your xml and place the content on table in new xml
Create an adapter by extending ArrayAdapter and set this adapter on your listView.
Don't add the views in your Java code, as they are added based on your XML file. It looks to me like your Java code is duplicating what you did in XML which is very precarious...
I don't see why you can't just remove the Java code and use setContentView to use the XML layout you defined.
Set the width to 0, and add weight as 1 for all the testviews, it will evenly assign space for every item in the row.
textView1.setWidth(0);
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));