简体   繁体   中英

Android: how to restart a method with a button click

I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results. Here is my code. Can any of you smart folks please help me.

package com.app.simplictyPortal;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.app.simplicityPortal.adapter.InvoiceAdapter;

import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;



public class InvoiceFragment extends Fragment {
    public InvoiceFragment(){}
    Button load;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
        ArrayList<String> years = new ArrayList<String>();
        int thisYear = Calendar.getInstance().get(Calendar.YEAR);
        int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
        for (int i = 2013; i <= thisYear; i++)
        {
            years.add(Integer.toString(i));
        }

        //String tmonth = Integer.toString(currentMonth);
        String tyear = Integer.toString(thisYear);
        final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
        final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_spinner_item, years);



        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // Apply the adapter to the spinner
        year.setAdapter(adapter);
        year.setSelection(adapter.getPosition(tyear));

        ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
                R.array.month, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        month.setAdapter(adapter2);
        month.setSelection(currentMonth);
        load=(Button)rootView.findViewById(R.id.button1);
        load.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String y = (String) year.getSelectedItem();
                int im = month.getSelectedItemPosition();
                String m =  Integer.toString(im +1);

                final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();

                final String Compid = globalVariable.getCompid();
                new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);

            }
        }); 


        return rootView;

    }


    public void invoice(JSONArray jArray) {

        ListView lv = (ListView) getView().findViewById(R.id.listView1);
        List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
        try {
            for (int i = 0; i <jArray.length(); i++) { 
                final JSONObject json_data = jArray.getJSONObject(i);
                    items.add(new ListViewItem()
                    {{
                        Vendor=  json_data.optString("CarrierName");
                        Bill =  "$ " + json_data.optString("BillAmount");
                        Serviceacct = json_data.optString("ServiceAccountNumber");
                        Date = json_data.optString("ReceivedDate");                     
                    }});


                }


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();


}




        InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
        lv.setAdapter(adapter);


        // TODO Auto-generated method stub

    }


public class ListViewItem
{

    public String Vendor;
    public String Bill;
    public String Serviceacct;
    public String Date;

}   public static String GET(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}


public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        return GET(urls[0]);

    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        try {
            JSONArray jArray = new JSONArray(result);

                invoice(jArray);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

    }

}

}


    }

How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?

Maybe the sample below will help you.

First, implement AsyncTask class with callback interface:

public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {

public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
    mFragment = fragment;
    mRequest = request;
}

public interface OnServerRequestAsyncTaskCompletedListener {
    void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}

public void cancel() {
    if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
    cancel(true);
}

And also add onPostExecute():

@Override
protected void onPostExecute(ServerResponseDetails response) {
    if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}

I call AsyncTask from Fragment, but you can use it with Activity instead. Then, in your Activity you implement interface:

@Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
    // do what you need here, then 'finish' task by setting mServerRequest to null
    mServerRequest = null;
}

And to execute AsyncTask:

protected ServerRequestAsyncTask mServerRequest = null;

public boolean isServerRequestRunning() {
    return (mServerRequest != null);
}

public void cancelServerRequest() {
    mServerRequest.cancel();
}

public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
    if (Application.isNetworkAvailable()) {
        if (!isServerRequestRunning()) {
            mServerRequest = new ServerRequestAsyncTask(fragment, request);
            mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                    {params});
        }
    }
}

mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.

Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.

@Override
    protected void onPostExecute(String result) {
        try {
            JSONArray jArray = new JSONArray(result);

                invoice(jArray);
                cancel(true);
                isCancelled();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM