I had query title column from database and want to set it in TextView in GridView.
How?
CafeDatasource
public List<Model_Insert> findTblCafe(){
List<Model_Insert> model_Inserts = new ArrayList<Model_Insert>();
Cursor cursor = database.query(CafeDbOpenHelper.TABLE_CAFE, rtv_tbl_Cafe,
null, null, null, null, null);
Log.i("number", "return" + cursor.getCount()+ " rows");
if(cursor.getCount() > 0){
while (cursor.moveToNext()) {
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ID)));
model_Insert.setCafe_Title(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_TITLE)));
model_Insert.setCafe_Been(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_BEEN)));
model_Insert.setCafe_Want(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WANT)));
model_Insert.setCafe_Address(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ADDRESS)));
model_Insert.setCafe_Thumb(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_THUMB)));
model_Insert.setCafe_Description(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_DESCRIPTION)));
model_Insert.setCafe_WifiRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WIFI_RATE)));
model_Insert.setCafe_CoffeeRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_COFFEE_RATE)));
model_Insert.setCafe_Latitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LATITUDE)));
model_Insert.setCafe_Longitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LONGITUDE)));
model_Inserts.add(model_Insert);
}
}
return model_Inserts;
}
MainActivity
public ArrayList<HashMap<String, String>> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
===============================================================
dataSource = new CafeDataSource(this);
dataSource.open();
List<Model_Insert> model_Inserts = dataSource.findTblCafe();// query database (findTblCafe)
if(model_Inserts.size() == 0){
new DownloadImageTask().execute();
model_Inserts = dataSource.findTblCafe();
}
===============================================================
} // End onCreate
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList));
}
public class DownloadImageTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
placeList = new ArrayList<HashMap<String,String>>();
JSONParser jParser = new JSONParser();
JSONObject jsonO = jParser.getJSONUrl(url);
try {
places = jsonO.getJSONArray("place");
for (int i = 0; i < places.length(); i++) {
JSONObject jobj = places.getJSONObject(i);
int cafe_id = jobj.getInt(TAG_CAFE_ID);
String cafe_title = jobj.getString(TAG_CAFE_TITLE);
int cafe_been = jobj.getInt(TAG_CAFE_BEEN);
int cafe_want = jobj.getInt(TAG_CAFE_WANT);
String cafe_address = jobj.getString(TAG_CAFE_ADDRESS);
String cafe_thumb = jobj.getString(TAG_CAFE_THUMB);
String cafe_description = jobj.getString(TAG_CAFE_DESCRIPTION);
int cafe_wifi_rate = jobj.getInt(TAG_CAFE_WIFI_RATE);
int cafe_coffee_rate = jobj.getInt(TAG_CAFE_COFFEE_RATE);
double cafe_latitude = jobj.getDouble(TAG_CAFE_LATITUDE);
double cafe_longitude = jobj.getDouble(TAG_CAFE_LONGITUDE);
// Table Save
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert = dataSource.createTableCafeSave(model_Insert);
Log.i("data", " ID " + model_Insert.getCafe_Id());
// Table Cafe
model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Title(cafe_title);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert.setCafe_Address(cafe_address);
model_Insert.setCafe_Thumb(cafe_thumb);
model_Insert.setCafe_Description(cafe_description);
model_Insert.setCafe_WifiRate(cafe_wifi_rate);
model_Insert.setCafe_CoffeeRate(cafe_coffee_rate);
model_Insert.setCafe_Latitude(cafe_latitude);
model_Insert.setCafe_Longitude(cafe_longitude);
model_Insert = dataSource.createTableCafe(model_Insert);
Log.i("data", " Picture " + model_Insert.getCafe_Id());
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CAFE_TITLE, cafe_title);
placeList.add(map);
}
// for " piture " Object in json
pictures = jsonO.getJSONArray("pictures");
for (int i = 0; i < pictures.length(); i++) {
JSONObject jObj = pictures.getJSONObject(i);
int cafe_id = jObj.getInt(TAG_CAFE_ID);
String picture_url = jObj.getString(TAG_PICTURE_URL);
// Table Picture
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setPitureUrl(picture_url);
model_Insert = dataSource.createTablePicture(model_Insert);
Log.i("pic", " Picture " + model_Insert.getPitureurl());
HashMap<String, String> map = new HashMap<String, String>();
placeList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
}
}
private static class ViewHolder {
public ImageView imageview;
public TextView txtTitle;
}
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String,String>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, String>> myArrayList){
context = c;
MyArr = myArrayList;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View converView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(converView == null){
converView = inflater.inflate(R.layout.grid_item, null);
}
viewHolder.imageview = (ImageView) converView.findViewById(R.id.imv_card_cafe);
viewHolder.txtTitle = (TextView) converView.findViewById(R.id.txt_title);
/* String str = "frute : juse text";
Integer len;
len = str.length();
if(len > 20){
String result = str.substring(0, 15);
viewHolder.txtTitle.setText(result);
}
else {
viewHolder.txtTitle.setText(str);
} */
=============================================================================
viewHolder.txtTitle.setText(...............................?);
=============================================================================
viewHolder.imageview.setImageResource(mThumb[position]);
return converView;
}
}
because you are getting all titles inside model_Inserts List you will need to pass this List to Custom BaseAdapter for showing in TextView as :
Change ShowAllContent() method as:
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList,model_Inserts));
}
and ImageAdapter constructor as :
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr =
new ArrayList<HashMap<String,String>>();
List<Model_Insert> model_Inserts=null;
public ImageAdapter(Context c,
ArrayList<HashMap<String, String>> myArrayList,
List<Model_Insert> model_Inserts){
context = c;
MyArr = myArrayList;
this.model_Inserts=model_Inserts;
}
///your code here...
now use model_Inserts for getting Title to show inside getView
Related
I have a problem, I keep getting an error that there is too much work being done on the mainthread. The code goes like this:
In my main activity call the helper class(UcitavanjeUpozadini) to load the data in background.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//String link = getResources().getString(R.string.blogLink);
//Uri uri = Uri.parse(link); // missing 'http://' will cause crashed
//Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//startActivity(intent);
List<View> listaView = new ArrayList<View>();
int[] idView = {R.layout.fragment_first_apartment, R.layout.fragment_second_apartment, R.layout.fragment_third_apartment, R.layout.fragment_fourth_apartment};
for(int i = 0; i < idView.length; i++)
{
View view = getLayoutInflater().inflate(idView[i], null);
listaView.add(view);
}
UcitavanjeUpozadini ucitavanje = new UcitavanjeUpozadini(this, listaView);
ucitavanje.execute();
}
I also inflate the fragments i am going to use later to populate the data i get.
Then all of my code is done in the doInBackground part of the class.
Any help is welcome.
public class UcitavanjeUpozadini extends AsyncTask<Void, Void, Void> {
private Context context;
private List<OglasHelper> lista;
private List<TypedArray> listaId;
private List<View> views;
private ProgressDialog progressDialog;
public UcitavanjeUpozadini(Context context, List<View> views){
this.context = context;
this.lista = new ArrayList<OglasHelper>();
this.listaId = new ArrayList<TypedArray>();
this.views = views;
this.progressDialog = null;
}
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(context, "",
"Loading...");
}
#Override
protected Void doInBackground(Void... params) {
UcitavanjeHelperKlasa ucitavanjeHelperKlasa = new UcitavanjeHelperKlasa();
String jsonString = ucitavanjeHelperKlasa.vratiJsonFajl(context, R.raw.source);
lista = ucitavanjeHelperKlasa.vratiSveOglase(jsonString);
int[] idEviArraya = {R.array.prviOglas, R.array.drugiOglas, R.array.treciOglas, R.array.cetvrtiOglas};
for (int i = 0; i < idEviArraya.length; i++)
{
TypedArray oglas = context.getResources().obtainTypedArray(idEviArraya[i]);
listaId.add(oglas);
}
napuniOglasePodacima();
return null;
}
#Override
protected void onPostExecute() {
progressDialog.dismiss();
}
public void napuniOglasePodacima(){
for(int i = 0; i < lista.size(); i++)
{
View view = (View) views.get(i);
TypedArray array = listaId.get(i);
Log.v("broj podataka u array-u", String.valueOf(array.getIndexCount()));
if(array.getIndexCount() == 7)
{
fillApartment(array, lista.get(i), view);
}
else if(array.getIndexCount() == 9)
{
fillApartment(array, lista.get(i), view);
TextView description = (TextView) view.findViewById(array.getIndex(7));
String sredjenOpis = lista.get(i).getDescription().substring(0, array.getIndex(8)) + "...";
description.setText(sredjenOpis);
}
}
}
public void fillApartment(TypedArray array, OglasHelper oglasHelper, View view)
{
ImageView borderTop = (ImageView) view.findViewById(array.getIndex(0));
ImageView dugme = (ImageView) view.findViewById(array.getIndex(1));
TextView rentBuy = (TextView) view.findViewById(array.getIndex(2));
TextView currency = (TextView) view.findViewById(array.getIndex(3));
TextView price = (TextView) view.findViewById(array.getIndex(4));
TextView name = (TextView) view.findViewById(array.getIndex(5));
TextView address = (TextView) view.findViewById(array.getIndex(6));
int broj = array.getIndex(0);
String string = String.valueOf(broj);
Log.v("Ovo je testiranje", string);
borderTop.setBackgroundColor(Color.parseColor(oglasHelper.getColor()));
String rentBuyString = oglasHelper.getRentBuy();
if(rentBuyString.equals("RENT"))
{
dugme.setImageResource(R.drawable.dugme_rent);
}
else if(rentBuyString.equals("BUY"))
{
dugme.setImageResource(R.drawable.dugme_buy);
}
rentBuy.setText(rentBuyString);
rentBuy.setTextColor(Color.parseColor(oglasHelper.getColor()));
currency.setText(oglasHelper.getCurrency());
String sredjenaCena = NumberFormat.getNumberInstance(Locale.GERMANY).format(oglasHelper.getPrice());
price.setText(sredjenaCena);
name.setText(oglasHelper.getName());
String[] poljaAdrese = {oglasHelper.getStreet() ,oglasHelper.getCity(), oglasHelper.getNeighbourhood(), oglasHelper.getZipcode()};
String sredjenaAdresa = "";
for(int i = 0; i < poljaAdrese.length; i++)
{
if(i == 3)
{
sredjenaAdresa = sredjenaAdresa.substring(0, -1) + ", " + poljaAdrese[i];
}
else if(!poljaAdrese[i].equals(""))
{
sredjenaAdresa += poljaAdrese[i] + " ";
}
}
address.setText(sredjenaAdresa);
}
}
its my following code.
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;
#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);
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;
//Toast.makeText(getApplicationContext(), productID[j] + "" + ProductName[j] + "" + ProductPrice[j] + "" + ProductQuantity[j] + "" + ProductModel[j] + "" + ProductImage[j] + "" + ProductManufacturer[j], Toast.LENGTH_SHORT).show();
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));
getListViewSize(ListCart);
String s1 = ProductPrice.toString();
}
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
if (listItem != null) {
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
if (params != null) {
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
}
myListView.requestLayout();
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
}
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();
}
}
}
}
listview is working properly
i just inflate cardview in listview.
when using this code image cannot displaying. only dispaly last image in list view
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter
.getCount() - 1));
my problem is: In listview only displaying last image
check this image:
Try adding your ImageView to Holder class and use like viewholder.img.setImageBitmap(new LoadImage().execute(urll)) and change the return type to Bitmap
Use BaseAdapter instead of ArrayAdapter. Load and show image with UIL, Picasso or other image loader library.
public class ImageAdapter extends BaseAdapter {
private List<ImageBean> list;
private ArrayList<ImageBean> arraylist;
private LayoutInflater inflater;
public ImageAdapter(Context context, List<ImageBean> list) {
this.list = list;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<>();
}
#Override
public int getCount() {
return list.size();
}
#Override
public ImageBean getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.recycler_view_item, parent, false);
holder.ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Loading image with UIL example
ImageLoader.getInstance().displayImage(getItem(position).getUrl(), holder.ivImage, ImageUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS);
return convertView;
}
private class ViewHolder {
public ImageView ivImage;
}
}
I am using AyncTask to get data from server and set it to listview .
For notifying the changes to the listview I am calling mAdapter.notifyDataSetChanged(); in onPostExecute() method
I am using Pull to refresh listview library
Still I am getting IllegalStateException
listView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int count = Integer.parseInt(index_temp)+6;
System.out.println("Checking "+ listView.getLastVisiblePosition());
System.out.println("----->Checking loadmore:"+ load_more);
System.out.println("----->Checking actual:"+ count);
if (listView.getLastVisiblePosition()+1 == count) {
if(load_more==1){
index_temp = String.valueOf(Integer.parseInt(icount) + Integer.parseInt(index_temp));
new GetList_ontouch().execute(index_temp);
}
}
}
});
GetList_ontouch
private class GetList_ontouch extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar1.setVisibility(0);
}
#Override
protected Void doInBackground(String... params) {
if (NetworkCheck.isNetworkAvailable(getActivity()) == true) {
Log.d("index count for array", params[0]);
if(Integer.parseInt(params[0])==0){
Log.d("index count for array","Reached");
newsList = new ArrayList<HashMap<String, String>>();
}
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(All_link.HOME_DATA_URL + "/"+params[0]+"/"+ icount,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
news = jsonObj.getJSONArray(All_link.TAG_NEWS);
String err = jsonObj.getString(All_link.TAG_ERROR);
String more = jsonObj.getString(All_link.TAG_MORE);
Log.e("------>Error",String.valueOf(err));
Log.e("------>More",String.valueOf(more));
if(more.equals("0")){
load_more = 0;
}else{
load_more = 1;
}
// looping through All Contacts
for (int i = 0; i < news.length(); i++) {
JSONObject segments_list = news.getJSONObject(i);
for (int plates_count = 0; plates_count < segments_list
.length(); plates_count++) {
String plates = "";
if (plates_count == 3) {
plates = String.valueOf("banner_image");
JSONObject segments_plates = segments_list
.getJSONObject(plates);
//String flag = "banner_image";
String id = segments_plates
.getString(All_link.TAG_BANNER_ID);
String banner_no = segments_plates
.getString(All_link.TAG_BANNER_NO);
String banner_image;
if(segments_plates.getString(All_link.TAG_BANNER_THUMB_URL)==""){
banner_image = All_link.TAG_NO_IMAGE;
}else{
banner_image = segments_plates.getString(All_link.TAG_BANNER_THUMB_URL);
}
String banner_status = segments_plates
.getString(All_link.TAG_BANNER_STATUS);
// tmp hashmap for single news
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_BANNER_ID, id);
news_hashmap.put(All_link.TAG_BANNER_NO,
banner_no);
news_hashmap.put(All_link.TAG_BANNER_THUMB_URL,
banner_image);
news_hashmap.put(All_link.TAG_BANNER_STATUS,
banner_status);
/*news_hashmap
.put(All_link.TAG_BANNER_FLAG, flag);*/
// adding contact to contact list
//newsList.add(news_hashmap);
addSeparatorItem();
} else {
plates = String.valueOf(plates_count + 1);
JSONObject segments_plates = segments_list
.getJSONObject(plates);
if(segments_plates.getString(All_link.TAG_NEWS_TYPE).equals("2")){
//type_of_news = segments_plates.getString(All_link.TAG_NEWS_TYPE);
addSeparatorItem_for_live();
}
String id = segments_plates
.getString(All_link.TAG_ID);
String news_title = segments_plates
.getString(All_link.TAG_NEWS_TITLE);
String news_desc = segments_plates
.getString(All_link.TAG_DESC);
String segment = segments_plates
.getString(All_link.TAG_SEGMENT);
String plate = segments_plates
.getString(All_link.TAG_PLATE);
String img ="";
if(segments_plates.getString(All_link.TAG_THUMB_URL).equals("")){
img = All_link.TAG_NO_IMAGE;
}else{
img = segments_plates.getString(All_link.TAG_THUMB_URL);
}
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_ID, id);
news_hashmap.put(All_link.TAG_NEWS_TITLE, news_title);
news_hashmap.put(All_link.TAG_DESC, news_desc);
news_hashmap.put(All_link.TAG_SEGMENT, segment);
news_hashmap.put(All_link.TAG_PLATE, plate);
news_hashmap.put(All_link.TAG_THUMB_URL, img);
//news_hashmap.put(All_link.TAG_BANNER_FLAG, flag);
// adding contact to contact list
newsList.add(news_hashmap);
int val = 0;
int val2 = 1;
val = (Integer.parseInt(segment)%2)==0 ? val:val2;
if((Integer.parseInt(segment)%2)!=0){
Log.e("--->CHECKING ODD EVEN", String.valueOf(val));
addSeparatorItem();
addSeparatorItem_for_alternate();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} else {
Log.e("Network Error", "Internet Connection Error");
error_flag = 1;
Log.e("error", "kareeScroll error_flag = 1");
// error = "Internet Connection Error";
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(error_flag==1){
/*listView.setVisibility(8);
main_error.setText("Internet Connection Error! Please check your network settings and try again");
main_error.setVisibility(0);*/
String jsonStr_temp=sharedPrefs.getString("jsonStr", "");
if (jsonStr_temp=="") {
listView.setVisibility(8);
main_error.setText("Internet Connection Error! Please check your network settings and try again");
main_error.setVisibility(0);
img_error.setVisibility(0);
}
else{
//newsList=null;
new GetList_refresh().execute(index_th,jsonStr_temp);
//newsList = new ArrayList<HashMap<String, String>>();
}
}
else{
listView.setVisibility(0);
main_error.setText("");
main_error.setVisibility(8);
int currentPosition = listView.getFirstVisiblePosition();
mAdapter = new MyCustomAdapter(getActivity(), newsList);
//testing
listView.setAdapter(mAdapter);
//refreshable_listView.setAdapter(mAdapter);
// Setting new scroll position
listView.setSelection(currentPosition);
//mAdapter.notifyDataSetChanged();
}
// Dismiss the progress dialog
progressBar1.setVisibility(8);
}
}
GetList_refresh // called when no network .This shows data got from local variable
private class GetList_refresh extends AsyncTask<String, String, Void> {
Dialog dialog = new Dialog(getActivity());
String jsonStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout._wait_dialog);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
}
#Override
protected Void doInBackground(String... params) {
//if (NetworkCheck.isNetworkAvailable(getActivity()) == true) {
//Log.d("index count for array", params[0]);
//if(Integer.parseInt(params[0])==0){
//Log.d("index count for array","Rweached");
//newsList = new ArrayList<HashMap<String, String>>();
//}
jsonStr=params[1];
Log.e("json","karjson "+jsonStr);
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
//jsonStr = sh.makeServiceCall(All_link.HOME_DATA_URL + "/"+params[0]+"/"+ icount,
//ServiceHandler.GET);
editor.putString("jsonStr", jsonStr);
editor.commit();
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
news = jsonObj.getJSONArray(All_link.TAG_NEWS);
err = jsonObj.getString(All_link.TAG_ERROR);
String more = jsonObj.getString(All_link.TAG_MORE);
Log.e("------>Error",String.valueOf(err));
Log.e("------>More",String.valueOf(more));
if(more.equals("0")){
load_more = 0;
}else{
load_more = 1;
}
// looping through All Contacts
for (int i = 0; i < news.length(); i++) {
//karthik
JSONObject segments_list = news.getJSONObject(i);
for (int plates_count = 0; plates_count < segments_list
.length(); plates_count++) {
String plates = "";
if (plates_count == 3) {
plates = String.valueOf("banner_image");
JSONObject segments_plates = segments_list
.getJSONObject(plates);
//String flag = "banner_image";
String id = segments_plates
.getString(All_link.TAG_BANNER_ID);
String banner_no = segments_plates
.getString(All_link.TAG_BANNER_NO);
String banner_image;
if(segments_plates.getString(All_link.TAG_BANNER_THUMB_URL)==""){
banner_image = All_link.TAG_NO_IMAGE;
}else{
banner_image = segments_plates.getString(All_link.TAG_BANNER_THUMB_URL);
}
String banner_status = segments_plates
.getString(All_link.TAG_BANNER_STATUS);
// tmp hashmap for single news
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_BANNER_ID, id);
news_hashmap.put(All_link.TAG_BANNER_NO,
banner_no);
news_hashmap.put(All_link.TAG_BANNER_THUMB_URL,
banner_image);
news_hashmap.put(All_link.TAG_BANNER_STATUS,
banner_status);
/*news_hashmap
.put(All_link.TAG_BANNER_FLAG, flag);*/
// adding contact to contact list
newsList.add(news_hashmap);
//karthik newsList
//Local_newsList.add(news_hashmap);
addSeparatorItem();
} else {
plates = String.valueOf(plates_count + 1);
JSONObject segments_plates = segments_list
.getJSONObject(plates);
if(segments_plates.getString(All_link.TAG_NEWS_TYPE).equals("2")){
//type_of_news = segments_plates.getString(All_link.TAG_NEWS_TYPE);
addSeparatorItem_for_live();
}
String id = segments_plates.getString(All_link.TAG_ID);
String news_title = segments_plates.getString(All_link.TAG_NEWS_TITLE);
String news_desc = segments_plates.getString(All_link.TAG_DESC);
String segment = segments_plates.getString(All_link.TAG_SEGMENT);
String plate = segments_plates.getString(All_link.TAG_PLATE);
String img ="";
if(segments_plates.getString(All_link.TAG_THUMB_URL).equals("")){
img = All_link.TAG_NO_IMAGE;
}else{
img = segments_plates.getString(All_link.TAG_THUMB_URL);
}
HashMap<String, String> news_hashmap = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
news_hashmap.put(All_link.TAG_ID, id);
news_hashmap.put(All_link.TAG_NEWS_TITLE, news_title);
news_hashmap.put(All_link.TAG_DESC, news_desc);
news_hashmap.put(All_link.TAG_SEGMENT, segment);
news_hashmap.put(All_link.TAG_PLATE, plate);
news_hashmap.put(All_link.TAG_THUMB_URL, img);
//news_hashmap.put(All_link.TAG_BANNER_FLAG, flag);
// adding contact to contact list
newsList.add(news_hashmap);
//karthik newsList
//Local_newsList.add(news_hashmap);
int val = 0;
int val2 = 1;
val = (Integer.parseInt(segment)%2)==0 ? val:val2;
if((Integer.parseInt(segment)%2)!=0){
Log.e("--->CHECKING ODD EVEN", String.valueOf(val));
addSeparatorItem();
addSeparatorItem_for_alternate();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
mAdapter.notifyDataSetChanged();
refreshable_listView.invalidate();
refreshable_listView.requestLayout();
refreshable_listView.onRefreshComplete();
super.onPostExecute(result);
// Dismiss the progress dialog
if (dialog.isShowing()){
dialog.dismiss();
}
/*SharedPreferences sharedPrefs = getActivity().getSharedPreferences(All_link.MyPREFERENCES,
Context.MODE_PRIVATE);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());*/
//For Breaking News Setting
if (sharedPrefs.getInt("prefswtch4", 1) == 1) {
if (All_link.GLOBAL_BREAKING_FLAG == 0) {
new getBreakingNews().execute();
}
}
//For Location Setting
if (sharedPrefs.getInt("prefswtch1", 1) == 1) {
} else {
}
//For Ticker Setting
if (sharedPrefs.getInt("prefswtch2", 1) == 1) {
new getTicker().execute();
} else {
marque.setVisibility(8);
}
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
refreshable_listView.onRefreshComplete();
}
}
OnCreateView ...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sharedPrefs = getActivity().getSharedPreferences(All_link.MyPREFERENCES,
Context.MODE_PRIVATE);
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
editor=sharedPrefs.edit();
View rootView = inflater.inflate(R.layout.listview_layout, container,false);
View footer_image=inflater.inflate(R.layout.listview_image_footer, null,false);
//footer_image.setClickable(false);
/* get theme webservice*/
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
userFunction=new UserFunctions();
//Breaking News Section
slide = AnimationUtils.loadAnimation(getActivity(), R.anim.slidedown);
fadeOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fadeout);
pan_breaking_new = (LinearLayout)rootView.findViewById(R.id.pan_breaking_new);
//pan_breaking_new.setOnClickListener(this);
pan_breaking_new.setVisibility(8);
btn_close= (ImageView) rootView.findViewById(R.id.btn_close);
btn_close.setOnClickListener(this);
img_share= (ImageView) rootView.findViewById(R.id.img_share);
img_share.setOnClickListener(this);
//END Breaking News Section
//Ticker
marque = (ScrollingTextView)rootView.findViewById(R.id.txtTicker);
marque.setVisibility(8);
//END ticker
main_error = (TextView) rootView.findViewById(R.id.main_error);
main_error.setText("Loading...");
img_error = (ImageView) rootView.findViewById(R.id.img_error);
img_error.setOnClickListener(this);
progressBar1 = (ProgressBar) rootView.findViewById(R.id.progressBar1);
progressBar1.setVisibility(8);
//karthik
refreshable_listView = (PullToRefreshListView) rootView.findViewById(R.id.listView);
listView=refreshable_listView.getRefreshableView();
listView.addFooterView(footer_image, null, false);
refreshable_listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// TODO Auto-generated method stub
listView=refreshable_listView.getRefreshableView();
try {
getTheme();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new GetList().execute(index_th);
}
});
newsList = new ArrayList<HashMap<String, String>>();
mAdapter = new MyCustomAdapter(getActivity(), newsList);
refreshable_listView.setAdapter(mAdapter);
//listView.addHeaderView(pan_breaking_new);
mSeparatorsSet = new TreeSet<Integer>();
mSeparatorsSet_alternate_layout = new TreeSet<Integer>();
mSeparatorsSet_live_layout = new TreeSet<Integer>();
new GetList_with_dialog().execute(index_th); // same as GetList(), but displays dialog
return rootView;
}
MyCursorAdapter
private class MyCustomAdapter extends BaseAdapter {
private Activity activity;
Boolean result;
private final LayoutInflater inflater = null;
public ImageLoader imageLoader;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_SEPARATOR_ALTERNATE = 2;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 3;
private int live_type = 0;
private LayoutInflater mInflater;
public MyCustomAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
mInflater = (LayoutInflater) a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
activity = a;
//newsList=d;
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getItemViewType(int position) {
int separtorValue;
int pos = mSeparatorsSet.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
live_type = mSeparatorsSet_live_layout.contains(position) ? TYPE_SEPARATOR: TYPE_ITEM;
if(pos==1){
//Log.e("--->if called- position->", String.valueOf(position));
if(mSeparatorsSet_alternate_layout.contains(position)){
//Log.e("--->if called-->", String.valueOf(position));
separtorValue = 2;
}else{
separtorValue = 1;
}
}else{
separtorValue = 0;
}
return separtorValue;
}
#Override
public int getViewTypeCount() {
Log.e("--->TYPE_MAX_COUNT called-->", String.valueOf(TYPE_MAX_COUNT));
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return newsList.size();
}
#Override
public HashMap<String, String> getItem(int position) {
return newsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NewsViewHolder holder = null;
int type = getItemViewType(position);
Log.e("--->SHISHIR-->", String.valueOf(live_type));
/*System.out.println("getView " + position + " " + convertView
+ " type = " + type);
**/
//Log.e("--->SHISHIR-->", String.valueOf(position) + " -->live"+String.valueOf(mSeparatorsSet_live_layout.first()));
if (convertView == null) {
holder = new NewsViewHolder();
//Log.e("--itempostion", String.valueOf(getItem(type)));
switch (type) {
case TYPE_ITEM:
if (CURRENT_THEME==1) {
convertView = mInflater.inflate(
R.layout.theme_one_row_small, null);
}
else{
convertView = mInflater.inflate(
R.layout.theme_one_row_small_new, null);
}
holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.live = (TextView) convertView.findViewById(R.id.live);
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
imageLoader
.DisplayImage(
com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(
All_link.TAG_THUMB_URL),
holder.img);
break;
case TYPE_SEPARATOR_ALTERNATE:
if (CURRENT_THEME==1) {
convertView = mInflater
.inflate(R.layout.theme_one_row_big, null);
}
else{
convertView = mInflater
.inflate(R.layout.theme_one_row_big_new, null);
}
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.img_flag = (ImageView) convertView.findViewById(R.id.img_live_flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.live = (TextView) convertView.findViewById(R.id.live);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
break;
case TYPE_SEPARATOR:
convertView = mInflater
.inflate(R.layout.theme_banner, null);
holder.flag = (TextView) convertView.findViewById(R.id.flag);
holder.id = (TextView) convertView.findViewById(R.id.fid);
holder.name = (TextView) convertView
.findViewById(R.id.title);
holder.img = (ImageView) convertView
.findViewById(R.id.list_image);
break;
}
convertView.setTag(holder);
} else {
holder = (NewsViewHolder) convertView.getTag();
}
switch (type) {
case TYPE_ITEM:
if(live_type == 1){
holder.img_flag.setVisibility(0);
holder.live.setText("live");
}else{
holder.live.setText("not_live");
holder.img_flag.setVisibility(8);
}
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_ID)));
holder.flag.setText("normal");
break;
case TYPE_SEPARATOR_ALTERNATE:
if(live_type == 1){
holder.img_flag.setVisibility(0);
holder.live.setText("live");
//Log.e("--itempostion Live", "live");
}else{
holder.live.setText("not_live");
holder.img_flag.setVisibility(8);
}
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_ID)));
holder.flag.setText("normal");
Log.e("karthik", "karthik "+com.rb.library.All_link.IMAGE_URI+ newsList.get(position).get(All_link.TAG_THUMB_URL));
break;
case TYPE_SEPARATOR:
Log.e("--banner Images", com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
imageLoader.DisplayImage(com.rb.library.All_link.IMAGE_URI_BANNER
+ newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL),
holder.img);
holder.id.setText(String.valueOf(newsList.get(position).get(
All_link.TAG_BANNER_ID)));
holder.flag.setText(newsList.get(position).get(All_link.TAG_BANNER_THUMB_URL));
break;
}
holder.name.setText(String.valueOf(newsList.get(position).get(All_link.TAG_NEWS_TITLE)));
return convertView;
}
}
You shouldn't call in doInBackground() any method that updates the list.You should collect everything in doInBackground, return it as a result and then update the list in onPostExecute.
because onPostExecute and onProgressUpdate are executed in the UI thread, while doInBackground is executed in a different Thread.
Don't recreate your adapter each time doInBackground is call
mAdapter = new MyCustomAdapter(getActivity(), newsList);
listView.setAdapter(mAdapter);
Create it once and for all somewhere relevant.
mAdapter = new MyCustomAdapter(getActivity(), new ArrayList<HashMap<String, String>>());
listView.setAdapter(mAdapter);
And then return the List in doInBackground
return newsList;
And change onPostExecute like this, to integrate results in the adapter. onPostExecute runs in UI thread and has been designed to handle that kind of operation, like updating an adapter.
#Override
protected void onPostExecute(List<HashMap<String, String>> result)
{
// Assuming here MyCustomAdapter is an ArrayAdapter
mAdapter.clear();
mAdapter.addAll(result);
mAdapter.notifyDataSetChanged();
// [...]
}
The AsyncTask would look like this :
private class GetList_refresh extends AsyncTask<String, String, List<HashMap<String, String>>>
I'm working on a chat app. I want to create a cool design for my listview. My code is working but I want to add some design similar to the design of Facebook, but I have a problem.
I can't do this: i.e one user has an ID=52 and the other has=5293. If the user has Id=52, the textarea gravity in the left and the other in the right, and here my code it doesn't see my if statement every time print the else statement I don't know why really I put my ID in an array but really this is the same result.
public void LoadMessage() {
// TODO Auto-generated method stub
DatabseHandler d = new DatabseHandler(EchangingMessage.this);
String me = d.getData();
TextView you_id = (TextView) findViewById(R.id.you_id);
String you = you_id.getText().toString().trim();
Log.i("ID :", me + " : " + you);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("me", me));
params.add(new BasicNameValuePair("you", you));
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "POST",
params);
try {
int success = json.getInt(TAG_SUCCESS);
Log.i("success :", "" + success);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = "http://10.0.2.2/www/Android_Login_Secure/Images/upload/big/"
+ c.getString(TAG_LINK_IMAGE_RS);
String message_rs = c.getString(TAG_MESSAGE_RS);
String time_rs = c.getString(TAG_TIME_RS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_MESSAGE_RS, message_rs);
map.put(TAG_TIME_RS, time_rs);
DaftarRS.add(map);
}
} else {
finish();
}
} catch (Exception e) {
Log.e("Error", "COnnection:" + e.toString());
}
runOnUiThread(new Runnable() {
public void run() {
// updating listview
SetListViewAdapter(DaftarRS);
}
});
}
public class ListAdapterSendMessage extends BaseAdapter {
public String POST_TEXT;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public final static String you_id = null;
int count = 0;
public ListAdapterSendMessage(Activity a,
ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.item_list_send, null);
}
HashMap<String, String> daftar_rs = new HashMap<String, String>();
daftar_rs = data.get(position);
String me = daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS);
if (me == "52") {
vi = inflater.inflate(R.layout.list_row_even, null);
TextView name_rs = (TextView) vi.findViewById(R.id.senderMessage);
TextView Des_rs = (TextView) vi.findViewById(R.id.message);
ImageView thumb_image = (ImageView) vi
.findViewById(R.id.imageSender);
TextView Time_rs = (TextView) vi.findViewById(R.id.senderTime);
name_rs.setText(daftar_rs.get(MyMessages.TAG_NAMA_RS));
// link_image_rs.setText(daftar_rs.get(MainActivity.TAG_LINK_IMAGE_RS));
// alamat_rs.setText(daftar_rs.get(MainActivity.TAG_ALAMAT_RS));
Des_rs.setText(daftar_rs.get(MyMessages.TAG_MESSAGE_RS));
Time_rs.setText(daftar_rs.get(MyMessages.TAG_TIME_RS));
imageLoader.DisplayImage(
daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS), thumb_image);
} else {
vi = inflater.inflate(R.layout.list_row_odd, null);
TextView name_rs = (TextView) vi.findViewById(R.id.senderMessage);
TextView Des_rs = (TextView) vi.findViewById(R.id.message);
ImageView thumb_image = (ImageView) vi
.findViewById(R.id.imageSender);
TextView Time_rs = (TextView) vi.findViewById(R.id.senderTime);
name_rs.setText(daftar_rs.get(MyMessages.TAG_NAMA_RS));
// link_image_rs.setText(daftar_rs.get(MainActivity.TAG_LINK_IMAGE_RS));
// alamat_rs.setText(daftar_rs.get(MainActivity.TAG_ALAMAT_RS));
Des_rs.setText(daftar_rs.get(MyMessages.TAG_MESSAGE_RS));
Time_rs.setText(daftar_rs.get(MyMessages.TAG_TIME_RS));
imageLoader.DisplayImage(
daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS), thumb_image);
}
return vi;
}
}
for this question we assume that my id =1 and you id =2
if (id==1) {
inflater.inflate(R.layout.item_list_right, parent, false);
else
{
inflater.inflate(R.layout.item_list_left, parent, false);
}
here you have to different layout one of them item_list_right and the other one is item_list_left
I solved this problem like this
I have parsed json data in which there is a main json array and it contains sub json array. But the main json array not containing the sub json array in every item. So i have parsed all the data accroding to it. and i am getting perfect data from it. But the problem is that the main json array data is displaying in listview and after click on list view item the sub json array is display accroding to main json array item but its only get the last element of sub json array from hash map array list. So i can't get proper way to display so please find out some standard solution.
Here is My Code
public class MainCategories extends Fragment {
WebserviceClass wservice = new WebserviceClass();
Context c;
View v;
String data = "";
String User_id, countryid;
JSONObject jobj;
JSONArray datas;
int currentpage = 1;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// testAdapter adapter
ArrayList<Allcategories> listing = new ArrayList<Allcategories>();;
public static ArrayList<subCateData> subList = new ArrayList<subCateData>();
int limit = 3, id;
Button bt1, bt2, bt3;
String img, img1;
String name, count;
String subname, subcount, subCategoryId;
View fragmentview;
ListView lv1, lv2, lv3;
JSONObject ca;
MainTest test;
String url, main, subnameData, subCountData, subID, cateGoryID;
LinearLayout ll;
ProgressDialog pDialog;
HashMap<String, String> map;
JSONArray dataa;
// SimpleAdapter adp;
Button b1, b2, b3;
public MainCategories(Context mainActivity, int id) {
// TODO Auto-generated constructor stub
this.c = mainActivity;
this.id = id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
SharedPreferences sp = c.getSharedPreferences("key", 0);
User_id = sp.getString("userid=", User_id);
countryid = sp.getString("countryid", countryid);
v = inflater.inflate(R.layout.categories_tab, container, false);
lv2 = (ListView) v.findViewById(android.R.id.list);
if (FirstTab.adp == null) {
new CategoryTest().execute();
} else {
lv2.setAdapter(FirstTab.adp);
}
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for (int i = 0; i < subList.size(); i++) {
subID = subList.get(i).getsubcatId();
subnameData = subList.get(i).getsubcatname();
subCountData = subList.get(i).getsubcatcount();
Log.v("ALLDATA", subnameData + "/" + "/" + "/"
+ subCountData);
}
String catid = listing.get(position).getCategoryid();
int mycatID = Integer.parseInt(catid);
Log.v("CAtegory ID", mycatID + "");
addfragment(new CategoriesListClick(c, subID, mycatID,
subnameData, subCountData, position), true,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
});
return v;
}
public class CategoryTest extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url = String.format(Common.view_main_category + "country_id=%s",
countryid);
Log.v("CateGory URL:", url);
jobj = wservice.getjson(url);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jdata = jobj.getJSONObject("data");
datas = jdata.getJSONArray("allcategories");
for (int i = 0; i < datas.length(); i++) {
Log.e("length", "" + datas.length());
ca = datas.getJSONObject(i);
cateGoryID = ca.getString("categoryid");
name = ca.getString("categoryname");
count = ca.getString("categorystorecount");
// map = new HashMap<String, String>();
// map.put("categoryname", name);
// map.put("categorystorecount", "(" + count + ")");
// String countc=c.getString("categoryid");
Log.e(name, count);
if (ca.has("subcategories")) {
dataa = ca.getJSONArray("subcategories");
for (int j = 0; j < dataa.length(); j++) {
JSONObject d = dataa.getJSONObject(j);
// subList = new ArrayList<subCateData>();
subCategoryId = d.getString("subcategoryid");
subname = d.getString("subcategoryname");
subcount = d.getString("subcategorystorecount");
// map.put("subcategoryid", subCategoryId);
// map.put("subcategoryname", subname);
// map.put("subcategorystorecount", "(" + subcount
// + ")");
subList.add(new subCateData(subCategoryId, subname,
subcount));
/*
* Log.v("This is Data for Sub:",
* map.get("subcategoryname").toString());
*/
}
} else {
System.out.println("JSONArray is null");
}
listing.add(new Allcategories(cateGoryID, name, count));
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("Size", listing.size() + "");
FirstTab.adp = new MyCustom(c, listing);
lv2.setAdapter(FirstTab.adp);
}
}
void addfragment(Fragment fragment, boolean addBacktoStack, int transition) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addBacktoStack)
ft.addToBackStack(null);
ft.commit();
}
class MyCustom extends BaseAdapter {
Context Mcontext;
ArrayList<Allcategories> thisCatList;
LayoutInflater inflater;
public MyCustom(Context c, ArrayList<Allcategories> listing) {
// TODO Auto-generated constructor stub
this.Mcontext = c;
this.thisCatList = listing;
inflater = LayoutInflater.from(Mcontext);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return thisCatList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
v = inflater.inflate(R.layout.list_categories, parent, false);
TextView catName = (TextView) v.findViewById(R.id.txtcname);
TextView catCount = (TextView) v.findViewById(R.id.txtccount);
catName.setText(thisCatList.get(position).getCategoryname());
catCount.setText("(" + ""
+ thisCatList.get(position).getCategorystorecount()
+ "" + ")");
Log.v("CatCount", catCount.getText().toString());
}
// TODO Auto-generated method stub
return v;
}
}
class AllCategories Data:
public class Allcategories {
private String arabicname;
private String categoryid;
private String categoryname;
private String categorystorecount;
private String fatherid;
private String order;
private String status;
// private List subcategories;
public Allcategories(String name, String count) {
// TODO Auto-generated constructor stub
this.categoryname = name;
this.categorystorecount = count;
}
public String getCategoryname() {
return this.categoryname;
}
public void setCategoryname(String categoryname) {
this.categoryname = categoryname;
}
public String getCategorystorecount() {
return this.categorystorecount;
}
public void setCategorystorecount(String categorystorecount) {
this.categorystorecount = categorystorecount;
}
SubCategory Data Class:
public class subCateData {
String subcatId, subcategoryname, subcategorystorecount;
public subCateData(String id, String name, String count) {
// TODO Auto-generated constructor stub
this.subcatId = id;
this.subcategoryname = name;
this.subcategorystorecount = count;
}
public String getsubcatId() {
return this.subcatId;
}
public void setsubcatId(String subID) {
this.subcatId = subID;
}
public String getsubcatname() {
return this.subcategoryname;
}
public void setsubcatname(String name) {
this.subcategoryname = name;
}
public String getsubcatcount() {
return this.subcategorystorecount;
}
public void setsubcatcount(String count) {
this.subcategorystorecount = count;
}
This is My Json parsing URL:
http://www.sevenstarinfotech.com/projects/demo/okaz/API/view_categories.php?country_id=4
Stack Trace:
06-27 12:23:34.361: V/ALLDATA(8533): High School///0
06-27 12:24:02.001: I/Adreno200-EGLSUB(8533): <ConfigWindowMatch:2218>: Format RGBA_8888.
06-27 12:24:02.011: D/memalloc(8533): /dev/pmem: Mapped buffer base:0x53153000 size:1536000 offset:0 fd:74
06-27 12:24:02.041: D/memalloc(8533): /dev/pmem: Mapped buffer base:0x54048000 size:15683584 offset:14147584 fd:80
06-27 12:24:02.091: D/OpenGLRenderer(8533): Flushing caches (mode 0)
06-27 12:24:02.111: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x51b26000 size:3072000 offset:1536000
06-27 12:24:02.121: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x552a2000 size:9093120 offset:7557120
06-27 12:24:02.121: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x55b4e000 size:17219584 offset:15683584
06-27 12:24:03.081: D/CLIPBOARD(8533): Hide Clipboard dialog at Starting input: finished by someone else... !
06-27 12:24:03.141: D/OpenGLRenderer(8533): Flushing caches (mode 0)
06-27 12:24:03.141: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x53153000 size:1536000 offset:0
06-27 12:24:03.141: D/memalloc(8533): /dev/pmem: Unmapping buffer base:0x54048000 size:15683584 offset:14147584
06-27 12:24:03.441: D/OpenGLRenderer(8533): Flushing caches (mode 2)
you should have to put new HashMap inside your current HasHMap so you can get subcategories items for particular index.
see this for how to use nested HashMap? and use it in subcategories loop.
i am using ArrayList of getter setter class to bind the data. so if you can convert your code into arraylist and edit the question that will be a great..
and see below code
import java.util.ArrayList;
public class MainCategories extends Fragment {
WebserviceClass wservice = new WebserviceClass();
Context c;
View v;
String data = "";
String User_id, countryid;
JSONObject jobj;
JSONArray datas;
int currentpage = 1;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// testAdapter adapter
ArrayList<Allcategories> listing = new ArrayList<Allcategories>();;
public static ArrayList<subCateData> subList = new ArrayList<subCateData>();
int limit = 3, id;
Button bt1, bt2, bt3;
String img, img1;
String name, count;
String subname, subcount, subCategoryId;
View fragmentview;
ListView lv1, lv2, lv3;
JSONObject ca;
MainTest test;
String url, main, subnameData, subCountData, subID, cateGoryID;
LinearLayout ll;
ProgressDialog pDialog;
HashMap<String, String> map;
JSONArray dataa;
// SimpleAdapter adp;
Button b1, b2, b3;
/// sanket
ArrayList<Allcategories> list = new ArrayList<Allcategories>();
public MainCategories(Context mainActivity, int id) {
// TODO Auto-generated constructor stub
this.c = mainActivity;
this.id = id;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
SharedPreferences sp = c.getSharedPreferences("key", 0);
User_id = sp.getString("userid=", User_id);
countryid = sp.getString("countryid", countryid);
v = inflater.inflate(R.layout.categories_tab, container, false);
lv2 = (ListView) v.findViewById(android.R.id.list);
if (FirstTab.adp == null) {
new CategoryTest().execute();
} else {
lv2.setAdapter(FirstTab.adp);
}
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
for (int i = 0; i < subList.size(); i++) {
subID = list.get(position).get(i).getList().getsubcatId();
subnameData = list.get(position).get(i).getList().getsubcatname();
subCountData = list.get(position).get(i).getList().getsubcatcount();
Log.v("ALLDATA", subnameData + "/" + "/" + "/"
+ subCountData);
}
String catid = listing.get(position).getCategoryid();
int mycatID = Integer.parseInt(catid);
Log.v("CAtegory ID", mycatID + "");
addfragment(new CategoriesListClick(c, subID, mycatID,
subnameData, subCountData, position), true,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
});
return v;
}
public class CategoryTest extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
url = String.format(Common.view_main_category + "country_id=%s",
countryid);
Log.v("CateGory URL:", url);
jobj = wservice.getjson(url);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jdata = jobj.getJSONObject("data");
datas = jdata.getJSONArray("allcategories");
for (int i = 0; i < datas.length(); i++) {
// sanket
Allcategories binAll = new Allcategories();
Log.e("length", "" + datas.length());
ca = datas.getJSONObject(i);
cateGoryID = ca.getString("categoryid");
name = ca.getString("categoryname");
count = ca.getString("categorystorecount");
// map = new HashMap<String, String>();
// map.put("categoryname", name);
// map.put("categorystorecount", "(" + count + ")");
// String countc=c.getString("categoryid");
//sanket
binAll.setcategoryid(cateGoryID);
binAll.setcategoryname(name);
binAll.setcategorystorecount(count);
Log.e(name, count);
if (ca.has("subcategories")) {
dataa = ca.getJSONArray("subcategories");
for (int j = 0; j < dataa.length(); j++) {
JSONObject d = dataa.getJSONObject(j);
// subList = new ArrayList<subCateData>();
subCategoryId = d.getString("subcategoryid");
subname = d.getString("subcategoryname");
subcount = d.getString("subcategorystorecount");
// map.put("subcategoryid", subCategoryId);
// map.put("subcategoryname", subname);
// map.put("subcategorystorecount", "(" + subcount
// + ")");
//// sanket
ArrayList<subCateData> sublist = new ArrayList<subCateData>();
subCateData binSub = new subCateData();
binSub.setsubcatId(subCategoryId);
binSub.setsubcatname(subname);
binSub.setsubcatcount(subcount);
subList.add(new subCateData(subCategoryId, subname,
subcount));
/*
* Log.v("This is Data for Sub:",
* map.get("subcategoryname").toString());
*/
sublist.add(binSub);
}
/// sanket note : make arraylist of subdata in Allcategories class and generate getter and settter
binAll.setList(sublist);
} else {
System.out.println("JSONArray is null");
}
listing.add(new Allcategories(cateGoryID, name, count));
list.add(binAll);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("Size", listing.size() + "");
FirstTab.adp = new MyCustom(c, listing);
lv2.setAdapter(FirstTab.adp);
}
}
void addfragment(Fragment fragment, boolean addBacktoStack, int transition) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addBacktoStack)
ft.addToBackStack(null);
ft.commit();
}
class MyCustom extends BaseAdapter {
Context Mcontext;
ArrayList<Allcategories> thisCatList;
LayoutInflater inflater;
public MyCustom(Context c, ArrayList<Allcategories> listing) {
// TODO Auto-generated constructor stub
this.Mcontext = c;
this.thisCatList = listing;
inflater = LayoutInflater.from(Mcontext);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return thisCatList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
v = inflater.inflate(R.layout.list_categories, parent, false);
TextView catName = (TextView) v.findViewById(R.id.txtcname);
TextView catCount = (TextView) v.findViewById(R.id.txtccount);
catName.setText(thisCatList.get(position).getCategoryname());
catCount.setText("(" + ""
+ thisCatList.get(position).getCategorystorecount()
+ "" + ")");
Log.v("CatCount", catCount.getText().toString());
}
// TODO Auto-generated method stub
return v;
}
}