Android ListView Updated by AsyncTaskLoader - android

I'm populating a ListView from DB. The recordset from the DB contains the Zipcode which is then transformed into City and State using google map api and then set to Listview Item.
I need to be able to set the value that is being returned from the background class in Listview. Any guidance would be very much appreciated. Thanks in advance.
for (int i = 0; i < zipcodes.getLength(); i++) {
GetCityStateInfoFromPostalCode getCityStateInfoFromPostalCode = new GetCityStateInfoFromPostalCode(getActivity(), "110001", "ta");
String mCityState = getCityStateInfoFromPostalCode.getCityState();
}
Here's Background Class that fetches the info from Google maps api
public class GetCityStateInfoFromPostalCode extends AsyncTaskLoader<String> {
private String URL;
private String mState = "";
private String mCity = "";
private Context mContext;
public String getCityState() {
return mCityState;
}
private String mCityState = "";
public GetCityStateInfoFromPostalCode(Context context, String postalCode, String language) {
super(context);
this.mContext = context;
URL = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:" + postalCode + "&language=" + language;
// Kick start the load process
forceLoad();
}
public String loadInBackground() {
JSONObject jsonObject;
JSONArray jsonRootArray;
JSONArray jsonAdressArray;
JSONObject addressComponentCityObject;
JSONObject addressComponentStateObject;
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
httpGet.addHeader("content-type", "application/json");
try {
HttpResponse resp = client.execute(httpGet);
String json = EntityUtils.toString(resp.getEntity(), "UTF-8");
jsonObject = new JSONObject(json);
addressComponentCityObject = new JSONObject();
addressComponentStateObject = new JSONObject();
jsonRootArray = jsonObject.getJSONArray("results");
//This points to "0"
JSONObject rootJson = jsonRootArray.getJSONObject(0);
//This points to address components
jsonAdressArray = rootJson.getJSONArray("address_components");
//This points to Object 1 (Second object of the jsonAddressArray)
addressComponentCityObject = jsonAdressArray.getJSONObject(1);
mCity = addressComponentCityObject.getString("long_name");
addressComponentStateObject = jsonAdressArray.getJSONObject(3);
mState = addressComponentStateObject.getString("long_name");
} catch (Throwable t) {
// Handle error here
t.printStackTrace();
}
this.mCityState = mCity + ", " + mState;
return mCityState;
}
}

with AsyncTask you can generate and override the methods below :
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
I hope this will help you :)

Related

how to add OnScrollListener in my below code

It's been a while since I have been using android. can you please tell me how to add OnScrollListener in this code ? Everytime I scroll down I want to fetch 5 more images.
This is the Asyncatask its working correct, but I need fetch 5 image everytime I scroll down(load more).
public class RecyclerOkHttpHandler extends AsyncTask<String, Void, String> {
private Context mContext;
private MyInterface mListener;
public String category;
public String basestart;
public String limitend;
public RecyclerOkHttpHandler(Context context, MyInterface mListener, String categ, String base, String limit){
mContext = context;
this.mListener = mListener;
category=categ;
basestart=base;
limitend=limit;
}
public interface MyInterface {
public void myMethod(ArrayList result);
}
private final String Fetch_URL = "http://justedhak.com/old-files/Recyclerview_data.php";
// ArrayList<Listitem> Listitem;
ArrayList<CategoryList> Listitem;
int resulta;
OkHttpClient httpClient = new OkHttpClient();
ListView list;
String myJSON;
JSONArray peoples = null;
InputStream inputStream = null;
#Override
protected String doInBackground(String... params) {
Log.d("okhttp Fetch_URL", Fetch_URL);
RequestBody formBody = new FormEncodingBuilder()
.add("category", category)
.add("base", basestart)
.add("limit", limitend)
.build();
Request request = new Request.Builder()
.url(Fetch_URL)
.post(formBody)
.build();
String result = null;
try {
Response response = httpClient.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
inputStream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
resulta = 1; //"Success
// return response.body().bytes();
} catch (Exception e) {
Toast.makeText(mContext, "Connection failed, check your connection",
Toast.LENGTH_LONG).show();
e.printStackTrace(); }
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
if( resulta ==1){
myJSON=result;
Log.e("result",result);
showList();
}
else{
Log.e("d","there is an error on postexecute in okhhttphandler.java");
}
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println("Length:"+peoples.length());
int J_length=peoples.length()-1;
//JSONObject maxj = peoples.getJSONObject(peoples.length() - 1);
// max of arrray
jsonObj= peoples.getJSONObject(J_length);
String j_id= jsonObj.getString("id");
int _id = Integer.parseInt(j_id);
System.out.println(j_id);
//max of
DatabaseHandler db = new DatabaseHandler(mContext);
String db_id="";
db_id = db.getmax();
if (db_id== null)
{
db_id="0";
}
int d_id = Integer.parseInt(db_id);
Log.e("db_id", db_id);
Log.e("j_id",j_id);
// if (_id < d_id) {
System.out.println("Getting json result ");
Listitem = new ArrayList<CategoryList>();
for (int i = 0; i < peoples.length(); i++) {
JSONObject c = peoples.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
Listitem.add(new CategoryList(id, url));
}
if (mListener != null)
mListener.myMethod(Listitem);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the when I set the adapter
private String base = "0";
private String limit = "5";
final RecyclerOkHttpHandler handler = new RecyclerOkHttpHandler( this, new RecyclerOkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
mAdapter_first = new MyAdapter(result,SearchActivity.this);
mAdapter_first.notifyDataSetChanged();
mRecyclerView_first.setAdapter(mAdapter_first);
}
},"girls jokes",base,limit);
try {
handler.execute().get();
} catch (Exception e) {
Log.d("SearchActivity error", "error in mRecyclerView_first");
e.printStackTrace();
}
For the first load, call your RecyclerOkHttpHandler AsyncTaskto get your first 5 items.
Now, for any further load, all you have to do is to check if the listView is scrolled to its bottom and you can refer to this link Find out if ListView is scrolled to the bottom? to know how to deal with it.
So, each time you detect that the user has scrolled the listview to the bottom, it's time to call the RecyclerOkHttpHandler AsynTask to get the 5 new images.
PS: You need to save the limit you have reached in each load, so that in the next load, you start loading from that limit.
Hope this helps :)

Show data from world weather online api

I am developing weather application by using world weather online API
for android.How i show data in application? data is showing in logcat.Following is my code.
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// adding contact to contact list
dataList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
}
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
First of all, this format will refer to the V1 free version. World Weather Online has released v2, which is superior. I was in the process of updating and saw this question sitting out there so I'll answer based off of what I had that did work.
You are on the right track to use the AsyncTask, here is my call to AsyncTask. You should know I use my "DataPoint" class to simply contain the data from WWO that I need to use. Based on your question, you can show the data that I will put in the DataPoint object in anyway you see fit on the screen, since at the end of the queryWeatherService(), you will end up with a parsed set of data.
//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{
// This method will retrieve the data from the weather service
DataPoint newDataPoint = new DataPoint();
if (!waiting)
{
try{
newDataPoint = new WeatherServiceClass().execute(
String.valueOf(getlatitude()), //Not shown here: pass in some String of a float value of of your lat coordinate.
String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
.get();
} catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
return newDataPoint;
// Documentation:
// https://developer.worldweatheronline.com/page/documentation
}
The WeatherServiceClass that extends the AsyncTask
public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
private String latitude;
private String longitude;
public WeatherServiceClass() {
}
#Override
protected DataPoint doInBackground(String... params) {
DataPoint dp = new DataPoint();
JSONWeatherParser jparser = new JSONWeatherParser();
latitude = params[0];
longitude = params[1];
String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
try {
dp = jparser.getWeather(data);
} catch (JSONException e) {
e.printStackTrace();
}
return dp;
//Reference:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
}
}
Here is the WeatherHttpClient class:
public class WeatherHttpClient {
private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";
public String getWeatherData(String latitude, String longitude){
HttpURLConnection con = null;
InputStream is=null;
try{
con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//Reading the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line=br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close();} catch(Throwable t){}
try { con.disconnect();} catch(Throwable t){}
}
return null;
}
Finally, here is my JSONWeatherParser:
public class JSONWeatherParser {
public JSONWeatherParser() {
}
public DataPoint getWeather(String data) throws JSONException {
DataPoint dp = new DataPoint();
Weather weather = new Weather(); //This is just a class that has a bunch of strings in it for the weather info.
JSONObject jObj = new JSONObject(data);
//Parsing JSON data
JSONObject dObj = jObj.getJSONObject("data");
JSONArray cArr = dObj.getJSONArray("current_condition");
JSONObject JSONCurrent = cArr.getJSONObject(0);
weather.setCurrent_temp(getString("temp_F",JSONCurrent));
weather.setHour(getString("observation_time",JSONCurrent));
JSONArray jArr = dObj.getJSONArray("weather");
JSONObject JSONWeather = jArr.getJSONObject(0);
JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
JSONObject JSONIcon = jArrIcon.getJSONObject(0);
weather.setDate(getString("date",JSONWeather));
weather.setPrecipmm(getString("precipMM",JSONWeather));
weather.setTempMaxc(getString("tempMaxC",JSONWeather));
weather.setTempMaxf(getString("tempMaxF",JSONWeather));
weather.setTempMinf(getString("tempMinF",JSONWeather));
weather.setTempMinc(getString("tempMinC",JSONWeather));
weather.setWeatherCode(getString("weatherCode",JSONWeather));
weather.setWeatherIconURL(getString("value",JSONIcon));
weather.setWinddir16point(getString("winddir16Point",JSONWeather));
weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
// For details of these operations and how each works go here:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
return dp;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
}

How to return an arraylist/list generated in an AsysnTask

I am trying to implement an google map app that will store the google marker on the cloud database. But I have a problem to get back the coordinate of the marker on the cloud.
How do I return a List generated in an AsyncTask back to a custom java class? The problem that I have encountered right now is when I initialize a Alistener class in different class, for example, in class B:
AListener a = new Alistener( ..., ... );
...
a.getMarkerData();
List<Pair> myList = a.getList();
myList is just null, and I think because the a.getList() has executed before the data is fetched back from that cloud database in onPostExecute(). Any insight will help a lot.
This is my java class:
public class AListener {
protected static final String TAG = null;
double lat, lon;
List<Pair> myList = new ArrayList<Pair>();
CustomMarkerListener( double lat, double lon ) {
this.lat = lat;
this.lon = lon;
}
public void getMarkerData() {
MarkerDataInfo ms = new MarkerDataInfo();
ms.execute( UserLogin.ITEM_URI );
}
public void setList(List<Pair> myList ) {
this.myList = myList;
}
public List<Pair> getList() {
return this.myList;
}
}
And this is my AsyncTask an inner class of AListener:
private class MarkerDataInfo extends AsyncTask<String, Void, List<Pair>> {
List<Pair> list;
private CustomMarkerListener mLis;
public MarkerDataInfo() {}
public MarkerDataInfo( CustomMarkerListener mLis ) {
this.mLis = mLis;
}
#Override
protected List<Pair> doInBackground(String... url) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet( UserLogin.ITEM_URI);
list = new ArrayList<Pair>();
try {
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Log.d(TAG, data);
JSONObject myjson;
try {
myjson = new JSONObject(data);
JSONArray array = myjson.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String markerOfUser = obj.get("marker").toString();
if( markerOfUser.equals( UserLogin.accountName )) {
String latname = obj.get("lat").toString();
String lonname = obj.get("lon").toString();
double latData = Double.parseDouble(latname);
double lonData = Double.parseDouble(lonname);
list.add( new Pair( latData, lonData ));
}
}
} catch (JSONException e) {
Log.d(TAG, "Error in parsing JSON");
}
} catch (ClientProtocolException e) {
Log.d(TAG, "ClientProtocolException while trying to connect to GAE");
} catch (IOException e) {
Log.d(TAG, "IOException while trying to connect to GAE");
}
return list;
}
protected void onPostExecute(List<Pair> list) {
super.onPostExecute(list);
mLis.setList( list );
Log.d("CUstome", "" + list.size());
}
}
If only one request is active at any time, you can use singleton pattern for your 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