javaandroidandroid-asynctask

Make a function async/threaded in android


I have an interesting question for you. I have a function in Android that interacts with the ui by loading a listview with data from a remote server. As expected, this makes my app extremely sluggish.

With the minimum amount of code, how do I put this function on its own thread or A Sync Task, while still allowing it to perform like a normal function

It did not be extremely efficient. I just need to do this with the minimum amount of code possible.

try
    {   //getjson file
        HttpClient client = new DefaultHttpClient();  
        HttpGet get = new HttpGet(url);
    HttpResponse responseGet = client.execute(get);  
    HttpEntity resEntityGet = responseGet.getEntity();  

        if (resEntityGet != null) {
            InputStream instream = resEntityGet.getContent();
            BufferedReader str = new BufferedReader(new InputStreamReader(
                    instream));

            String ans = new String("");
            build = new String("");
            while ((ans = str.readLine()) != null) {
                build = build + ans;
            }
        //parse json file   
            JSONObject total = new JSONObject(build);
            JSONArray prices = null;
            if (!total.isNull("title")){
            Prices = title.getJSONArray("title"));}
            ArrayList<data> newArray = new ArrayList<data>();

            for(int i=0;i<Prices.length();i++)
            {
                JSONObject price = null;
                price = Prices.getJSONObject(i);
                data name = new data (price.getString("StoreName"),price.getString("price"),price.getString("Link"));
                newArray.add(name);
            }
            stockArr = new data[newArray.size()];
            stockArr = newArray.toArray(stockArr);
                    //add to listview
            ListView listView = (ListView) findViewById(R.id.mylist);
            listadapter adapter = new listadapter(this,R.layout.listview_item_row, stockArr);
            listView.setAdapter(adapter); 
        }
    } 
    catch(Exception e)
    {
        Toast.makeText(getApplicationContext(),e.toString(), 10).show();
    }

Solution

  • You can put your code for fetching the JSONObject from remote server in the doInBackground() method of AsyncTask class and return that JSONobject from that function. It will get in the onPostExecute() method and there you can parse and load that in to a list view.

    private class myasyncclass extends AsyncTask<String, Void, JSONObject>{
        @Override
        protected JSONObject doInBackground(String... params) {
            //Enter code for fetching value from remote server
            return yourjsonobj;
        }
        @Override
        protected void onPostExecute(JSONObject result) {   
            //Enter code for parsing and create list view
        }
    }