I am getting this error:
The constructor AllProductsActivity.MyAdapter(AllProductsActivity, int, ArrayList<HashMap<String,String>>) is undefined
At this line:
MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);
My best guess is that productsList is the issue, but after about 2 days of trying to understand the code, I haven't figured it out. A lot of the code is from this tutorial and to be honest I don't understand what a hashmap is. - http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
I know it sucks to help people on stack overflow who seem clueless but I could really use a push in the right direction. The HashMap Class Overview is like gibberish to me(http://developer.android.com/reference/java/util/HashMap.html)
Thanks in advance for any help.
Here is my entire AllProductsActivity:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// 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://mywebsite/mycameraapp/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_DESCRIPTION = "description";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on selecting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
/** CALLED WHEN THE USER CLICKS THE RECORD BUTTON */
public void sendMessage(View view) {
Intent videoIntent = new Intent(this, PhotoIntentActivity.class);
startActivity(videoIntent);
}
// 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(AllProductsActivity.this);
pDialog.setMessage("Loading trends...");
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
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String description = c.getString(TAG_DESCRIPTION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_DESCRIPTION, description);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.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
* */
MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);
// updating listview
setListAdapter(adapter);
}
});
}
}
}
I actually had MyAdapter in the AllProductsActivity file, but for ease of viewing I'll put it separately here:
public class MyAdapter extends ArrayAdapter<MyItem>{
Context context;
int resourceId;
ArrayList<MyItem> items = null;
LayoutInflater inflater;
public MyAdapter (Context context, int resourceId, ArrayList<MyItem> items)
{
super(context, resourceId, items);
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.video = (VideoView)convertView.findViewById(R.id.videoView);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
MyItem item = items.get(position);
if (item != null)
{
// This is where you set up the views.
holder.name.setText(TAG_NAME);
Uri myUri = Uri.parse(TAG_DESCRIPTION);
holder.video.setVideoURI(myUri);
holder.video.seekTo(1);
holder.video.setOnTouchListener(
new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event) {
holder.video.start();
holder.video.requestFocus();
return false;
}
}
);
}
return convertView;
}
public class ViewHolder
{
TextView name;
VideoView video;
}
}
You are passing productsList to the constructor which is ArrayList of HashMaps
ArrayList<HashMap<String, String>> productsList;
Also remove runOnUiThread cause onPostExecute is invoked on the ui thread itself.
Your constructor must be.
ArrayList<HashMap<String, String>> items;
public MyAdapter (Context context, int resourceId, ArrayList<HashMap<String, String>> items)
{
super(context, resourceId, items);
this.items =items;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
In getView()
HashMap<String,String> item = (HashMap<String,String> ) items.get(position);
To set text
holder.name.setText(item.get(TAG_NAME));
Also change to
public class MyAdapter extends ArrayAdapter<HashMap<String, String>> {
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
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);
}
});
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 am using json parser to pass image url and description into my listview. now i managed to load the images but how do i change the text for my list view? currently it just shows item 0, item 1 and so on.. how do i pass the description into the lazyadapter?
Main activity:
public class MainActivity extends Activity {
// CREATING JSON PARSER OBJECT
JSONParser jParser = new JSONParser();
JSONArray guide = null;
ListView list;
LazyAdapter adapter;
String[] mImageIds;
ArrayList<String> guideList =new ArrayList<String>();
ArrayList<String> descriptionList =new ArrayList<String>();
// GUIDE URL
private static String url_guide = "http://58.185.41.178/magazine_android/get_guide.txt";
private static final String TAG_GUIDES = "guides"; //the parent node of my JSON
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_IMAGE = "image";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// LOADING Guide IN BACKGROUND THREAD
new LoadGuide().execute();
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this,guideList);
list.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
}
#Override
public void onDestroy()
{
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadGuide extends AsyncTask<String, String, String> {
/**
* getting All videos 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_guide, "GET", params);
// CHECKING OF JSON RESPONSE
Log.d("All guide: ", json.toString());
try {
guide = json.getJSONArray(TAG_GUIDES);
for (int i = 0; i < guide.length(); i++) {
JSONObject c = guide.getJSONObject(i);
//String title = c.getString(TAG_DESCRIPTION);
String image = c.getString(TAG_IMAGE);
String description = c.getString(TAG_DESCRIPTION);
guideList.add(image);
descriptionList.add(description);
System.out.println(guideList);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// UPDATING UI FROM BACKGROUND THREAD
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter.notifyDataSetChanged();
}
});
}
}
}
Image adapter:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<String> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<String> guideList) {
activity = a;
data=guideList;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
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.item, null);
TextView text=(TextView)vi.findViewById(R.id.text);;
ImageView image=(ImageView)vi.findViewById(R.id.image);
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
}
In your adapter, you are making the TextView say "item 1", "item 2" etc specifically. What you need to do is add in the Adapter constructor your descriptionList
public LazyAdapter(Activity a, ArrayList<String> guideList, ArrayList<String> descriptionList) {
and then do
text.setText(descriptionList.get(position));
When your activity calls adapter.notifyDataSetChanged(), that forces a re-draw of every item in the list. That will trigger a call into the getView() method your adapter. So your logic belongs in the getView() method:
text.setText(descriptionList.get(position));
Use a single Hashmap for guidelist and descriptionlist and then pass that to the lazyadapter constructor. use the description part of the hashmap in the getview() method to the set the text.
#user1933630
descriptionList.add(description.subString(1,description.length()-1);