Populate listview with 2 strings from webservices in fragment - android

I have wrote the code to populate List View with single string. But, I don't know how to populate with 2 strings.. Somebody, please help me out.
here is my code:
public class BackTask extends AsyncTask<String, Void, String> {
ArrayList<FlowerAdapter.Flowers> flowersList = new ArrayList<FlowerAdapter.Flowers>();
String url = "http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String content = FlowerAdapter.HttpULRConnect.getData(url);
return content;
}
#Override
protected void onPostExecute(String s){
try {
JSONArray ar =new JSONArray(s);
for (int i = 0; i < ar.length(); i++){
JSONObject jsonObject=ar.getJSONObject(i);
here i want to get 2 strings "NAME"&"PERCENTAGE"....but i dont know how to get the another string and bind it in List View.
FlowerAdapter.Flowers flowers= new FlowerAdapter.Flowers();
flowers.setName(jsonObject.getString("NAME"));
flowersList.add(flowers);
FlowerAdapter adapter=new FlowerAdapter(getContext(),R.layout.flower_list_xml,flowersList);
listView = (ListView)getView().findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

first, add all the field in your Flowers class with setters and gettersThen set it in the object which you are passing to adapter.

i have created a setter for this second string and called it...thats all..
flowers.setPercentage(jsonObject.getString("Percentage");

Related

How to use custom Adapter after parsing data from server

ANSWERED BY ME
I am confused where to put and how to use my custom adapter.
My Parser.class has its own Adapter and my MainActivity is passing 3 parameters to the Parser.class (context, url, listview).
(Making my problem simple)
After creating a custom layout, custom adapter, and instantiating my custom adapter, I don't know what to do.
I tried instantiating my custom adapter in my MainActivity then creating MainActivity m = new MainActivity(); in my Parser.class and just use the textviews of my custom listview like m.name_tv.setText(name); and m.price_tv.setText(price) then changing the android.R.layout.simple_list_item_1 to my custom listview layout R.layout.list_layout.
I was just experimenting because I'm having trouble understanding.
Please help.
This is my Parser.class
public class Parser extends AsyncTask<Void,Integer,Integer> {
Context c;
ListView lv;
String data;
ArrayList<String> categories = new ArrayList<>();
ProgressDialog pd;
public Parser(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Parsing Data");
pd.setMessage("Please Wait...");
pd.show();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_list_item_1, categories);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
}
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse(){
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray ja = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jo = null;
categories.clear();
//LOOP THROUGH ARRAY
for(int i =0 ; i<ja.length();i++)
{
jo = ja.getJSONObject(i);
//RETRIEVE NAME
name=jo.getString("item_name");
price=jo.getString("item_price");
//ADD TO ARRAY LIST
categories.add(name + " " + price);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Should it be better to not separate the classes or it will work the same?
you should get response from web service and parse it (json object or json array) in one step
you can reach this in good way ,
First create class with json attribute name
in your case
Class JsonItem {
string item_name;
string item_price;
// create getter and setter
}
Second use Gson to parse your response
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
JsonItem staff = gson.fromJson(YOUR_JSON_Here, JsonItem.class);
that is all

Android Spinner with custom java object showing key value pairing instead of value

So, I used Android - configure Spinner to use array to try and display just one field of a custom java class. My Java class is as follows (it is a part of my Google App Engine backend)
public class CropVariety {
private String varietyId;
private String varietyName;
public String getVarietyId() { return varietyId; }
public String getVarietyName() {
return varietyName;
}
public void setVarietyId(String data) {varietyId = data; }
public void setVarietyName(String data) {
varietyName = data;
}
public String toString()
{
return varietyName;
}
}
and then in the activity Async task, I have the following in Post Execute
super.onPostExecute(result);
varietyList = result;
spinner = (Spinner) findViewById(R.id.variety_spinner);
spinner.setSelection(0);
dataAdapter = new ArrayAdapter(context,android.R.layout.simple_spinner_item, varietyList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
The OnItemSelectedListener is implemented as follows:
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
// String selectedItem = parent.getItemAtPosition(pos).toString();
CropVariety selectedItem = (CropVariety) parent.getItemAtPosition(pos);
//check which spinner triggered the listener
switch (parent.getId()) {
case R.id.variety_spinner:
selectedVarietyName = selectedItem.getVarietyName();
selectedVarietyId = selectedItem.getVarietyId();
break;
}
So while selectedVarietyName and selectedVarietyId get the right values, each item on the drop down list looks as follows:
{"varietyId":"sefs","varietyName":"asfd"}
I followed the link and don't know why the variety name isn't being displayed in the spinner. Thank you
you are downloading json Object from that link .. you have to parse th json in your doInBackground .. and store the result in a list to use it later in the postExecute here is an exemple:
class ModifierParam extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityMed.this);
if (action.equals("rdvmed")) {
pDialog.setMessage(getString(R.string.enrParam));
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
}
protected String doInBackground(String... args) {
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
//here are the password and email for login
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Mdp", mdp));
json = jsonParser.makeHttpRequest(url_parametres,
"POST", params);
}
try {
if(json != null && !json.isNull("yourArrayName")){
list.clear();
if (json.has("yourArrayName")) {
JSONArray ja = json.getJSONArray("yourArrayName");
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
String varietyNames= String.valueOf(c.getInt("varietyName"));
String varietyId= c.getString("varietyId"));
//store data in the list
list.add(new YourObjectName(varietyName, varietyId));
}
}
}
}
}} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
//here you create your adapter from that list
// and then Spinner.setAdapter(the Adapter);
}
}
you need jsonParser i think you have it... if you dont here it is :
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
now your data will be displayed correctly

How can I update the listview content each time on a button click?

I need to update my ListView content (which is retrieved from a database) each time when a button is clicked. I am trying to include a book search functionality in my android application.
For that I am taking some keywords as input.On a button click the book details matching the key word is retrieved from database and is displayed in the list view in the same layout.
The code I have written will create a new ListView with updated content on each button click and display it below the previous ListView.Which I need to correct.
A preferred solution will be to update the list view content on a button click.
Removing the previously displayed ListView is also acceptable.
For that I tried getListView().inValidate() but didn't work. notifyDataSetChanged() also is not working .Please help :)
public class searchActivity extends ListActivity {
String keyword;
Button bsearch;
EditText input;
JSONParser jParser = new JSONParser();
JSONArray books = null;
SimpleAdapter adapter;
ArrayList<HashMap<String, String>> booksList;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState{
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
bsearch=(Button)findViewById(R.id.search);
input=(EditText)findViewById(R.id.inputSearch);
booksList = new ArrayList<HashMap<String, String>>();
adapter=newSimpleAdapter(searchActivity.this,booksList,R.layout.search_list,new String[]{"bookname"},new int[] {R.id.bookname});
getListView().setAdapter(adapter);
bsearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
keyword=input.getText().toString();
new LoadAll().execute();
}
});
}
class LoadAll extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("keyword", keyword));
JSONObject json = Jparser.makeHttpRequest("http://10.0.2.2 /libraryconnect/search_book.php", "GET", params);
Log.d("All books: ", json.toString());
try {
int success = json.getInt("success");
if (success == 1) {
books = json.getJSONArray("books");
for (int i = 0; i < books.length(); i++) {
JSONObject c = books.getJSONObject(i);
String name = c.getString("bookname");
HashMap<String, String> map = new HashMap<String, String>();
map.put("bookname",bookname);
booksList.add(map);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
}
}
}
In your onClick(View v), call notifyDataSetChanged () from your adapter
You can change data set of your list view and then call notifyDataSetChanged() on it,instead of creating new list view or new adapter for it.
You can find what you need to know in Android ListView - Tutorial.

Android - Populate list with AsycTaskLoader & MySql

I want to fill a ListFragment with certain objects loaded from my MySql database.
It has to load the first 10 'objects' from my ResultSet.
I want to use an AsyncTaskLoader for this and put the loaded object in a ListItem each time I retreive it from the database.
Can anybody help me with this one? Tried searching for good examples or tutorials but I haven't really found something that's really useful...
Create your adapter with a new list in your preexecute method. Set that adapter to your listview.
Then in doInBackground read your database, create objects to fit in your list, but don't add them. Pas each object after made as parameter for your publishprogress method.
In onProgressUpdate add your object to the list and notify your adapter that the dataset is changed.
Below is an example for how I do it reading a twitter call.
private class parseTwitterTask extends AsyncTask<Void, TCListObject2, List<TCListObject2>> {
TCListObjectAdapter2 adapter;
List<TCListObject2> list;
#Override
protected void onPreExecute() {
list = new ArrayList<TCListObject2>();
ListView lv = (ListView)findViewById(R.id.twitterlist);
adapter = new TCListObjectAdapter2(list);
lv.setAdapter(adapter);
super.onPreExecute();
}
#Override
protected List<TCListObject2> doInBackground(Void... params) {
try {
String url = social.get("twittersearchurl");//"http://search.twitter.com/search.json?q=" + social.get("twitter");
String json = Internet.request(url, null);
JSONObject jo = new JSONObject(json);
if(jo.has("results")) {
JSONArray ar = jo.getJSONArray("results");
for(int i = 0; i < ar.length(); i++) {
TCListObject2 tweet = new TCListObject2();
JSONObject jobj = (JSONObject) ar.get(i);
tweet.id = "false";
tweet.img = jobj.getString("profile_image_url");
String text = jobj.getString("text");
text = Html.fromHtml(text).toString();
tweet.params.put(R.id.sub2, text);
String name = jobj.getString("from_user");
name = Html.fromHtml(name).toString();
tweet.params.put(R.id.text, name);
String time = jobj.getString("created_at");
tweet.params.put(R.id.sub1, Converter.timeToTimeAgo(time));
try {
tweet.time = new Date(time);
} catch(Exception e) {
e.printStackTrace();
}
tweet.celLayout = R.layout.cell_tweetobject;
publishProgress(tweet);
}
}
} catch(Exception e) {
e.printStackTrace();
}
return list;
}
#Override
protected void onProgressUpdate(TCListObject2... values) {
list.add(values[0]);
adapter.notifyDataSetChanged();
super.onProgressUpdate(values);
}

Setonitemclicklistener with AsyncTask gives NullPointerException

Need your help!!!
I have activity, where I get some data in JSON format and put it ListView. Everything works fine. But I want to define what item was clicked in list with Setonitemclicklistener. I tried to use it in onPostExecuted() method of my inner Connection class,which extends AsyncTask, but I've got NullPoinerException
public class ConnectionActivity extends ListActivity{
JsonParser jsonParser = new JsonParser();
private ListView listView;
JSONArray inbox = null;
private ProgressDialog pDialog;
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Date";
private static final String TAG_DATE = "Name";
private static final String TAG_PRICE = "Price";
ArrayList<HashMap<String,String>> resultList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resultList = new ArrayList<HashMap<String,String>> ();
new Connection().execute();
new ListHandler().execute();
}
class Connection extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConnectionActivity.this);
pDialog.setMessage("Не базарь и жди пока загрузиться!!!!");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest();
Log.d("Outbox JSON",json.toString());
try{
JSONArray jArray = new JSONArray(json);
for (int i=0;i<jArray.length();i++) {
JSONObject c = jArray.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name= c.getString(TAG_NAME);
String date = c.getString(TAG_DATE);
String price = c.getString(TAG_PRICE);
// creating new HashMap
HashMap<String, String> hashmap = new HashMap<String, String>();
// adding each child node to HashMap key => value
hashmap.put(TAG_ID, id);
hashmap.put(TAG_NAME, name);
hashmap.put(TAG_DATE, date);
hashmap.put(TAG_PRICE, price);
// adding HashList to ArrayList
resultList.add(hashmap);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
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(
ConnectionActivity.this, resultList,
R.layout.connect_item, new String[] { TAG_ID, TAG_NAME, TAG_DATE, TAG_PRICE },
new int[] { R.id.order_id, R.id.order_date, R.id.order_name, R.id.order_price });
// updating listview
setListAdapter(adapter);
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(new ListClickListener());
}
});
}
}
I think that problem is with using of one thread, so I created one more inner class in my ConnectionActivity like this^
class ListHandler extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute ()
{
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute()
{
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Log.d("Click on the item","!!!!!!!!!!!!!!!!!!!!!");
Toast toast = Toast.makeText(getApplicationContext(),
"Пора покормить кота!", Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
But it doesn't work. I mean that I cannot get the Toast when I clicked on the item , but there's no exception. I tried to handle setonitemclicklistener in void onResume() method of the Activity, but I've got NullPointerException. Also I handled this in OnPreExecute() method of the ListHandler class - same result...
Help please with it...
where is setContentView(R.layout.yourxml) ? i think you forgot it in oncreate Method.
So your listView is null and gives NPE.
AND
onPostExecute method have runonUiThread,Remove it no need it.Its already run in UI Thread.
Problem solved with extending from Activity instead of ListActivity and using setContentView().

Categories

Resources