Asynctask wont update array - android

I am having a problem accessing the arraylists populated by this asynctask from class file A. From Class file B I try to use A a method such as
inStream = new InboxLoader(MainInbox.this,1);
Log.e("JJJ",""+inStream.getMemId().size());
method from a different class file I get a crash in logcat saying indexoutofbounds error
I was looking for an alternative to having this AsyncTask in the same file as class B
public class InboxLoader {
Context ctx;
ArrayListmemName,memAvatar,msgBody,msgTime;
ArrayList msgId,memId;
InboxLoader(Context context,int id){
this.ctx = context;
this.msgBody = new ArrayList<String>();
this.memAvatar = new ArrayList<String>();
this.memId = new ArrayList<Integer>();
this.memName = new ArrayList<String>();
this.msgTime = new ArrayList<String>();
this.msgId = new ArrayList<Integer>();
new LoadStream().execute(id);
}
public ArrayList<String> getMsgBody(){
return msgBody;
}
public ArrayList<String> getMemAvatar(){
return memAvatar;
}
public ArrayList<Integer> getMemId(){
return memId;
}
public ArrayList<String> getMemName(){
return memName;
}
public ArrayList<Integer> getMsgId(){
return msgId;
}
public ArrayList<String> getMsgTime(){
return msgTime;
}
/*
* STARTS GRABBING DATA FOR THE LISTVIEW
*/
public class LoadStream extends AsyncTask<Integer, Integer, JSONObject> {
ProgressDialog progressBar;
#Override
protected void onPreExecute() {
progressBar = new ProgressDialog(ctx, ProgressDialog.STYLE_SPINNER);
progressBar.setMessage("Generating Inbox....");
progressBar.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Integer... params) {
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
params2.add(new BasicNameValuePair("memberId", String.valueOf(1)));
params2.add(new BasicNameValuePair("type", "get"));
JSONObject json = new jsonParser().makeRequest("url", params2);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
int success = 0;
JSONObject jData;
JSONArray jObj = null;
try{
// successfully received details
jObj = json.getJSONArray("details"); // JSON Array
success = json.getInt("success");
}catch(Exception e){
e.printStackTrace();
}
if(success == 1){
try{
for( int i = 0; i < jObj.length(); i++ ){
//GET OBJECT FROM JSON Array
jData = jObj.getJSONObject(i);
//ASSIGN VALUES
msgId.add(jData.getInt("msg_id"));
memAvatar.add(jData.getString("mem_avatar"));
memName.add(jData.getString("mem_name"));
memId.add(jData.getInt("mem_id"));
msgBody.add(jData.getString("msg_body"));
msgTime.add(jData.getString("msg_time"));
}
}catch(Exception e){
Log.e("STREAM FILE PROBLEM", e.getMessage());
}
}
progressBar.dismiss();
Log.e("STREAM FILE PROBLEM",""+memId.size());//prints 1
}
}
}

You are trying to read the ArrayList immediately after you start the AsyncTask, while the result will not be available until the doInBackground ends.
You should do what you want in onPostExecute to make sure the task executed all right.
Edited:
Define a listener like below:
public interface RequestListener {
public void onComplete(T response);
}
and the add a field requestListener in InboxLoader:
InboxLoader(Context context,int id, RequestListener li){
this.ctx = context;
this.msgBody = new ArrayList<String>();
this.memAvatar = new ArrayList<String>();
this.memId = new ArrayList<Integer>();
this.memName = new ArrayList<String>();
this.msgTime = new ArrayList<String>();
this.msgId = new ArrayList<Integer>();
this.requestListener = li;
new LoadStream().execute(id);
}
in the onPostExecute add this:
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
int success = 0;
JSONObject jData;
JSONArray jObj = null;
try{
// successfully received details
jObj = json.getJSONArray("details"); // JSON Array
success = json.getInt("success");
if(requestListener!=null)
requestListener.onComplete();
}catch(Exception e){
e.printStackTrace();
}
Then you could process the result in onComplete define in your class B:
inStream = new InboxLoader(MainInbox.this,1, new RequestListener() {
public void onComplete(){
Log.e("JJJ",""+inStream.getMemId().size());
};
});

Related

How to set List Adapter in onPostExecute Asynctask?

Good Day everyone,
I have some problem here. I make a web service call in AsyncTask DoInBackground.
And I wanted to set list adapter, but I got error
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
Now how to set list adapter in post execute or something?
My code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
progressBar = (ProgressBar)findViewById(R.id.prgLoading);
//Initialize the ListView
final ListView lvProf = (ListView)findViewById(R.id.lvProfile);
//call the asynctask cals and add item to the list.
new LoadDataForActivity().execute();
//Set adapter , but i got error here
lvProf.setAdapter(new ListProfileAdapter(this,mItems));
}
private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
progressBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
getAll();
getTotalLeaveBalance();
getMedicalBalance();
return null;
}
#Override
protected void onPostExecute(Void result) {
//here is I add the item to my list (mitems)
try{
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.replace("\\\"", "\"");
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.substring(1, ResponseServiceMedicalBalance.length() - 1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(ResponseServiceMedicalBalance);
String Status = jsonObject.get("Status").toString();
if (Status == "true") {
// JSONArray structure = (JSONArray) jsonObject.get("DataList");
String dataku = jsonObject.get("DataList").toString();
mItems = new ArrayList<ListProfileItem>();
try {
dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
}catch (GeneralSecurityException e){
//handle error - could be due to incorrect password or tampered encryptedMsg
}
JSONParser parser = new JSONParser();
JSONArray structure = (JSONArray) parser.parse(dataku);
for (int i = 0; i < structure.size(); i++) {
JSONObject data = (JSONObject) structure.get(i);
item = new ListProfileItem();
item.claimpostname = data.get("claim_post_name").toString();
String claimamount = data.get("max_limit_per_year").toString();
if (claimamount!=("0.0"))
{
Double amount = Double.parseDouble(claimamount);
DecimalFormat formatter = new DecimalFormat("#,###.00");
String AmountFormatted = formatter.format(amount);
item.claimpostamount = AmountFormatted;
}
else
{
item.claimpostamount = data.get("max_limit_per_year").toString();
}
mItems.add(item);
}
// initialize and set the list adapter
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
There are several ways of solving this, One of the quick and dirtiest is:
Change your AsyncTaskActivity Like this:
private class LoadDataForActivity extends AsyncTask<Void, Void, Void> {
private ListView listView;
private Context context;
public LoadDataForActivity(ListView listView,Context context){
this. listView = listView;
this.context = context;
}
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
progressBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
getAll();
getTotalLeaveBalance();
getMedicalBalance();
return null;
}
#Override
protected void onPostExecute(Void result) {
//here is I add the item to my list (mitems)
try{
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.replace("\\\"", "\"");
ResponseServiceMedicalBalance = ResponseServiceMedicalBalance.substring(1, ResponseServiceMedicalBalance.length() - 1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(ResponseServiceMedicalBalance);
String Status = jsonObject.get("Status").toString();
if (Status == "true") {
// JSONArray structure = (JSONArray) jsonObject.get("DataList");
String dataku = jsonObject.get("DataList").toString();
mItems = new ArrayList<ListProfileItem>();
try {
dataku = ANGGACRYYPT.decrypt(Enc_Pass, dataku);
}catch (GeneralSecurityException e){
//handle error - could be due to incorrect password or tampered encryptedMsg
}
JSONParser parser = new JSONParser();
JSONArray structure = (JSONArray) parser.parse(dataku);
for (int i = 0; i < structure.size(); i++) {
JSONObject data = (JSONObject) structure.get(i);
item = new ListProfileItem();
item.claimpostname = data.get("claim_post_name").toString();
String claimamount = data.get("max_limit_per_year").toString();
if (claimamount!=("0.0"))
{
Double amount = Double.parseDouble(claimamount);
DecimalFormat formatter = new DecimalFormat("#,###.00");
String AmountFormatted = formatter.format(amount);
item.claimpostamount = AmountFormatted;
}
else
{
item.claimpostamount = data.get("max_limit_per_year").toString();
}
mItems.add(item);
}
listView.setAdapter(new ListProfileAdapter(context,mItems));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
And you can call the asyncTask like this:
new LoadDataForActivity(listView,this).execute();
Initialise mItems as
mItems = new ArrayList<>();
Create object for ListProfileAdapter
ListProfileAdapter adapter = new ListProfileAdapter(this,mItems);
lvProf.setAdapter(adapter);
Add items in mItems
mItems.add(item);
After all items added to the list notify the adapter
adapter.notifyDataSetChanged();
move it from onCreate to onPostExecute()
define instance of Adapter as global variable then add Items in doInBackground() & call setAdapter onPostExec.
//Set adapter , but i got error here >> move it to onPostExecute
lvProf.setAdapter(new ListProfileAdapter(this,mItems));
I think the following line should be before setting your adapter,
mItems = new ArrayList<ListProfileItem>();
adapter = new ListProfileAdapter(this,mItems)
lvProf.setAdapter(adapter);
Make the instance variable,
ListProfileAdapter adapter;
instead of putting in the Asynctask. After finishing the asynctask in onPostExecute you also need to run,
adapter.notifyDatasetChanged();

Get an Arraylist from an inner class

I am seeking help so that I may get an ArrayList<String> in an alternate class. As you can see in the following code I have inner and outer classes. Both work as expected and I am both able to insert values and fetch details from my online database using php scripts (I have commented out these details for code clarity as it was taking up a lot of space).
public class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 15000;
public static final String SERVER_ADDRESS = "// my url domain";
public ArrayList<String> list1 = new ArrayList<>();
public ServerRequests(Context context)
{
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please wait..");
}
public void storeDataInBackground(MultiChallenge multiChallenge)
{
progressDialog.show();
new StoreDataAsyncTask(multiChallenge).execute();
}
public class StoreDataAsyncTask extends AsyncTask<Void , Void , Void>
{
MultiChallenge multiChallenge;
public StoreDataAsyncTask(MultiChallenge multiChallenge)
{
this.multiChallenge = multiChallenge;
}
#Override
protected Void doInBackground(Void... voids) {
// where I insert values...
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
super.onPostExecute(aVoid);
Log.d("ServerRequests", "Post execute");
}
}
public ArrayList<String> fetchDataInBackground() {
progressDialog.show();
new FetchDataAsyncTask().execute();
return list1;
}
public class FetchDataAsyncTask extends AsyncTask<Void, Void, ArrayList<String>>
{
public FetchDataAsyncTask()
{
}
String text = "";
#Override
protected ArrayList<String> doInBackground(Void... params) {
InputStream is1;
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(// my url domain+ "// php script");
try {
HttpResponse httpResponse = client.execute(post);
is1 = httpResponse.getEntity().getContent();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(is1, "iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
text += line + "\n";
}
is1.close();
JSONArray data = new JSONArray(text);
for (int i = 0; i < data.length(); i++) {
Log.d("GetNames", data.getString(i));
JSONObject jsonData = data.getJSONObject(i);
list1.add( // I successfully add details to list1 here, I have commented it out for code clarity);
}
for (int iterate = 0; iterate < list1.size(); iterate++) {
Log.d("list1", list1.get(iterate));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
// catch (JSONException e) {e.printStackTrace();}
return list1;
}
#Override
protected void onPostExecute(ArrayList<String> myList) {
progressDialog.dismiss();
super.onPostExecute(myList);
}
}
}
Now that I successfully add to the list1 (I can tell values are added to it because of the for loop with the int iterate), I now need to send it to another class whereby I will put items in a listview. This is my code in the class in which I want to display the details of the ArrayList I get from ServerRequests:
ServerRequests serverRequests = new ServerRequests(DisplayInfo.this);
ArrayList<String> myList = new ArrayList<>();
myList = serverRequests.fetchDataInBackground();
for (int iterate = 0; iterate < myList.size(); iterate++) {
Log.d("Display", myList.get(iterate));
However the above for loop is never called, indicating that myList is never given the details that list1 manages to get in the doInBackground method of class FetchDataAsync.
Please note I did spend a number of hours attempting a variety of my own ideas and answers derived from SO before asking this question. Thank you all in advance of your help.
In the onPostExecute method call a function in the calling class
#Override
protected void onPostExecute(ArrayList<String> myList) {
progressDialog.dismiss();
super.onPostExecute(myList);
MainActivity.sendStrings(myList);
}
In the calling function implement a method:
public static void sendStrings(ArrayList<String> strings)
{
//Add for loop here
}
Alternatively you can also use interfaces. Call the interface in onPostExecute and implement the interface in the calling class

Hashmap size is not constant

I want to retrieve values from a Hash map. When i tried to display the size of a Hashmap in a TextView the size changes in my screen. Any ideas why?
Is there any other way instead of using Hashmap to store the JSONArray so it is more easy to retrieve values?
public void updateJSONdata() {
cafebartablesList = new ArrayList<HashMap<String, Integer>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
cafebartables = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < cafebartables.length(); i++) {
LoadMap ld = new LoadMap();
ld.execute();
JSONObject c =cafebartables.getJSONObject(i);
int tableId = c.getInt(TAG_TABLE_ID);
int tableMarginLeft = c.getInt(TAG_MARGIN_LEFT);
int tableMarginTop = c.getInt(TAG_MARGIN_TOP);
int isFree = c.getInt(TAG_ISFREE);
map = new HashMap<String, Integer>();
map.put(TAG_TABLE_ID, tableId);
map.put(TAG_MARGIN_LEFT, tableMarginLeft);
map.put(TAG_MARGIN_TOP, tableMarginTop);
map.put(TAG_ISFREE, isFree);
cafebartablesList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void printMap() {
mapcounter ++;
length_txt =(TextView)findViewById(R.id.length_txt);
length_txt.setText("the size is " +cafebartablesList.size());
}
public class LoadMap extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
printMap();
}
}
You're method is executing an asynctask that's recursively calling itself, which is probably causing some weird behavior.
Try something like this instead. have your print method call your asynctask. Your asynctask calls updateJSONdata, which iterates over the json object and constructs your map. At the end of your asynctask, update your textview with the size of your map.
public void updateJSONdata() {
cafebartablesList = new ArrayList<HashMap<String, Integer>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
cafebartables = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < cafebartables.length(); i++) {
JSONObject c =cafebartables.getJSONObject(i);
int tableId = c.getInt(TAG_TABLE_ID);
int tableMarginLeft = c.getInt(TAG_MARGIN_LEFT);
int tableMarginTop = c.getInt(TAG_MARGIN_TOP);
int isFree = c.getInt(TAG_ISFREE);
map = new HashMap<String, Integer>();
map.put(TAG_TABLE_ID, tableId);
map.put(TAG_MARGIN_LEFT, tableMarginLeft);
map.put(TAG_MARGIN_TOP, tableMarginTop);
map.put(TAG_ISFREE, isFree);
cafebartablesList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void printMap() {
LoadMap ld = new LoadMap();
ld.execute();
}
public class LoadMap extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
length_txt =(TextView)findViewById(R.id.length_txt);
length_txt.setText("the size is " +cafebartablesList.size());
}
}
}
Otherwise, you could use something like Gson, create a POJO for your cafebartablesList and call
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyPojo.class, new MyDeserializer())
.build();
MyPojo mp = gson.fromJson(json, MyPojo.class);

Why do I get a null pointer exception while issuing a HTTP request using AsyncTask in Android?

I'm trying to get scoreboards from FB, and to achieve this I issue a HTTP request to the API. It has to be done on a separate thread, here is my async task class:
public class AsyncBuildScoreboard extends AsyncTask<Void, Void,String> {
ProgressBar pb;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String token = Session.getActiveSession().getAccessToken();
try{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/"+GameStatic.app_id+"?fields=scores&access_token=" + token);
HttpResponse resp = client.execute(get);
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
return response;
}
catch (IOException e)
{
}
return "";
}
protected void onPostExecute(String response) {
try{
JSONObject res = new JSONObject(response);
JSONObject scores = res.getJSONObject("scores");
JSONArray data = scores.getJSONArray("data");
int len = data.length();
String[] values = new String[len];
for(int i=0;i<len;i++)
{
JSONObject obj = data.getJSONObject(i);
JSONObject user = obj.getJSONObject("user");
String name = user.getString("name");
String score = obj.getString("score");
values[i] = name + " " + score;
GameStatic.scoreboard.add(values[i]);
}
}
catch (JSONException e)
{
}
}
}
GameStatic is an external variable to store what I get from thread. And yet, when doing this:
AsyncBuildScoreboard board = new AsyncBuildScoreboard ();
board.execute();
final ListView listview = (ListView) findViewById(R.id.scorelist);
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, GameStatic.scoreboard);
listview.setAdapter(adapter);
a null pointer exception occurs, which means, that the GameStatic.scoreboard has NOT been filled with the entries I wanted.
What am I doing wrong, any ideas?
I'd be obliged, since I am REALLY pressed on time...
public class AsyncBuildScoreboard extends AsyncTask<Void, Void, Void>
{
public ListView list;
public Context ctx;
public ArrayList<String> scoreboard = new ArrayList <String> ();
public AsyncBuildScoreboard(ListView list, Context context)
{
this.list = list;
this.ctx = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids)
{
Void nothing = null;
String token = Session.getActiveSession().getAccessToken();
try{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://graph.facebook.com/"+GameStatic.app_id+"?fields=scores&access_token=" + token);
HttpResponse resp = client.execute(get);
HttpEntity responseEntity = resp.getEntity();
String response = EntityUtils.toString(responseEntity);
}
catch (IOException e)
{
}
return nothing;
}
protected void onPostExecute(String response) {
try{
JSONObject res = new JSONObject(response);
JSONObject scores = res.getJSONObject("scores");
JSONArray data = scores.getJSONArray("data");
int len = data.length();
String[] values = new String[len];
for(int i=0;i<len;i++)
{
JSONObject obj = data.getJSONObject(i);
JSONObject user = obj.getJSONObject("user");
String name = user.getString("name");
String score = obj.getString("score");
values[i] = name + " " + score;
scoreboard.add(values[i]);
}
}
catch (JSONException e)
{
}
final ArrayAdapter adapter = new ArrayAdapter(ctx,
android.R.layout.simple_list_item_1, scoreboard);
list.setAdapter(adapter);
}
}
you will need to use onPostExecute for showing the score when doInBackground execution complete instead of passing GameStatic.scoreboard just after AsyncTask.execute() because doInBackground always execute in separate thread so it.
you can use AsyncBuildScoreboard class constructor for passing ListView instance and Context from Activity as:
ListView listview;
Context context;
public AsyncBuildScoreboard(ListView listview,Context context){
this.context=context;
this.listview=listview;
}
....
protected void onPostExecute(String response) {
//...your code here..
StableArrayAdapter adapter = new StableArrayAdapter(context,
android.R.layout.simple_list_item_1, GameStatic.scoreboard);
listview.setAdapter(adapter);
}
and change your Activity code as for passing Context :
ListView listview = (ListView) findViewById(R.id.scorelist);
AsyncBuildScoreboard board = new AsyncBuildScoreboard (listview,
Your_Activity.this);
board.execute();
or you can also create callbacks methods using interface which fire when on UI Thread when doInBackground execution complete.see following post for more details:
android asynctask sending callbacks to ui

Is it Possible to add list view in separate class in a android?

In my application, I have created a separate class for AsynchronousTask. From the main class I execute the Asynchronous task class, is it possible to use the list view in Asynchronous task class?
MAIN CLASS
search_items_task = new Search_class();
search_items_task.execute(search_str);
ASYNCHRONOUS TASK CLASS
public class Search_class extends AsyncTask<String, Void, String> {
JSONObject json = new JSONObject();
JSONArray jsonarray;
String viewsubmenuSuccess;
//Activity activity;
ListView search_lv;
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response;
HttpPost post = new HttpPost("http://www.name.in/cakefoodnew/customer/submenus");
post.setHeader("json", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
// get a data
InputStream in = response.getEntity().getContent();
String a = convertStreamToString(in);
// Log.v("Search", ""+a);
try {
jsonarray = new JSONArray("[" + a + "]");
json = jsonarray.getJSONObject(0);
String menus = json.getString("submenus");
viewsubmenuSuccess = json.getString("viewsubmenuSuccess");
// Log.v("Search", ""+a);
try {
jsonarray = new JSONArray(menus);
for (int ij = 0; ij < jsonarray.length(); ij++) {
json = jsonarray.getJSONObject(ij);
String name = json.getString("submenu");
if (name.toLowerCase().contains(params[0].toLowerCase())) {
String id = json.getString("submenu_id");
String price = json.getString("submenu_price");
String avaliable_quantity = json.getString("submenu_stock");
HashMap<String, String> map = new HashMap<String, String>();
map.put(MENU_ID, id);
map.put(MENU_NAME, name);
map.put(MENU_PRICE, price);
map.put(MENU_STOCK, avaliable_quantity);
search_details.add(map);
//Log.v("search_details", ""+search_details);
}
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return viewsubmenuSuccess;
}
protected void onPostExecute(String result) {
if (viewsubmenuSuccess.equalsIgnoreCase("1")) {
//search_lv = (ListView)activity.findViewById(R.id.search_list_view);
//Order_page_custom for customized list view
/*Order_page_custom adapter = new Order_page_custom(activity,search_details);
search_lv.setAdapter(adapter);*/
}
}
Yes, Make a Constructor of Search_Class AsyncTask with ListView and Context parameter. Define ListView in onCreate() of Your activity after setContentView() and then Call AsyncTask..
Something Like;
Context mContext
ListView search_lv;
public Search_class(Context context, ListView list)
{
mContext = context;
search_lv = list;
}
Now in
protected void onPostExecute(String result) {
if (viewsubmenuSuccess.equalsIgnoreCase("1")) {
Order_page_custom adapter = new Order_page_custom(mContext,search_details);
search_lv.setAdapter(adapter);
}
}
And in Main Class (Activity Class)
setContentView(R.layout.<activity_layout>);
search_lv = (ListView)findViewById(R.id.search_list_view);
search_items_task = new Search_class(this, search_lv);
search_items_task.execute(search_str);

Categories

Resources