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
Related
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.
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
I have successfully produced a ListView, which takes JSON data from a remote MySQL database, and adds the 3 fields (employee no, employee name, and title) to an Output string called
"employees".
This displays on an Android phone, OK, but what I really want to do is display ONLY employee
name and title - and then when this record in the list is clicked on, the I want to display
ONLY employee no in the next Activity.
Using Split String, I have managed to just show "employee no" in the next Activity, but that
still leaves the problem of just showing employee name + title ONLY in the ListView.
If I only add those 2 fields together in the Output string, then "employee no" would be
"invisible" when single item clicked on..
Many thanks in advance!
Here is the relevent code in my MainActivity..
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("employee no");
String title = jsonChildNode.optString("title");
String outPut = name + "-" + title + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_activated_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
You have to create an object of Employee which has three fields
private String emplyeeName;
private String employeeTitle;
private String employeeNum;
Then fill an ArrayList with the data returned from the server, and populate it using a Custom Adapter.
This way you could manage what should appear in the listview item.
hope it'll help. If there is something not obvious do not hesitate to ask. :)
Edit 1:
Here is an example :
The code in onCreate in MainActivity
final ArrayList<Employee> arr = new ArrayList<Employee>();
final ListView lv = (ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
String EmployeeNum = arr.get(position).getEmployeeNum();
Intent i = new Intent(MainActivity.this, SecondActivity.class);
i.putExtra("EmployeeNum", EmployeeNum);
startActivity(i);
}
});
CustomAdapter adapter = new CustomAdapter(this , R.layout.activity_main , arr);
lv.setAdapter(adapter);
The custom adapter
public class CustomAdapter extends ArrayAdapter<Employee> {
ArrayList<Employee> Info;
private Context context;
CustomAdapter(Context context, int resource, ArrayList<Employee> objects) {
super(context, resource, objects);
// TODO Auto-generated constructor stub
this.context = context;
Info = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
EmployeeItemHolder employeeHolder;
View view = convertView;
if (view == null) {
employeeHolder = new EmployeeItemHolder();
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
view = inflater.inflate(R.layout.custom_row, parent, false);
employeeHolder.title = (TextView) view.findViewById(R.id.tvtextView);
view.setTag(employeeHolder);
} else {
employeeHolder = (EmployeeItemHolder) view.getTag();
}
Employee eItem = (Employee) this.Info.get(position);
employeeHolder.title.setText(eItem.getEmployeeTitle()+"-"+eItem.getEmplyeeName());
return view;
}
private static class EmployeeItemHolder {
TextView title;
}
}
custom_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/tvtextView" />
</LinearLayout>
Edit 2:
To integrate with this code convert your employeeList from
ArrayList<String>
to
ArrayList<Employee>
Here is an example :
ArrayList<Employee> employeeList = new ArrayList<Employee>();
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
Employee emp = new Employee();
emp.setEmplyeeName(jsonChildNode.optString("employee name"));
emp.setEmployeeTitle(jsonChildNode.optString("title"));
emp.setEmployeeNum(jsonChildNode.optString("employee no"));
employeeList.add(emp);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.activity_main, employeeList );
listView.setAdapter(adapter);
hope that'll help you
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
Question part: 1
I have created an activity which contains product id and product name as list items. Each row contains an edittext which can be used to enter quantity for a particular product. The rows also contain a checkbox to select the particular product.
This is how the list looks like:
When I click on the list items, I can get the id and name of the particular list item, but I also want to get the quantity entered by the user for the list item.
This is the activity responsible for generating the listview:
public class PollStationActivity extends Activity {
// Hashmap for ListView
ArrayList<HashMap<String, String>> PSList = new ArrayList<HashMap<String, String>>();
String status_code_from_prev;
List<HashMap<String, String>> fillMaps=null;
String alert_message;
String quantity_message;
//quantity edittext
EditText quantity_edit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll_station);
//quantity edittext
quantity_edit = (EditText)findViewById(R.id.qty_editText);
//database insertion
DatabaseHelper db = new DatabaseHelper(this);
ContentValues values = new ContentValues();
try {
db.createDataBase();
values.put("_id", "1");
values.put("name", "rose");
db.insert(values);
} catch (IOException e) {
e.printStackTrace();
}
db.close();
ArrayList<TestItem> PSList = new ArrayList<TestItem>();
try {
db.createDataBase();
PSList = db.getAllData();
} catch (IOException e) {
e.printStackTrace();
}
db.close();
fillMaps = new ArrayList<HashMap<String, String>>();
Iterator<TestItem> i = PSList.iterator();
while(i.hasNext())
{
HashMap<String, String> map = new HashMap<String, String>();
TestItem objPSItem = i.next();
map.put("name", objPSItem.NAME);
map.put("Id", objPSItem.ID);
//map.put("quantity", objPSItem.QUANTITY);
fillMaps.add(map);
}
Log.i("Size: ", ""+fillMaps.size());
//populating listview from database
ListView listView1 = (ListView) findViewById(R.id.poll_list_listView);
if (null != listView1 && null != PSList) {
listView1.setAdapter(new ListAdapter(PollStationActivity.this,
R.id.ListViewContainer, new String[fillMaps.size()]));
}
}
//class for the list and on click handler
class ListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ListAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.values = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// return super.getView(position, convertView, parent);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.list_layout, parent,
false);
final HashMap<String, String> map = fillMaps.get(position);
TextView textView = (TextView) rowView
.findViewById(R.id.list_label_name);
textView.setText("("+map.get("Id")+") "+map.get("name"));
rowView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rowView.setBackgroundResource(R.drawable.list_bg_pressed);
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
rowView.setBackgroundResource(R.drawable.list_bg);
}
};
handler.postDelayed(r, 200);
//alert box
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PollStationActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Please Note!");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
// Intent intent = new Intent(RegisterFirstActivity.this, RegisterSecondActivity.class);
//
// intent.putExtra("AC_Code", map.get(TAG_CODE));
// RegisterFirstActivity.this.startActivity(intent);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
return rowView;
}
}
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
This is the TestItem class:
public class TestItem {
public String ID;
public String NAME;
public String QUANTITY;
public boolean selected;
// Empty constructor
public TestItem(){
}
// constructor
public TestItem(String id, String name, String quantity){
this.ID = id;
this.NAME = name;
this.QUANTITY = quantity;
}
// constructor
public TestItem(String name, String quantity){
this.NAME = name;
this.QUANTITY = quantity;
}
// getting ID
public String getID(){
return this.ID;
}
// setting id
public void setID(String id){
this.ID = id;
}
// getting name
public String getName(){
return this.NAME;
}
// setting name
public void setName(String name){
this.NAME = name;
}
// getting phone number
public String getQuantity(){
return this.QUANTITY;
}
// setting quantity
public void setQuantity(String quantity){
this.QUANTITY = quantity;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
This is the activity_poll_station.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/main_bg">
<RelativeLayout
android:id="#+id/ListViewContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/poll_label_textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp" >
<ListView
android:id="#+id/poll_list_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ListView>
</RelativeLayout>
</RelativeLayout>
This is the list_layout.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/library_linear_layout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:background="#drawable/list_bg"
android:padding="5dp" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="44dp"
android:background="#null" >
<TextView
android:id="#+id/list_label_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="name"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="17sp" />
<CheckBox
android:id="#+id/item_checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
<EditText
android:id="#+id/qty_editText"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:maxLines="1"
android:inputType="number" >
</EditText>
</RelativeLayout>
</LinearLayout>
I want to how to extract text from the edittext which I have created for every list item. If I try to extract the text on
rowView.setOnClickListener(new View.OnClickListener()
like this:
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to select "+"("+map.get("Id")+") "+map.get("name")+"Quantity: "+quantity_edit.getText().toString()+"?");
The I am getting a null pointer exception getting generated due to the rowView.setOnClickListener(new View.OnClickListener()
What should I do? What should be the work around?
Thanks in advance!
//------------------------------------------------------------------------------//
Question part: 2
Now I want to do something like, I want to remove a particular row on clicking it. The row will only be deleted from the existing listview and a new list will be shown, how to do that?
Thanks once again!
You first need to get the reference to the EditText object, which you can do by using findViewById
quantity_edit = (EditText) view.findViewById("qty_editText");
you have override getView method of custom adapter. like the following.
public class SimpleAdapter1 extends ArrayAdapter<Data> {
public SimpleAdapter1(Context context, int textViewResourceId,
List<Data> catDesc) {
super(context, textViewResourceId, catDesc);
this.items = (ArrayList<Data>) catDesc;
this.context = context;
itemsid = new ArrayList<Integer>();
System.out.println(items);
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.YourLayout, null);
}
edit = (EditText) v.findViewById(R.id.editText1);
String tx = edit.getText().toString();
return v;
}
}
It will be very simple if you use custom adapter for your listview.
you can see this Custom Adapter for List View
and This one also useful for you how to get EditText value from listview