Using custom array adapter - android

i am learning to use custom adapter and i think i am headed to the right direction until i have problem with the super method of the constructor of class Custom Adapter. Could you identify the problem behind it ?
Before that i used Simple Adapter but i want more flexibility in controlling the layout.
Here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<!-- Name Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello This is testing"
android:id="#+id/guid"
android:visibility="gone"/>
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:text="name:"
android:textStyle="bold"
android:visibility="gone"/>
<!-- Email label -->
<TextView
android:id="#+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#acacac"
android:text="email"
android:textStyle="bold"
/>
<!-- Mobile number label -->
<TextView
android:id="#+id/mobile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:text="Mobile: "
android:textColor="#5d5d5d"
android:maxLines="1"/>
</LinearLayout>
here is my fragment class
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
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(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public 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(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
}
public View getView(int position, View convertView, ViewGroup Parent){
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
HashMap<String, String> objects = new HashMap<String, String>();
TextView thisview = (TextView) convertView.findViewById(R.id.email);
thisview.setText(objects.get(position).get(POST_TITLE));
return convertView;
}
}//
}
}

Change this line
CA = new CustomAdapter(this, R.layout.list_item, postList);
to
CA = new CustomAdapter(getActivity(), R.layout.list_item, postList);
NOTE : While you are using Fragment you should use getActivity() as a Context.
Also keep in mind that you's using HashMap<String,String> so your ArrayAdapter will be ArrayAdapter<HashMap<String, String>> instead of ArrayAdapter<String>.

You are extending ArrayAdapter<String> and passing ArrayList as constructor argument. They both have to be of the same type.
Also, you need to pass Context and not your asynctask GetNews.
You could also look at BaseAdapter where you need not pass any array as constructor argument.

To expand on Piyush's answer, you will also need to modify the CustomAdapter constructor
From this:
public CustomAdapter(GetNews context, ... ) { }
to this
public CustomAdapter(Context context, ... ) { }
This is because getActivity() will return an Activity, which is an instance of the Context class - Not an instance of GetNews

private ArrayList<HashMap<String, String>> mList;
public void setmList(ArrayList<HashMap<String, String>> mList) {
this.mList = mList;
}
public CustomAdapter(Context context, int resource) {
//something is wrong with super
super(context, resource);
}
and initialize it with setting list
CA = new CustomAdapter(getActivity, R.layout.list_item);
CA.setmList(yourlist);
don't know why the super with three parameter is not working in this case but it will surely resolve your issue

Related

how to set values in edittext as per spinner selection?

I have following response,
{
"1": {
"name": "abc",
"mobile_number": "123456789",
"address": "streetno3",
"landmark": "landmarksss",
},
"2": {
"name": "def",
"mobile_number": "123456789",
"address": "streetno3",
"landmark": "landmarksss",
},
"3": {
"name": "ghi",
"mobile_number": "23423423234",
"address": "abcdefgh",
"landmark": "usa",
},
"4": {
"name": "vvb",
"mobile_number": "55666655",
"address": "xvgghg",
"landmark": "fghgh",
},
"5": {
"name": "test",
"mobile_number": "77699231010",
"address": "pune",
"landmark": "fghgh",
}
}
I am getting all the names in spinner till here it works fine,now what im trying is by default i have abc selected, if i select test from spinner then how can i display his details in my edittexts,in short as per name selection i am trying to get and set details in edittext
Java code
class LoadAllStates extends AsyncTask<String, String, ArrayList<String>> {
private ProgressDialog pDialog;
private String test;
private String username;
private String usermobile;
private String useraddress;
private String userlandmark;
private String usercity;
private String userstate;
private String userpincode;
private String useremail;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ShippingAddress.this.getActivity());
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<String> doInBackground(
String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<String>();
dispdata= new ArrayList<String>();
String jsonStr = sh.makeServiceCall(GET_ADDRESS_DETAIL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONObject(jsonStr);
for (int i = 1; i <= jsonObj.length(); i++) {
JSONObject user = jsonObj.getJSONObject(""+i);
username= (user.has("name")) ? user.getString("name") : null;
usermobile= (user.has("mobile_number")) ? user.getString("mobile_number") : null;
useraddress= (user.has("address")) ? user.getString("address") : null;
userlandmark= (user.has("landmark")) ? user.getString("landmark") : null;
usercity= (user.has("city")) ? user.getString("city") : null;
userstate= (user.has("state")) ? user.getString("state") : null;
userpincode= (user.has("pin_code")) ? user.getString("pin_code") : null;
useremail= (user.has("email")) ? user.getString("email") : null;
if(username!=null) statedata.add(username+","+usermobile);
/* if(username!=null) dispdata.add(username);
if(usermobile!=null) dispdata.add(usermobile);*/
Log.i("inner",user.toString());
}
System.out.println("WifeBday"+statedata.size());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
pDialog.dismiss();
arrallstates = new String[statedata.size()]; // you can also use "result" array instead
for (int index = 0; index < statedata.size(); index++) {
arrallstates[index] = statedata.get(index);// or result.get(index);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adapterallstates = new ArrayAdapter<String>(
ShippingAddress.this.getActivity(),
android.R.layout.simple_spinner_dropdown_item, arrallstates);
System.out.println("adpttest"+adapterallstates);
spiner.setAdapter(adapterallstates);
spiner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
/*String abc=statedata.get(position);
System.out.println("abc"+abc);*/
edtname.setText(username);
edtmobile.setText(usermobile);
edtlandmark.setText(userlandmark);
edtemail.setText(useremail);
edtcity.setText(usercity);
edtstate.setText(userstate);
edtaddress.setText(useraddress);
edtpincode.setText(userpincode);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
}
It is better to make POJO class for this type of data, so that data can be managed easily. But if you have not taken POJO class then now you can take the spinner data from its position and split it to print in EditText.
Suppose if you get data in data string on ItemSelected in spinner you can follow the below code and print it in the edittext.
String split[]=data.split(",");
String name=split[0];
String mobile=split[1];
you have two option
1.Create the custom spinner adapter like below example
CustomAdapter.java
/***** Adapter class extends with ArrayAdapter ******/
public class CustomAdapter extends ArrayAdapter<String>{
private Activity activity;
private ArrayList data;
public Resources res;
SpinnerModel tempValues=null;
LayoutInflater inflater;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(
CustomSpinner activitySpinner,
int textViewResourceId,
ArrayList objects,
Resources resLocal
)
{
super(activitySpinner, textViewResourceId, objects);
/********** Take passed values **********/
activity = activitySpinner;
data = objects;
res = resLocal;
/*********** Layout inflator to call external xml layout () **********************/
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getDropDownView(int position, View convertView,ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
// This funtion called for each row ( Called data.size() times )
public View getCustomView(int position, View convertView, ViewGroup parent) {
/********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
View row = inflater.inflate(R.layout.spinner_rows, parent, false);
/***** Get each Model object from Arraylist ********/
tempValues = null;
tempValues = (SpinnerModel) data.get(position);
TextView label = (TextView)row.findViewById(R.id.company);
TextView sub = (TextView)row.findViewById(R.id.sub);
ImageView companyLogo = (ImageView)row.findViewById(R.id.image);
if(position==0){
// Default selected Spinner item
label.setText("Please select company");
sub.setText("");
}
else
{
// Set values for spinner each row
label.setText(tempValues.getCompanyName());
sub.setText(tempValues.getUrl());
companyLogo.setImageResource(res.getIdentifier
("com.androidexample.customspinner:drawable/"
+ tempValues.getImage(),null,null));
}
return row;
}
}
spinner_rows.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="3dip"
>
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:layout_toRightOf="#+id/image"
android:padding="3dip"
android:layout_marginTop="2dip"
android:textColor="#drawable/red"
android:textStyle="bold"
android:id="#+id/company"
android:layout_marginLeft="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_toRightOf="#+id/image"
android:padding="2dip"
android:textColor="#drawable/darkgrey"
android:layout_marginLeft="5dip"
android:id="#+id/sub"
android:layout_below="#+id/company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
SpinnerModel.java
public class SpinnerModel {
private String CompanyName="";
private String Image="";
private String Url="";
/*********** Set Methods ******************/
public void setCompanyName(String CompanyName)
{
this.CompanyName = CompanyName;
}
public void setImage(String Image)
{
this.Image = Image;
}
public void setUrl(String Url)
{
this.Url = Url;
}
/*********** Get Methods ****************/
public String getCompanyName()
{
return this.CompanyName;
}
public String getImage()
{
return this.Image;
}
public String getUrl()
{
return this.Url;
}
}
activity_custom_spinner.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:paddingTop="20dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/spinner"
android:drawSelectorOnTop="true"
android:prompt="#string/defaultText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:paddingTop="20dip"
android:paddingLeft="20dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/output"
/>
</LinearLayout>
CustomSpinner.java
public class CustomSpinner extends Activity {
/************** Intialize Variables *************/
public ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
TextView output = null;
CustomAdapter adapter;
CustomSpinner activity = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_spinner);
activity = this;
Spinner SpinnerExample = (Spinner)findViewById(R.id.spinner);
output = (TextView)findViewById(R.id.output);
// Set data in arraylist
setListData();
// Resources passed to adapter to get image
Resources res = getResources();
// Create custom adapter object ( see below CustomAdapter.java )
adapter = new CustomAdapter(activity, R.layout.spinner_rows, CustomListViewValuesArr,res);
// Set adapter to spinner
SpinnerExample.setAdapter(adapter);
// Listener called when spinner item selected
SpinnerExample.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
// your code here
// Get selected row data to show on screen
String Company = ((TextView) v.findViewById(R.id.company)).getText().toString();
String CompanyUrl = ((TextView) v.findViewById(R.id.sub)).getText().toString();
String OutputMsg = "Selected Company : \n\n"+Company+"\n"+CompanyUrl;
output.setText(OutputMsg);
Toast.makeText(
getApplicationContext(),OutputMsg, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
/****** Function to set data in ArrayList *************/
public void setListData()
{
// Now i have taken static values by loop.
// For further inhancement we can take data by webservice / json / xml;
for (int i = 0; i < 11; i++) {
final SpinnerModel sched = new SpinnerModel();
/******* Firstly take data in model object ******/
sched.setCompanyName("Company "+i);
sched.setImage("image"+i);
sched.setUrl("http:\\www."+i+".com");
/******** Take Model Object in ArrayList **********/
CustomListViewValuesArr.add(sched);
}
}
}
Create a bean type arraylist and store all detail in same order in which you are storing inside arrallstates and in onItemSelected method of spinner you always get the position and in both array list you have same position of data so now fetch data from bean type array list and then set it as you want

How to store items of multiple JSON Array and display it listview?

In my application I am using listview and I am also doing json parsing.
Now the issue is I want to set colors in my views, the color code I am getting from server.
Following is my json response and java code can any one help me, to set color codes in my views?
[
{
"id_product": "1445",
"name": "Stylish Sleeveless Leather Vest",
"price": 1990,
"discount": 199,
"colors": [
"#000000",
"#7E3517",
"#C85A17"
],
"sizes": [
"Medium",
"Large",
"Small"
],
"img_url": "",
"popup_images": [
]
},
{
"id_product": "1427",
"name": "Stylish Slim Fit Designed PU Leather Jacket",
"price": 3290,
"discount": 329,
"colors": [
"#000000",
"#C85A17"
],
"sizes": [
"Large",
"Medium",
"Small"
],
"img_url": "",
"popup_images": [
]
}
]
MainActivity.java
public class Product_Listing extends Fragment{
private ListView listview;
private ArrayList<HashMap<String,String>> aList;
private static String INTEREST_ACCEPT_URL = "";
// private static final String INTEREST_ACCEPT="interestaccept";
private static final String INTERESTACCEPT_USER_NAME="name";
private static final String INTEREST_ACCEPT_PRICE="price";
private static final String INTEREST_ACCEPT_PRODUCTID="id_product";
private static final String INTEREST_ACCEPT_DISCOUNT="discount";
private static final String INTEREST_ACCEPT_IMAGEURL="img_url";
private static final String INTEREST_ACCEPT_COLOR="colors";
private static final String INTEREST_ACCEPT_SIZES="sizes";
private CustomAdapterAccept adapter;
private String brandnms;
String user_img;
ArrayList<String> userImgArrayList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_listing_listivew, container, false);
Bundle bundle = this.getArguments();
brandnms = bundle.getString("Brandkeyword");
listview=(ListView)rootView.findViewById(R.id.listview_productlistings);
INTEREST_ACCEPT_URL = "";
new LoadAlbums().execute();
return rootView;
}
public class CustomAdapterAccept extends BaseAdapter{
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
String rup="\u20B9";
private static final String TAG_NAME="name";
private static final String TAG_IMAGE="img_url";
private static final String TAG_PRICE="price";
public CustomAdapterAccept(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.product_listing_items, null);
holder.propic = (ImageView) convertView.findViewById(R.id.productlist_img);
holder.txtproname = (TextView) convertView.findViewById(R.id.productlist_name);
holder.txtprice = (TextView) convertView.findViewById(R.id.productlist_price);
// holder.txtpr = (TextView) convertView.findViewById(R.id.productlist_name);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtprice.setText(listData.get(position).get(TAG_PRICE));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.meracaslogo);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
TextView txtprice;
ImageView propic;
TextView txtproname;
}
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
private ProgressDialog pDialog;
private String first;
private String sizefirst;
private JSONObject c;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(INTEREST_ACCEPT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonary = new JSONArray(jsonStr);
System.out.println("Test jsonObj"+jsonary);
// Getting JSON Array node
// interestaccept = jsonObj.getJSONArray(INTEREST_ACCEPT);
for (int i = 0; i < jsonary.length(); i++) {
c = jsonary.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(INTERESTACCEPT_USER_NAME, c.getString(INTERESTACCEPT_USER_NAME));
map.put(INTEREST_ACCEPT_PRICE,c.getString(INTEREST_ACCEPT_PRICE));
map.put(INTEREST_ACCEPT_DISCOUNT, c.getString(INTEREST_ACCEPT_DISCOUNT));
map.put(INTEREST_ACCEPT_PRODUCTID, c.getString(INTEREST_ACCEPT_PRODUCTID));
map.put(INTEREST_ACCEPT_IMAGEURL, c.getString(INTEREST_ACCEPT_IMAGEURL));
//map.put(INTEREST_ACCEPT_AGE, c.getString(INTEREST_ACCEPT_AGE)+" years");
//map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
// adding HashList to ArrayList
JSONArray colors=c.getJSONArray(INTEREST_ACCEPT_COLOR);
JSONArray sizes=c.getJSONArray(INTEREST_ACCEPT_SIZES);
user_img=c.getString(INTEREST_ACCEPT_COLOR);
// user_img=jsonObj.getString(USER_IMG);
user_img = "";
userImgArrayList = new ArrayList<String>();//declare userImgArrayList globally like ArrayList<String> userImgArrayList;
JSONArray picarray = c.getJSONArray(INTEREST_ACCEPT_COLOR);
for(int a=0;a< picarray.length();a++)
{
user_img = picarray.getString(a);
userImgArrayList.add(user_img);
}
Log.d("mylog", "curent pro pic = " + userImgArrayList);
first=userImgArrayList.get(i);
System.out.println("Color First"+first);
//first=colors.getJSONObject(a);
/* for(int j=0;j<colors.length();j++)
{
//first=colors.getJSONObject(j);
}
for(int s=0;s<sizes.length();s++)
{
sizefirst=sizes.getString(s);
}
System.out.println("Color First"+first);
System.out.println("Colors"+colors);*/
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterAccept(getActivity(),result);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
listitem
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Colors:" />
<TextView
android:id="#+id/firstcolor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
/>
<TextView
android:id="#+id/secondcolor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
/>
<TextView
android:id="#+id/thirdcolor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
/>
<TextView
android:id="#+id/fourthcolor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
/>
</LinearLayout>
Use Following code to get ArrayList of colors
ArrayList<String> colorsList = new ArrayList<>();
JsonArray jarr = new JsonArray(result);
for(int i=0;i<jarr.length;i++)
{
JsonArray color = jarr.get("colors");
String myColor="";
for(int k=0;k<color.length;k++){
myColor = color.getString(k)+",";
}
colorsList.add(myColor);
}
From this code you can get ArrayList with each object contains comma seperated colors as String.
Fill Your list adapter with this list and in your list get each color and split it by comma and use it as your background color.
Inside the adapter-> getview method inflate your view and set the following code
view.setBackgroundColor(yourColorCode);
you can take your color code from the parsed json.
EDIT:
In the getView method
getView(parameters)
{
your_current_object=objectList.get(position);
color_arraylist=your_current_object.colorsList;
if(color_arraylist.get(0)!=null)
textview1.setBackgroundColor(color_arraylist.get(0));
if(color_arraylist.get(1)!=null)
textview2.setBackgroundColor(color_arraylist.get(1));
//....so on..
}
And do appropriate type casting if color_arraylist.get(position) cant be directly passed as a parameter to setBackgroundColor(). But i hope it will work without any typecasting.
You can set listview' row color as per your JSON response below :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.product_listing_items, null);
holder.propic = (ImageView) convertView.findViewById(R.id.productlist_img);
holder.txtproname = (TextView) convertView.findViewById(R.id.productlist_name);
holder.txtprice = (TextView) convertView.findViewById(R.id.productlist_price);
// holder.txtpr = (TextView) convertView.findViewById(R.id.productlist_name);
convertView.setTag(holder);
}else{
**Add you code here for color.**
view.setBackgroundColor(listData.get(position).get(INTEREST_ACCEPT_COLOR));
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtprice.setText(listData.get(position).get(TAG_PRICE));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.meracaslogo);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
EDIT :
For showing colors to your TextView , you should first put all the colors in Hashmap and pass that hashmap to your adapter.
Now on the basis of keys you can set colors to your Textview.
HashMap<String, String> hashmap;
Method for passing Hashmap in ArrayList.
public ArrayList<HashMap<String, String>> getAllColor(String firstcolor , String second color , String thirdcolor)
{
ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();
hashmap = new HashMap<String, String>();
hashmap.put("firstcolor", firstcolor);
hashmap.put("second color",secondcolor);
hashmap.put("thirdcolor",thirdcolor);
array_list.add(hashmap);
}
return array_list;
}
Now Call this method for passing your colors. And pass your Arraylist to your ADAPTER .. And In getView() method you can retrieve it by keys like below :
**ArrayList<HashMap<String, String>> arrayList;** // declare globally
arrayList = "Your adapterList"; // declare in adapter's constructor
in getView() :
if (arrayList.size() != 0)
{
for (int i = 0; i < arrayList.size(); i++)
{
textView1.setBackgroundColor(arrayList.get(i).get("firstcolor"));
textView2.setBackgroundColor(arrayList.get(i).get("secondcolor"));
textView3.setBackgroundColor(arrayList.get(i).get("thirdcolor"));
}
}
Hope this time it will solve your problem.

Show external Image using async task

i want to call an external picture and show it in a listview.
My code works for one second and crashes giving null pointer error. The code logic is like this
1.I have called First async task to fetch Json objects from outside.
Then created a custom adapter to set that objects in custom layout.
2.second async task gets one of the object(which contains the url for the image) and returns Bitmap image.
Could you identify what i did wrong ?
Eroor: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object referenc
My Fragment class
public class NewsFragment extends Fragment{
private ProgressDialog pDialog;// Progress Dialog
String my_url;
ListView newsList;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/get_news.php";
GetNews.CustomAdapter CA;
View ImageView;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.news, container, false);
newsList = (ListView) view.findViewById(R.id.newsListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
newsList.setOnItemClickListener(new newsListClick());
return view;
}
public class newsListClick implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SinglePost singleFrag = new SinglePost();
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
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(url, ServiceHandler.GET);
Log.d("Strings","Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
int count = 1;
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
post.put("ListCount",String.valueOf(i));
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
//get the bitmap url
return null;
}
#Override
public 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(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{
private final ArrayList<HashMap<String, String>> objects;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup Parent){
//convertView = new ImageView();
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
TextView thisview = (TextView) convertView.findViewById(R.id.email);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
}else{
thisview.setText("Normal line");
}
my_url = objects.get(position).get(GUID);
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
return convertView;
}
}//
}// end async task
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}//
}
The custom layout:
?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="wrap_content"
android:background="#444444"
android:padding="10dp">
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/img"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/headertext"
android:layout_gravity="center_horizontal"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:textSize="20dp"
android:fontFamily="http://fonts.googleapis.com/css?family=Roboto:700"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/headercontent"
android:layout_gravity="center_horizontal"
android:textColor="#ffffff"
android:maxLines="2"/>
</LinearLayout>
I can suppose the following problem: you have 2 different custom layout:
R.layout.list_item_header
R.layout.list_item
And, according to your code, you are calling for both of them:
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
If the ImageView R.id.img is NOT in both these layouts, your app will crash. If I'm right, you just need to fix your if/else and invoke the DownloadImageTask only when needed.
Eroor: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference clearly says that the ImageView parameter that you are passing in the constructor is NULL.
You are initializing this graphical unit at the runtime. Why not initialize it in the beginning like
Variable_name = (ImageView) convertView.findViewById(R.id.img)
in the OnCreateView..
and pass the created object where you are currently using it. This might solve your error.
Some Tweak in the condition - and works. It was conflict in which view i wanted to set.
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}

Adding button in custom adapter class in android

Hi in my application I am parse the json url and displaying the image and text Now I am going to adding the button. if i click the button i want to move to another activity.Now My problem is if i click the button nothing happened .can any one please help me.
ListViewAdapter class:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView title;
ImageView thumb_url;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
title = (TextView) itemView.findViewById(R.id.rank);
// Locate the ImageView in listview_item.xml
thumb_url = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
title.setText(resultp.get(MainActivity.TITLE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.THUMB_URL), thumb_url);
// Capture ListView item click
Button Add = (Button) itemView.findViewById(R.id.add);
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("title", resultp.get(MainActivity.TITLE));
// Pass all data country
/*intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
*/// Pass all data flag
intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
// Start SingleItemView Class
context.startActivity(intent);
Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
}
private void startActivity(Intent in) {
// TODO Auto-generated method stub
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return context;
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
return itemView;
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
listview_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/flag"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:background="#444"
android:padding="3dp" />
<TextView
android:id="#+id/rank"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_toRightOf="#+id/flag"
android:maxLines="1"
android:textSize="15dip"
android:textStyle="bold" />
<!-- <TextView
android:id="#+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
-->
<!-- <ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:layout_toRightOf="#+id/flag"
android:padding="1dp" />
-->
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/rank"
android:text="Add" />
</RelativeLayout>
MainActivity class:
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String TITLE = "title";
/*static String COUNTRY = "country";
static String POPULATION = "population";*/
static String THUMB_URL = "thumb_url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunction
.getJSONfromURL("http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("veg_food");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobject.getString("title"));
/*map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));*/
map.put("thumb_url", jsonobject.getString("thumb_url"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Store the hashMap in the view tag.
Button Add = (Button) itemView.findViewById(R.id.add);
Add.setTag(resultp);
Then access it inside onClick() like this
instead of trying to access it by position which may not refer to the current view, access it by its tag. In your code, replace the line
resultp = data.get(position);
with
resultp = (HashMap<String, String>) view.getTag();
EDIT: After adding resultp = data.get(position); as shown above
Replace your onClick() with the following
#Override
public void onClick(View arg0) {
resultp = (HashMap<String, String>) view.getTag();
Intent intent = new Intent(context, SingleItemView.class);
intent.putExtra("title", resultp.get(MainActivity.TITLE));
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
context.startActivity(intent);
}

GetView in BaseAdapter Calling Infinte Time

In app i am loading data from Url and displaying it in list view.Total Item which I retrieve from Url is 5 Item, Which are displayed successfully in listview.But getView() runs infinite times at backend.IT keeps on calling till activity is alive .I am unable to figure it why it is calling so much time.
My code is
public class asasa extends Activity {
//ListView listView;
Intent intent;
public int currentimageindex=0;
private ProgressDialog pDialog;
//Class Declartion DataHolder
DataHolder obj;
Timer timer;
TimerTask task;
ImageView slidingimage;
private int[] IMAGE_IDS = {
R.drawable.myno, R.drawable.cock, R.drawable.item,
R.drawable.ketchup,R.drawable.oil,R.drawable.pan
};
//ProgressDialog progressDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static final String URL = "http://10.0.2.2/android_connect/get_all_products.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "name";
private static final String TAG_Description = "description";
private static final String TAG_URL = "url";
private static final String TAG_Price = "price";
LazyAdapter adapter;
// flag for Internet connection status
Boolean isInternetPresent = false;
// products JSONArray
JSONArray products = null;
// Connection detector class
ConnectionDetector cd;
String ITEMTITLE ="HasMapValue";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
LoadAllProducts il = new LoadAllProducts();
il.execute(URL);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
Toast.makeText(asasa.this, "No Internet Connection You don't have internet connection.", Toast.LENGTH_LONG).show();
}
}
public void longToast(CharSequence message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater=null;
private ArrayList<HashMap<String, Object>> data;
int i=0;
public LazyAdapter(Activity a, ArrayList<HashMap<String, Object>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
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.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
DataHolder objj=new DataHolder();
objj=(DataHolder) song.get(ITEMTITLE);
Log.i("iiiiii "," " +i++);
Log.i("objj.GetName() ",objj.GetName());
Log.i("objj.GetDescription() ",objj.GetDescription());
Log.i("objj.GetPrice() ",objj.GetPrice());
title.setText(objj.GetName());
artist.setText(objj.GetDescription());
duration.setText(objj.GetPrice());
imageview.setImageBitmap(objj.Getimage());
return vi;
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// creating new HashMap
ArrayList<HashMap<String, Object>> productsList=new ArrayList<HashMap<String,Object>>();
Bitmap decodedByte;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(asasa.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
Log.i("products ",products.toString());
// looping through All Products
Log.i("LENGTHHHH "," "+products.length());
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
Log.i("ccccccccc ",c.toString());
// Storing each json item in variable
// String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Log.i("name::",name);
String description = c.getString(TAG_Description);
Log.i("description::",description);
String price = c.getString(TAG_Price);
Log.i("price",price);
byte[] decodedString = Base64.decode(c.getString(TAG_URL), Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
obj=new DataHolder();
obj.setData(name, description, price, decodedByte);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(ITEMTITLE, obj);
productsList.add(map);
}
} else {
// no products found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
ListView list;
// dismiss the dialog after getting all products
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(asasa.this, productsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
public void onPause()
{
super.onPause();
}
public class DataHolder
{
String Name;
String Description;
String Price;
Bitmap image;
public void setData(String Name,String Descipton,String Price,Bitmap iamage)
{
this.Name=Name;
this.Description=Descipton;
this.Price=Price;
this.image=iamage;
}
public String GetName()
{return Name;}
public String GetDescription()
{return Description;}
public String GetPrice()
{return Price;}
public Bitmap Getimage()
{return image;}
}
}
And getview()
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);
HashMap<String, Object> song = new HashMap<String, Object>();
song = data.get(position);
DataHolder objj=new DataHolder();
objj=(DataHolder) song.get(ITEMTITLE);
Log.i("iiiiii "," " +i++);
Log.i("objj.GetName() ",objj.GetName());
Log.i("objj.GetDescription() ",objj.GetDescription());
Log.i("objj.GetPrice() ",objj.GetPrice());
title.setText(objj.GetName());
artist.setText(objj.GetDescription());
duration.setText(objj.GetPrice());
imageview.setImageBitmap(objj.Getimage());
return vi;
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background" >
<include layout="#layout/footer" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="460dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/background2"
android:minHeight="400dp"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/bar" >
<Button
android:id="#+id/back"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/left" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/ImageView3_Left"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginTop="20dp" >
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#drawable/textarea"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I will post the answer here for others..
When working with ListView, make sure you set a fixed height to the ListView, otherwise getView() will be called multiple times. This is because the ListView tries to calculate how many items can be visible..
and I believe I have solved the problem.
the BaseAdapter adapter requires that the listview has a high associated set to fill_parent or match_parent

Categories

Resources