I am having a problem on my android application , i am getting data from mysql using JSON Parsing.
When i select a listview item and pass it to another activity it takes a random value instead of the one i have selected.
Here is my code in the listview activity.
public class Outlets extends ListActivity{
// Progress Dialog
private ProgressDialog pDialog;
// testing on Emulator:
private static final String READ_OUTLETS_URL = "http://10.0.2.2:8081/bfc_webservice/outlet_list.php";
// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_OUTLET_NAME = "outlet_name";
private static final String TAG_SPARKLING_CLASSIFICATION = "sparkling_classification";
private static final String TAG_ID = "id";
private static final String TAG_POSTS= "posts";
private static final String TAG_SPARKLING_CHANNEL = "sparkling_channel";
// An array of all of our comments
private JSONArray mOutlets = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mOutletsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.outlets);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
/*public void addComment(View v) {
Intent i = new Intent(ShowComments.this, PostComment.class);
startActivity(i);
}
*/
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content.
mOutletsList = new ArrayList<HashMap<String, String>>();
// Instantiating the json parser J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
// back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_OUTLETS_URL);
//Catcing Exceptions
try {
//Checking the amount of data rows.
mOutlets = json.getJSONArray(TAG_POSTS);
// looping through the database
for (int i = 0; i < mOutlets.length(); i++) {
JSONObject c = mOutlets.getJSONObject(i);
// gets the content of each tag
String outletname = c.getString(TAG_OUTLET_NAME);
String spark_channel = c.getString(TAG_SPARKLING_CHANNEL);
String spark_class = c.getString(TAG_SPARKLING_CLASSIFICATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_OUTLET_NAME, outletname);
map.put(TAG_SPARKLING_CHANNEL, spark_channel);
map.put(TAG_SPARKLING_CLASSIFICATION, spark_class);
// adding HashList to ArrayList
mOutletsList.add(map);
// JSON data parsing completed by hash mappings
// list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mOutletsList,
R.layout.single_outlet, new String[] { TAG_OUTLET_NAME, TAG_SPARKLING_CHANNEL,
TAG_SPARKLING_CLASSIFICATION }, new int[] { R.id.outlet_name, R.id.sparkling_channel,
R.id.sparkling_classification });
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
TextView outname = (TextView)findViewById(R.id.outlet_name);
TextView channel = (TextView)findViewById(R.id.sparkling_channel);
TextView clas = (TextView)findViewById(R.id.sparkling_classification);
String foutname = outname.getText().toString();
String fchannel = channel.getText().toString();
String fclass = clas.getText().toString();
Intent i = new Intent(Outlets.this, ScoreSheet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
startActivity(i);
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Outlets.this);
pDialog.setMessage("Loading Outlets...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
And the code for my next activity is this one.I want just to test if i am getting the correct value using TextViews.
public class ScoreSheet extends Activity{
TextView oname, sch, scls;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.score_sheet);
oname = (TextView)findViewById(R.id.txtoutname);
sch = (TextView)findViewById(R.id.txtspchannel);
scls = (TextView)findViewById(R.id.txtspclass);
Intent myIntent = getIntent();
String ot = myIntent.getStringExtra("outlt");
String ch = myIntent.getStringExtra("chnl");
String cls = myIntent.getStringExtra("cls");
oname.setText(ot);
sch.setText(ch);
scls.setText(cls);
}
}
Your help is so much appreciated forever in my heart guys.Even other methods of doing the same tasks i welcome them.Thank you so much in advance.
Change this
TextView outname = (TextView)findViewById(R.id.outlet_name);
TextView channel = (TextView)findViewById(R.id.sparkling_channel);
TextView clas = (TextView)findViewById(R.id.sparkling_classification);
to
TextView outname = (TextView)view.findViewById(R.id.outlet_name);
TextView channel = (TextView)view.findViewById(R.id.sparkling_channel);
TextView clas = (TextView)view.findViewById(R.id.sparkling_classification);
You need to use the view to find views. Instead of initalizing views you can do as below
The other way
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String,String> map= (HashMap<String, String>) parent.getItemAtPosition(position); // use postion. get the map
String foutname =map.get(TAG_OUTLET_NAME); // get the value using key
String fchannel = map.get(TAG_SPARKLING_CHANNEL);
String fclass = map.get(TAG_SPARKLING_CLASSIFICATION);
...// rest of the code
}
});
Use Following:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
View view1=(View) lv.getItemAtPosition(itemPosition );
TextView outname = (TextView)view1.findViewById(R.id.outlet_name);
TextView channel = (TextView)view1.findViewById(R.id.sparkling_channel);
TextView clas = (TextView)view1.findViewById(R.id.sparkling_classification);
String foutname = outname.getText().toString();
String fchannel = channel.getText().toString();
String fclass = clas.getText().toString();
Intent i = new Intent(Outlets.this, ScoreSheet.class);
i.putExtra("outlt", foutname);
i.putExtra("chnl", fchannel);
i.putExtra("cls", fclass);
startActivity(i);
}
});
Related
I retrieved some data from server and populated these data into a listview. I want to use part of the data i received and send it back to server. How do I do it? When I click on one of the list item it will start another activity with buttons, when i click one of the button the app will use part of the data in that listitem(which was previously retrieved from server) and send it back to server. I'm new to android programming, i'm stuck and have no idea how do I do this. Could someone advised me? I know how to send data to server by manually typing the data i want to send.
This is how i get the data from server and populated into a listview and i want to send a particular phonenumber received back to server when i click that listview item:
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)getView().findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)getView().findViewById(R.id.number);
info = (TextView)getView().findViewById(R.id.info);
remark = (TextView)getView().findViewById(R.id.remark);
statuss = (TextView)getView().findViewById(R.id.statuss);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_view,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
Intent ThreeButton = new Intent(getActivity(), ThreeButton.class);
startActivity(ThreeButton);
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent ThreeButton = new Intent(getActivity(), ThreeButton.class);
ThreeButton.putExtra("phone", oslist.get(position).get("phonenumber"));
//u can put all variables similarly...
startActivity(ThreeButton);
}
}
);
In ThreeButton Activity
onCreate(){
Intent data=getIntent();
data.getString("phone");
Log.v("phone",phone);
}
You do not have access to data in listview in your next activity. Instead of trying get that from there, you can pass needed data to new activity. Before call startActivity put into intent data using methods putExtra. By the way, if you are working with JSON you should check Gson library to parse json
Sorry for my English,How i can show arraylist index numbers in my dynamic listview?
for example in my app when listview display,in a listview every cell have a index number display like first cell 1,second cell 2,third cell 3 and so on..how i can implement this?Thanks in advance.
This is the screen shot:
in my screen shot see the left int number 1.and now want to in 2nd cell display 2 and so on..
This is my activity:
public class Artists extends Activity {
// Connection detector
ConnectionDetector cd;
// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// This is not using now if you want you can remove its all references :)
ArrayList<HashMap<String, String>> albumsList;
ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
private LazyAdapterArtist mLazyAdatper = null;
private ArrayList<String> array_sort = new ArrayList<String>();
int textlength = 0;
// albums JSONArray
JSONArray albums = null;
LinearLayout ll_artists_chart;
LinearLayout ll_artists_newrelease;
private EditText etSearch;
private static String URL_ALBUMS = "My URL";
// JSON Node names
private static final String TAG_CONTACTS = "data";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private ListView lv = null;
EditText et_artists_searchWord;
// contacts JSONArray
JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.artists);
lv = (ListView) findViewById(R.id.artist_main_list_id);
cd = new ConnectionDetector(getApplicationContext());
// Check for internet connection
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(Artists.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Hashmap for ListView
albumsList = new ArrayList<HashMap<String, String>>();
mAdapterDTOs = new ArrayList<AdapterDTOArtist>();
// Loading Albums JSON in Background Thread
new LoadAlbums().execute();
// get listview
/**
* Listview item click listener TrackListActivity will be lauched by
* passing album id
* */
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// on selecting a single album
}
});
ll_artists_chart = (LinearLayout) findViewById(R.id.ll_artists_chart);
ll_artists_newrelease = (LinearLayout) findViewById(R.id.ll_artists_newrelease);
et_artists_searchWord = (EditText) findViewById(R.id.et_artists_searchWord);
et_artists_searchWord.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
// ((Filterable) Artists.this.mAdapterDTOs).getFilter().filter(s);
List<AdapterDTOArtist> list = filter(s.toString(),mAdapterDTOs, true);
mAdapterDTOs.addAll(list);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
ll_artists_chart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), ChartActivity.class);
startActivity(intent);
// finish();
}
});
ll_artists_newrelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getBaseContext(), NewReleases.class);
startActivity(intent);
//finish();
}
});
}
/**
* Background Async Task to Load all Albums by making http request
* */
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Artists.this);
pDialog.setMessage("Listing Artists ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
//List<NameValuePair> params = new ArrayList<NameValuePair>();
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(URL_ALBUMS);
// getting JSON string from URL
//String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET", params);
// Check your log cat for JSON reponse
Log.i("Albums JSON: ", "> " + json);
try {
//albums = new JSONArray(json);
albums = json.getJSONArray(TAG_CONTACTS);
if (albums != null) {
// looping through All albums
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
/*String EateryThmbnailUrl = c
.getString(TAG_THMBNAIL_URL);*/
// ~\/Uploads\/EateryImages\/\/7\/41283f1f-8e6f-42d4-b3c1-01f990efb428.gif
/*EateryThmbnailUrl = HOST_URL
+ EateryThmbnailUrl.replace("~", "");*/
AdapterDTOArtist adapterDTO = new AdapterDTOArtist();
adapterDTO.setmTag_Id(id);
adapterDTO.setmTag_Name(name);
// adapterDTO.setmImage_URL(EateryThmbnailUrl);
mAdapterDTOs.add(adapterDTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
albumsList.add(map);
}
} else {
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all albums
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
// updating listview
mLazyAdatper = new LazyAdapterArtist(Artists.this,
mAdapterDTOs);
lv.setAdapter(mLazyAdatper);
// mLazyAdatper.setDataSet(mAdapterDTOs);
}
});
}
}
public static List<AdapterDTOArtist> filter(String string,
Iterable<AdapterDTOArtist> iterable, boolean byName) {
if (iterable == null)
return new LinkedList<AdapterDTOArtist>();
else {
List<AdapterDTOArtist> collected = new LinkedList<AdapterDTOArtist>();
Iterator<AdapterDTOArtist> iterator = iterable.iterator();
if (iterator == null)
return collected;
while (iterator.hasNext()) {
AdapterDTOArtist item = iterator.next();
collected.add(item);
}
return collected;
}
}
}
My AdapterDTOArtist class :
public class AdapterDTOArtist {
private String mTag_Id;
private String mTag_Name;
public String getmTag_Name() {
return mTag_Name;
}
public void setmTag_Name(String mTag_Name) {
this.mTag_Name = mTag_Name;
}
public String getmTag_Id() {
return mTag_Id;
}
public void setmTag_Id(String mTag_Id) {
this.mTag_Id = mTag_Id;
}
}
My LazyAdapterArtist class:
public class LazyAdapterArtist extends BaseAdapter {
private Context mContext = null;
private ArrayList<AdapterDTOArtist> mAdapterDTOs = null;
public LazyAdapterArtist(Context context,
ArrayList<AdapterDTOArtist> mAdapterDTOs2) {
// TODO Auto-generated constructor stub
this.mContext = context;
this.mAdapterDTOs = mAdapterDTOs2;
}
public void setDataSet(ArrayList<AdapterDTOArtist> adapterDTOs) {
this.mAdapterDTOs = adapterDTOs;
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mAdapterDTOs.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder mHolder = new ViewHolder();
if (row == null) {
// Cell is inflating for first time
row = LayoutInflater.from(mContext)
.inflate(com.whizpool.triplevmusic.R.layout.row_artists,
null, false);
mHolder.mNameTxt = (TextView) row
.findViewById(com.whizpool.triplevmusic.R.id.tv_row_artists);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
mHolder.mNameTxt.setText(mAdapterDTOs.get(position).getmTag_Name());
return row;
}
static class ViewHolder {
TextView mNameTxt = null;
}
}
just want to display my arraylist cells serialwise like first cell is 1,2nd cell 2 and so on
in your listview adapter, on getView() method, you can use the position for that purpose. If you don't have any textView to show the number, first add it to your listview item, then use it in getView() method
Add a new textview to show your position number;
static class ViewHolder {
TextView mNameTxt = null;
TextView mSeqNo; //new
}
Then use it in getView() method,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder mHolder = new ViewHolder();
if (row == null) {
// rest of your code
mHolder.mSeqNo = (TextView)row.findViewById(R.id.your_text_view);
row.setTag(mHolder);
} else {
// recycling of cells
mHolder = (ViewHolder) row.getTag();
}
//rest of your code
mHolder.mSeqNo.setText("" + position);
return row;
}
Using the position param in getView method is sufficient. It starts from 0 (the first index), then 1, 2,3 ...
mHolder.mSeqNo.setText("" + (position+1));
This would start the seq numbers from 1, like 1, 2, 3,..... and so on to the end of the list. But giving mHolder.mSeqNo.setText("" + (position) starts your number from 0, since list starts with 0 (the first value of index). All the best!
In my new Android app I have a view with a ListView populated from a JSON call, that is working. But what I need now is a Spinner populated with the same data as the ListView.
But after two days trying to do it, I am not able. The new Spinner id in its layout XML file is spinner2. Spinner1 is populated from a String[] as you can see in the code.
public class HiScreen extends ListActivity {
String[] spinnerValues = { "1","2","3"};
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> newsList;
// url to get all products list
private static String url_all_news = "";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_NEWS = "news";
private static final String TAG_ID = "id";
private static final String TAG_HEADER = "header";
private static final String TAG_BODY = "body";
private static final String TAG_TIME = "time";
// products JSONArray
JSONArray news = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_news);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
mySpinner.setAdapter(new MyAdapter(this, R.layout.custom_spinner,
spinnerValues));
Spinner s = (Spinner) findViewById( R.id.spinner2 );
String user,server_url;
Bundle extras = getIntent().getExtras();
// Obtenemos datos enviados en el intent.
if (extras != null) {
user = extras.getString("user");//usuario
server_url = extras.getString("server");
url_all_news = server_url+"android_get_all_news.php";
} else {
user="error";
}
// Hashmap for ListView
newsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
;
}
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context ctx, int txtViewResourceId, String[] objects) {
super(ctx, txtViewResourceId, objects);
}
#Override
public View getDropDownView(int position, View cnvtView, ViewGroup prnt) {
return getCustomView(position, cnvtView, prnt);
}
#Override
public View getView(int pos, View cnvtView, ViewGroup prnt) {
return getCustomView(pos, cnvtView, prnt);
}
public View getCustomView(int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View mySpinner = inflater.inflate(R.layout.custom_spinner, parent,
false);
TextView main_text = (TextView) mySpinner .findViewById(R.id.text_main_seen);
main_text.setText(spinnerValues[position]);
TextView subSpinner = (TextView) mySpinner
.findViewById(R.id.sub_text_seen);
subSpinner.setText(spinnerSubs[position]);
ImageView left_icon = (ImageView) mySpinner
.findViewById(R.id.left_pic);
left_icon.setImageResource(total_images[position]);
return mySpinner;
}
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HiScreen.this);
pDialog.setMessage("Loading News. Bitte warten...");
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_all_news, "GET", params);
// Check your log cat for JSON reponse
Log.d("All News: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
news = json.getJSONArray(TAG_NEWS);
String[] datos = new String[news.length()];
// looping through All Products
for (int i = 0; i < news.length(); i++) {
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
datos[i] = c.getString(TAG_HEADER);
String id = c.getString(TAG_ID);
String header = c.getString(TAG_HEADER);
String body = c.getString(TAG_BODY);
String time = c.getString(TAG_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_HEADER, header);
map.put(TAG_BODY, body);
map.put(TAG_TIME, time);
// adding HashList to ArrayList
newsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
HiScreen.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
HiScreen.this, newsList,
R.layout.list_item, new String[] { TAG_ID,
TAG_HEADER,TAG_BODY,TAG_TIME},
new int[] { R.id.pid, R.id.name,R.id.body,R.id.time });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
You can create String Array or ArrayList from json, after it you can add it in array adapter so you can easily add data to spinner.
I have a Custom ListView which is populated with retrieved from a database. Now, what I can't understand is how to remove an item from the list: searching on Google I've seen different questions without a standard solution, so I have doubts about this. How can I delete a row from a CustomListView also using Async Task?
Here is Leggi_Pizzaiolo activity (where I display the listView):
public class Leggi_Pizzaiolo extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
public List list = new LinkedList();
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://10.0.2.2/tesina/Leggi_Pizzaiolo.php";
// JSON Node names
private static final String TAG_SUCCESS = "Esito";
private static final String TAG_PRODUCTS = "comande";
private static final String TAG_PID = "ID";
private static final String TAG_NAME = "Nome";
private static final String TAG_TABLE = "Tavolo";
public ListView lv;
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ordini_cuoco);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
// Get listview
lv = (ListView)findViewById(R.id.lista);
new LoadAllProducts().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Leggi_Pizzaiolo.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_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
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);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt(TAG_PID);
String name = c.getString(TAG_NAME);
int Tavolo= c.getInt(TAG_TABLE);
list.add(new Comanda(name, id, Tavolo));
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
Listino.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating listview
final ComandaCursorAdapter adapter = new ComandaCursorAdapter(Leggi_Pizzaiolo.this, R.layout.comanda_cuoco, list);
lv.setAdapter(adapter);
}
}
}
This is the CursorAdapter:
public class ComandaCursorAdapter extends ArrayAdapter<Comanda>
{
public ComandaCursorAdapter(Context context, int comandaCuoco, List list) {
super(context, comandaCuoco, list);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.comanda_cuoco, null);
TextView Nome = (TextView)convertView.findViewById(R.id.Comanda);
TextView Tavolo = (TextView)convertView.findViewById(R.id.Tavolo);
TextView Codice = (TextView)convertView.findViewById(R.id.Codice);
Comanda c = getItem(position);
Nome.setText(c.getNome());
Tavolo.setText("Tavolo: " + Integer.toString(c.getTavolo()));
Codice.setText("Codice: " + Integer.toString(c.getCodice()));
return convertView;
}
And this is the object Comanda:
public class Comanda {
private String Nome;
private int Codice;
private int Tavolo;
public Comanda(String Nome, int Codice, int Tavolo)
{
this.Nome = Nome;
this.Codice = Codice;
this.Tavolo = Tavolo;
}
public String getNome()
{
return Nome;
}
public void setNome(String Nome)
{
this.Nome = Nome;
}
public int getCodice()
{
return Codice;
}
public void setCodice(int Codice)
{
this.Codice = Codice;
}
public int getTavolo()
{
return Tavolo;
}
public void setTavolo(int Tavolo)
{
this.Tavolo = Tavolo;
}
}
Now, where I have to declare the setOnItemClickListener in Leggi_Pizzaiolo activity? Should I have to implement a remove method into the class or something? Please let me know how...
Now, what I can't understand is how to remove an item from the list
No, normally create for example OnItemClickListener() to be able to handle click events on ListView. Then in onItemClick() you have parameter int position that returns position of item in Adapter. Now you need to remove item from your List and then perform
list.remove(position)
and then you need to call
adapter.notifyDataSetChanged();
to notify Adapter that datasource has changed.
Note: For more comfort you can show after click on ListItem some AlertDialog with buttons for deleting or not.
Try this
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
where lv is your listview,adb is a dialog, mydataobject is the collection you are using to populate your listview and adapter is your adapter.
I will retrieve student information (id -number- name) from a database (MySQL) as a list view,
each student have 2 buttons (delete - alert ) and radio buttons
screen shot http://im21.gulfup.com/1pWi1.png
Every thing is ok, but how can I make an onClickListener, for example for the delete button
because I try lots of examples, I heard that I can use (custom list or get view or direct onClickListener as in my code (but it is not working ) or Simple Cursor Adapter) I do not know what to use, I looked around for examples that can help me, but in my case but I did not find any so I hope this be reference for anyone have the same problem.
this is my code which I use direct onClick with Simple Adapter
public class ManageSection extends ListActivity {
//ProgresogressDialog pDialog;
private ProgressDialog pDialog;
// Creating JSON Parser object
// Creating JSON Parser object
JSONParser jParser = new JSONParser(); //class
boolean x =true;
Button delete;
ArrayList<HashMap<String, String>> studentList;
//url to get all products list
private static String url_all_student = "http://10.0.2.2/SmsPhp/view_student_info.php";
String cl;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_student = "student";
private static final String TAG_StudentID = "StudentID";
private static final String TAG_StudentNo = "StudentNo";
private static final String TAG_FullName = "FullName";
private static final String TAG_Avatar="Avatar";
HashMap<String, String> selected_student;
// course JSONArray
JSONArray student = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_section);
studentList = new ArrayList<HashMap<String, String>>();
ListView list1 = getListView();
list1.setAdapter(getListAdapter());
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
delete =(Button)view.findViewById(R.id.DeleteStudent);
cl=selected_student.get(TAG_StudentID);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Log.d("id: ",cl);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
}
});
}
});
new LoadAllstudent().execute();
}
/**
* Background Async Task to Load all student by making HTTP Request
* */
class LoadAllstudent extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ManageSection.this);
pDialog.setMessage("Loading student. Please wait...");
pDialog.setIndeterminate(false);
/**
* getting All student from u r l
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_student, "GET", params);
// Check your log cat for JSON response
Log.d("All student : ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// student found
// Getting Array of course
student = json.getJSONArray(TAG_student);
// looping through All courses
for (int i = 0; i < student.length(); i++)//course JSONArray
{
JSONObject c = student.getJSONObject(i); // read first
// Storing each json item in variable
String StudentID = c.getString(TAG_StudentID);
String StudentNo = c.getString(TAG_StudentNo);
String FullName = c.getString(TAG_FullName);
// String Avatar = c.getString(TAG_Avatar);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_StudentID, StudentID);
map.put(TAG_StudentNo, StudentNo);
map.put(TAG_FullName, FullName);
// adding HashList to ArrayList
studentList.add(map);
}
} else {
x=false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
if (x==false)
Toast.makeText(getBaseContext(),"no student" ,Toast.LENGTH_LONG).show();
ListAdapter adapter = new SimpleAdapter(
ManageSection.this, studentList,
R.layout.list_student, new String[] { TAG_StudentID,
TAG_StudentNo,TAG_FullName},
new int[] { R.id.StudentID, R.id.StudentNo,R.id.FullName});
setListAdapter(adapter);
// Updating parsed JSON data into ListView
}
}
}
So what do you think, why doesn't the delete button work? There is no error in my log cat. What is the alternative way?
Add your button's onclicklistener outside of your ListView's onclicklistener -
list1.setAdapter(new (youradaptername)(getApplicationContext()));
list1.setOnItemClickListener(detaillistener);
private OnItemClickListener detaillistener = new OnItemClickListener()
{
// to your Onclick action coding here
}
};
just do as same for other buttons.
for more just go to this link here
Just define your button's onclick listener in outside of your ListView's onclicklistener -
delete =(Button)view.findViewById(R.id.DeleteStudent); // initialize this here
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l)
{
selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
cl=selected_student.get(TAG_StudentID);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
}
});
delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Log.d("id: ",cl);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
}
});
From your code it will work when your ListView's item once clicked then only your button will work. So try with above code.
#sara your code is very correct but, it is not working because you havent passed the context properly..!
now use this code it will work for sure :
ListView list1 = getListView();
list1.setAdapter(getListAdapter());
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
selected_student =(HashMap<String, String>) studentList.get(pos); //member of your activity.
delete =(Button)view.findViewById(R.id.DeleteStudent);
cl=selected_student.get(TAG_StudentID);
Toast.makeText(getBaseContext(),cl,Toast.LENGTH_LONG).show();
delete.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Log.d("id: ",cl);
Toast.makeText(ManageSection.this,cl,Toast.LENGTH_LONG).show();
}
});
}
});
i have just added this line to ur code:
Toast.makeText(ManageSection.this,cl,Toast.LENGTH_LONG).show();
now try and tell me if it is working..