asynctask中的赋值在其他函数中显示null

时间:2018-06-07 10:45:10

标签: android

我已经在json的asynctask中分配了字符串值,但它在onclick函数中显示为null值。这是我的字符串变量声明

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {


    String due,total;

这是我在json

的asynctask中指定的字符串值total
JSONObject jsonObject = new JSONObject(str);
                    JSONArray jsonArray = jsonObject.getJSONArray("result");

                    for(int i=0; i< jsonArray.length(); i++)
                    {
                        JSONObject jo = jsonArray.getJSONObject(i);
                        total = jo.getString("due");

在此类total中分配为&#34; name1&#34;并且还在println中显示结果为logcat。但是当我在onclicklistener函数中将此值赋给其他字符串变量时,其println结果显示为null

这是我的完整活动代码

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private Spinner sname;
    private EditText txtamount;
    private ArrayList<String> names;
    private ArrayAdapter<String> sdap;
    String amount,mem,due,total;
    TableLayout tableLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        names = new ArrayList<String>();
        tableLayout = findViewById(R.id.tblLoan);
        sname = findViewById(R.id.spnMem);
        sname.setOnItemSelectedListener(this);
        txtamount = findViewById(R.id.txtLonCr);
        Getdata getdata = new Getdata();
        getdata.execute();
        sdap = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_spinner_item, names);
        sdap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sname.setAdapter(sdap);
    }



    protected class Getdata extends AsyncTask<Void,Void,Void>
    {
        private String jsonurl;
        private  String str;

        @Override
        protected  void onPreExecute()
        {

            jsonurl="http://10.0.2.2/dwnloandata.php";

        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                tableLayout.removeAllViews();
                URL url = new URL(jsonurl);
                HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                StringBuilder json = new StringBuilder();
                while ((line = bufferedReader.readLine())!= null)
                {
                    json.append(line).append('\n');
                    str=json.toString();

                }


                if (str != null){

                    JSONObject jsonObject = new JSONObject(str);
                    JSONArray name = jsonObject.getJSONArray("result");

                    for (int i=0; i< name.length(); i++)
                    {
                        JSONObject jo= name.getJSONObject(i);
                        names.add(jo.getString("name"));
                        TableRow raw = new TableRow(MainActivity.this);
                        TableRow.LayoutParams lp = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
                        raw.setLayoutParams(lp);
                        raw.setId(i+1);
                        TextView nm = new TextView(MainActivity.this);
                        nm.setWidth(650);
                        nm.setHeight(250);
                        nm.setTextSize(20);
                        nm.setText(jo.getString("name"));
                        TextView amnt = new TextView(MainActivity.this);
                        amnt.setTextSize(20);
                        amnt.setWidth(600);
                        amnt.setHeight(250);
                        amnt.setTextAlignment(TEXT_ALIGNMENT_CENTER);
                        amnt.setText(jo.getString("due"));
                        tableLayout.addView(raw);
                        raw.addView(nm);
                        raw.addView(amnt);
                    }}



                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();

            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            sdap.notifyDataSetChanged();
        }
    }



    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        String item = parent.getItemAtPosition(position).toString();
        mem=item;

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    private class MembersLoan extends AsyncTask<String,Void,String> {
        private String jsonurl,str;

        @Override
        protected void onPreExecute()
        {
            jsonurl = "http://10.0.2.2/dwnsingleloandata.php";
        }
        @Override
        protected String doInBackground(String... strings) {
            String member = strings[0];

            try {
                URL url = new URL(jsonurl);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                String post_data = URLEncoder.encode("name","UTF-8") + "=" + URLEncoder.encode(member,"UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String line;
                StringBuilder jaon = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null)
                {
                    jaon.append(line).append("\n");
                    str = jaon.toString();
                }

                if( str != null)
                {
                    JSONObject jsonObject = new JSONObject(str);
                    JSONArray jsonArray = jsonObject.getJSONArray("result");

                    for(int i=0; i< jsonArray.length(); i++)
                    {
                        JSONObject jo = jsonArray.getJSONObject(i);
                        total = jo.getString("due");
                        System.out.println("due==" + total);
                    }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                }
            } catch (JSONException | IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    public void onClick(View view) {
        amount = txtamount.getText().toString();
        due = total;
        LoanCreditInsert loanCreditInsert = new LoanCreditInsert(view.getContext());
        loanCreditInsert.execute(mem,amount);
        MembersLoan membersLoan = new MembersLoan();
        membersLoan.execute(mem);
        System.out.println("Amount=" + amount);
        System.out.println("due=" + due);
        int bdue = Integer.valueOf(due);
        int ade = Integer.valueOf(amount);

        int ldue = bdue - ade;
        String ldu = String.valueOf(ldue);

        LoanInsert loanInsert = new LoanInsert(view.getContext());
        loanInsert.execute(mem,amount,ldu);

        Getdata getdata = new Getdata();
        getdata.execute();

    }
}

2 个答案:

答案 0 :(得分:0)

  

membersLoan.execute(MEM);

在这样的调用之后,你不能拥有代码(使用doInBackground()的结果)。

将以下所有代码放在MenbersLoan的onPostExecute中。

一般情况下:如果使用.execute()启动asynctask,则调用后无法获得更多代码。如果您有“以下代码”,则将该代码放入该任务的onPostExecute()中。

由于你有大约四个/五个asynctasks,你只能在前者的onPostExecute中调用下一个。

有工作要做......只需稍加编辑。

答案 1 :(得分:0)

LoanCreditInsert loanCreditInsert = new LoanCreditInsert(view.getContext());
        loanCreditInsert.execute(mem,amount);
        MembersLoan membersLoan = new MembersLoan();
        membersLoan.execute(mem);

请逐个执行asynctask并尝试。