How to make a BaseAdapter class part of an asynctask - Android [duplicate] - android

This question already has answers here:
BaseAdapter class wont setAdapter inside Asynctask - Android
(4 answers)
Closed 9 years ago.
I have an asynctask that gathers comments, usernames, and numbers by using a JSON method. Then I have a class that extends BaseAdapter that suppose to put the comments and usernames into a listView. The problem is how can I get the comments, usernames and numbers to the BaseAdapter class? Here is my current code
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
l1=(ListView)findViewById(R.id.list);
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
new loadComments().execute();
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(Context ctx_invitation, String[] comments, String[] Numbers, String[] usernames)
{
super();
this.ctx_invitation = ctx_invitation;
listComments = comments;
listNumbers = Numbers;
listUsernames = usernames;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#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 v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}

overwrite the values of the adapter you have implemented or add setters for them. Then set the values and make sure you call notifyDatasetChanged on the adapter.
You can either reference the adapter directly if it is a global variable or pass it in the constructor of your AsyncTask

In onPostExecute you can create a new BaseAdapter with the new data and then use setAdapter to set it as the adapter for your ListView. Or, as already said, you can use setters to update data in your current adapter and then notify the ListView that it should redraw itself.
By the very nature of AsyncTask you can update your UI wherever you want in onPreExecution, onProgressUpdate and onPostExecution.

Related

Show the Elements from ArrayList of map ,in list form in Android

I have a A data stored in ArrayList< HashMap< String, String> > retrieved from JSON
in the form (i.e.)
[{price: =1685 name: =Monographie Der Gattung Pezomachus (Grv.) by Arnold F. Rster}]
And I need to show the all map elements into list form in Android.
I've tried many ways but I'm unable to do it .
Also help me to know about the layouts to use in it
EDITED:
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(myarr_list);
setListAdapter(adapter);
And in the MySimpleArrayAdapter Class, in Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
LayoutInflator inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
The control does not proceed after this,
MySimpleArrayAdapter Class
public class MySimpleArrayAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> ProductList = new ArrayList<HashMap<String, String>>();
LayoutInflater inflater;
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#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;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl) {
this.ProductList = pl;
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
View myview = convertView;
if (convertView == null) {
myview = inflater.inflate(R.layout.show_search_result, null);
}
TextView price = (TextView) myview.findViewById(R.id.price);
TextView name = (TextView) myview.findViewById(R.id.name);
HashMap<String, String> pl = new HashMap<String, String>();
pl = ProductList.get(position);
//Setting
price.setText(pl.get("price"));
name.setText(pl.get("name"));
return myview;
}
}
I am editing here a onPostExecute class from SearchResultsTask extended by AsyncTask
protected void onPostExecute(JSONObject json) {
if (json != null && json.length() > 0) {
try {
JSONArray json_results = (JSONArray)(json.get("results"));
String parsedResult = "";
System.out.println("-> Size ="+ json_results.length());
for(int i = 0; i < json_results.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_i = json_results.getJSONObject(i);
map.put("name: ",json_i.getString("name") + "\n");
map.put("price: ",json_i.getString("price") + "\n");
arr_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println("-> Size =====arr_llist ="+ arr_list.size());
// CustomListAdapter adapter = new CustomListAdapter (arr_list);
//final StableArrayAdapter adapter = new StableArrayAdapter(this, R.id.result, arr_list);
// listview.setAdapter(adapter);
MyListActivity obj1 = new MyListActivity();
Bundle icicle = null;
obj1.onCreate(icicle);
}
public class MyListActivity extends Activity {
public void onCreate(Bundle icicle) {
// System.out.println("In my list Activity");
// super.onCreate(icicle);
//populate list
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this,arr_list);
// System.out.println("in 2");
adapter.getView(0, listview, listview);
listview.setAdapter(adapter);
}
}
#Override
public int getCount() {
return ProductList.size() ;
}
//Constructor
public MySimpleArrayAdapter( ArrayList<HashMap<String,String>> pl, Context c) {
this.ProductList = pl;
inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
getSystemService() is method of context, you are calling it on instance of adapter.

Unable to Print data in listview in android after Json Parsing

public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
CustomList adapter = new CustomList(this, rowItems);
listView1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
rowItems = new ArrayList<RowItem>();
}
}
}
This my code i am able to display the value after Jason parsing in this line System.out.println(Id + "" + Designation + ""
+ EmployeeName);
But i am unable to print data in Listview there is Error coming while i have created
Datamodel
public class RowItem {
public RowItem(String title, String desc) {
this.title = title;
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private String title;
private String desc;
}
I have create adapter which i s extending from Base adapter that work fine can u please tell me how to bind value and display in list view after Json Parsing please suggest me i m trying to Implement .
Use Custom Adapter for binding your JSON data to your Listview like below :
public class ListViewAdapterForLead extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<SpinnerNavItem> data;
TextView txtText;
public ListViewAdapterForLead(Context context,ArrayList<SpinnerNavItem> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int index) {
return data.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
public View getDropDownView(int position,View convertView,ViewGroup parent){
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_lead, null);
}
txtText = (TextView) convertView.findViewById(R.id.textLeadMenu);
txtText.setText(data.get(position).getTitle());
return convertView;
}
}
bind your values in the getView() method of your custom adapter.
You should set the data after the background task gets completed.
* First try to set list adapter in onPostExecute() method.
* Make sure all the details in your model gets filled.
* Make use of getView() method in your Adapter class to parse the data.
For sample code for ListView with BaseAdapter, refer the below link
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
You forgot one thing,this is why the List is empty
Add the parsed data to your List
//initialize your list here
rowItems = new List<RowItems>();
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
RowItemsr = new RowItems();
Id = _obj.getString("Id");
Designation = _obj.getString("Designation");
EmployeeName = _obj.getString("EmployeeName");
System.out.println(Id + "" + Designation + ""
+ EmployeeName);
// you must create an object and add it to your list
r.setTitle(EmployeeName);
r.setDesc(Designation);
rowItems.add(r);
}
This is what you need

Blank listview getting in android

public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
DataModel datamodel = new DataModel();
ArrayList<DataModel> list = new ArrayList<DataModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
if (Id != null) {
datamodel.setId(_obj.getString("Id"));
}
if (Designation != null) {
datamodel.setDesignation(_obj.getString("Designation"));
}
if (EmployeeName != null) {
datamodel.setEmployeeName(_obj
.getString("EmployeeName"));
}
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
}
public class DataModel implements Parcelable {
private String Id = "";
private String Designation = "";
private String EmployeeName = "";
public String getId() {
return Id;
}
public void setId(String id) {
this.Id = id;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
this.Designation = designation;
}
public String getEmployeeName() {
return EmployeeName;
}
public void setEmployeeName(String employeeName) {
this.EmployeeName = employeeName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public DataModel() {
// TODO Auto-generated constructor stub
}
public DataModel(Parcel in) {
Id = in.readString();
EmployeeName = in.readString();
Designation = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(Id);
dest.writeString(EmployeeName);
dest.writeString(Designation);
}
}
public class CustomList extends BaseAdapter {
Context context;
private ArrayList<DataModel> arrModel;
public CustomList(Context context, ArrayList<DataModel> arrModel) {
this.context = context;
this.arrModel = arrModel;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView locationimage;
ImageView roleimageview;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.settingrowitem, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView
.findViewById(R.id.rowcontact_txtName);
holder.txtTitle = (TextView) convertView
.findViewById(R.id.rowcontact_txtrole);
holder.locationimage = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.roleimageview = (ImageView) convertView
.findViewById(R.id.imageView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(arrModel.get(position).getEmployeeName());
holder.txtTitle.setText(arrModel.get(position).getDesignation());
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
}
else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
return convertView;
}
#Override
public int getCount() {
return arrModel.size();
}
#Override
public Object getItem(int position) {
return arrModel.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
There are three class which I have use to parse data from from web service and and trying to print in Listview .I am able to do Json parsing and getting data from server insetting.javaclass:
list.add(datamodel);
and bind this in list in onpostexcute method:
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
Using this i am trying to print data in listview item but I am getting blank value in each item while Number Json is 49 and i am getting that 49 but getDesignation and getEmploye I am getting blank value please check and tell me where I am doing mistake I have tried much unable to get Print that value please check suggest me
Where are you inistailizind the Id,Designation and EmployeeName, it will be null itself. so doInBackground wont add any datamodel. remove the check
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
DataModel datamodel = new DataModel();
JSONObject _obj = _jarray.getJSONObject(i);
datamodel.setId(_obj.getString("Id"));
datamodel.setDesignation(_obj.getString("Designation"));
datamodel.setEmployeeName(_obj.getString("EmployeeName"));
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
Initialise the model inside the for loop and try once.
To identify changes in your list item you should call
adapter.notifyDataSetChanged();
call it before setting adapter to list view.

adding data to existing listview

I have created listview using the following code
public class homeScreen extends Activity{
ArrayList<SingleRow> list;
boolean flag = false;
String space = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
final Context c = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
//putting actual values in array
list = new ArrayList<SingleRow>();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
int[] images = {R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i = 0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
final ListView list1 = (ListView)findViewById(R.id.spacelist);
final MySimpleAdapter adapter = new MySimpleAdapter(this,list);
list1.setAdapter(adapter);
space = getIntent().getStringExtra("spaceName");
if(null! = space){
adapter.addView(space);
}
list1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
if((titles[position]).equalsIgnoreCase("My Ideas")){
Intent i = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(i);
} else if((titles[position]).equalsIgnoreCase("Create New Space")){
Intent i = new Intent(homeScreen.this, createNewSpace.class);
startActivity(i);
}
}
});
}
}
Row class:
class SingleRow{
String title;
int image;
public SingleRow(String title,int image) {
this.title = title;
this.image = image;
}
}
Adapter:
class MySimpleAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
private Context context;
public MySimpleAdapter(Context c,ArrayList<SingleRow> list) {
this.context = c;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void addView(String space) {
int rows = this.getCount();
list.add(rows, new SingleRow(space,R.drawable.ic_launcher));
notifyDataSetChanged();
}
#Override
public View getView(int i, View view, ViewGroup viewgroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row,viewgroup,false);
TextView title = (TextView)row.findViewById(R.id.label);
ImageView image = (ImageView)row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
image.setImageResource(temp.image);
return row;
}
}
code for create new space
public class createNewSpace extends Activity{
Button add;
TextView sname,pname;
ListView plist;
int success;
Jparser jsonParser = new Jparser();
JSONObject json;
private ProgressDialog pDialog;
ArrayList<String> usersList;
ArrayList<String> spaceUsers;
private static String url_users = "http://10.0.2.2/phpdata/getting_allusers.php";
private static String url_create_space = "http://10.0.2.2/phpdata/create_space.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERS = "users";
private static final String TAG_UNAME = "firstName";
// products JSONArray
JSONArray users = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.createnewspace);
sname=(TextView)findViewById(R.id.spaceName);
pname=(TextView)findViewById(R.id.participents);
plist=(ListView)findViewById(R.id.participantlist);
add=(Button)findViewById(R.id.button1);
// Hashmap for ListView
usersList= new ArrayList<String>();
spaceUsers=new ArrayList<String>();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new getAllUsers().execute();
}
});
plist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String users[]=usersList.toArray(new String[usersList.size()]);
Toast.makeText(getApplicationContext(), "User "+users[arg2]+ " added to space "+sname.getText(), Toast.LENGTH_SHORT).show();
spaceUsers.add(users[arg2]);
}
});
// Loading users in Background Thread
}
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menuspace, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return MenuChoice(item);
}
private boolean MenuChoice(MenuItem item)
{
switch(item.getItemId())
{
case R.id.create:
new createSpace().execute();
return true;
}
return false;
}
class createSpace extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
for(int i=0;i<spaceUsers.size();i++)
{
String sname1 = sname.getText().toString();
String uname = spaceUsers.get(i);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sname", sname1));
params.add(new BasicNameValuePair("uname", uname));
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(url_create_space,
"POST", params);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully inserted user details
Intent is = new Intent(getApplicationContext(), homeScreen.class);
is.putExtra("spaceName", sname1);
startActivity(is);
// closing this screen
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
class getAllUsers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON Object
json = jsonParser.makeHttpRequest(url_users,"GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// getting value of success tag
try {
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
// Getting Array of users
try{
JSONArray users=json.getJSONArray(TAG_USERS);
// looping through All Products
for (int i = 0; i < users.length(); i++) {
Log.d("check", "success");
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_UNAME);
Log.d("name....",name);
// adding HashList to ArrayList
usersList.add(name);
}
} catch(JSONException e)
{
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
plist.setAdapter(new ArrayAdapter<String>(createNewSpace.this,android.R.layout.simple_list_item_1,usersList));
}
});
}
}
}
Now I want to add Item to this existing list.
I am taking data from another activity using intent.
Now one item get added.but next time that get replaced.
Please Help.
Thank you in advance.
You should move the creation of the data outside of the adapter:
list=new ArrayList<SingleRow>();
//putting actual values in array
Resources res=c.getResources();
String[] titles=res.getStringArray(R.array.titles);
int[] images={R.drawable.error,R.drawable.ic_launcher,R.drawable.ic_launcher};
//putting single row in arraylist
for(int i=0;i<3;i++){
list.add(new SingleRow(titles[i], images[i]));
}
Pass the list variable to the adapter and store a reference to it there. Then you can just update the data in the list variable, and call notifyDataSetChanged() on your adapter.
Edit: It seems you want to store the space values, and then retrieve them in the HomeScreen activity later. If I understand the flow of your app correctly, then the createNewSpace class should store the space in SharedPreferences. Then in the HomeScreen activity you should retrieve those from the SharedPreferences, and show them.
You can add data to the adapter and call notifyDataSetChanged().Alternatively, You can create a new adapter and listView.setAdapter(adapter) that adapter.

Populating Gridview from JSON response

I am trying to populate Grid View from JSON response received from Async Task. Below is the activity file
public class OpenTableActivity extends Activity implements AsyncResponse{
String serUri, method;
OpenTableAdapter op;
WebServiceAsyncTask webTask = new WebServiceAsyncTask(this);
ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_table);
getTables();
webTask.listener = this;
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new OpenTableAdapter(this,tableList));
LinearLayout layout = (LinearLayout) findViewById(R.id.opentableLinear);
layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent ev) {
hideKeyboard(view);
return false;
}
});
Button btn = (Button) findViewById(R.id.table_home_btn);
btn.setOnClickListener(homeBtn);
}
public boolean getTables() {
serUri = "tables.json";
method = "get";
WebServiceAsyncTask webServiceTask = new WebServiceAsyncTask(OpenTableActivity.this);
webServiceTask.execute(serUri, method, this);
return true;
}
#Override
public void WriteJsonArray(JSONArray result) {
// TODO Auto-generated method stub
try {
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String tabLabel = c.getString("tablabel");
String tabStatus = c.getString("tabstatus");
HashMap<String, String> map = new HashMap<String, String>();
map.put("table_name", tabLabel);
map.put("table_status", tabStatus);
tableList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
The Adapter class to fill grid view is as below
public class OpenTableAdapter extends BaseAdapter {
private Context mContext;
String orderNumber;
OpenTableActivity openInstance;
String tableLabel;
String tableStatus;
LayoutInflater mInflater;
ArrayList<HashMap<String, String>> tablist = null;
public OpenTableAdapter(Context c, ArrayList<HashMap<String, String>> tablelist ) {
// TODO Auto-generated constructor stub
mContext = c;
mInflater = LayoutInflater.from(c);
tablist = tablelist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
openInstance = new OpenTableActivity();
return openInstance.tableList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.button,
parent, false);
holder = new ViewHolder();
holder.btn = (Button) convertView.findViewById(R.id.button);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Button btn = (Button) view.findViewById(R.id.button);
HashMap<String, String> map = tablist.get(position);
for (java.util.Map.Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
holder.btn.setText(key);
return convertView;
}
static class ViewHolder
{
Button btn;
}
}
the interface class defined is as below:
public interface AsyncResponse {
public void WriteJsonArray(JSONArray tableList);
}
The Async task class is as below
public class WebServiceAsyncTask extends AsyncTask<Object,Void,JSONArray> {
AsyncResponse listener;
public WebServiceAsyncTask(){}
public WebServiceAsyncTask(Context appcontext)
{
this.context=appcontext;
listener = (AsyncResponse) this.context;
}
String serviceUrl;
OpenTableActivity openInstance=new OpenTableActivity();
CategoryActivity catAct;
private static JSONArray json = null;
private Context context = null;
private static JSONObject jsonObject = null;
protected JSONArray doInBackground(Object... params) {
// TODO Auto-generated method stub
serviceUrl = (String) params[0];
String method = (String) params[1];
final HTTPHelper httph = new HTTPHelper(serviceUrl,context);
json = httph.fetch();
return json;
}
#Override
protected void onPostExecute(JSONArray result) { // invoked on the ui thread
// TODO Auto-generated method stub
// dismiss progress dialog
// update ui here
super.onPostExecute(result);
if (listener != null){
listener.WriteJsonArray(result);
}
}
On running this I am getting Stackoverflow error as soon as activity class is called. I tried many different options but still same error. Not sure what I am missing as unable to debug too as its giving error even before entering the activity class. Please advise. Thanks.
Posting solution. From the discussion
You need to move the below to WriteJsonArray. Once you get the data you need to pass the same to the adapter class
gridview.setAdapter(new OpenTableAdapter(this,tableList));
Replace your getCount by
#Override
public int getCount() {
return tablist.size();
}
In getview remove your for loop
HashMap<String,String> map = tablist.get(position);
String value = map.get("key");
// make sure the key i right. "key" here is only an example. replace with right key
holder.btn.setText("value");
remove this
WebServiceAsyncTask webTask = new WebServiceAsyncTask(this); // at the beginnning
remove this from asynctask
OpenTableActivity openInstance=new OpenTableActivity();
AsyncTask<Void, Void, Boolean> waitForCompletion = new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Void... params) {
}
#Override
protected void onPostExecute(Boolean result) {
}
}

Categories

Resources