在android

时间:2016-05-26 07:57:30

标签: java android listview arraylist

这是我写的代码: -

    package com.example.hp.applood;

    import java.io.IOException;
    import java.util.ArrayList;

    public class aa extends AppCompatActivity {

    int CONNECTION_TIMEOUT = 1000 * 15;
    ProgressDialog progressDialog;
    String SERVER_ADDRESS = "http://xxxxxxxxx/";

      public aa(Context context) {

        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("Processing..");
        progressDialog.setMessage("Please wait");
    }

     ArrayList<User> userlist;
      MyCustomAdapter dataAdapter = null;

    Spinner s11 = (Spinner) findViewById(R.id.spinner);
    Spinner s2 = (Spinner) findViewById(R.id.spinner2);
    String bloodd = s11.getSelectedItem().toString();
    String loc = s2.getSelectedItem().toString();


        public void storeUserDataInBackground(User user, GetUserCallback userCallback) {
        progressDialog.show();
        new aaAsyncTask(user, userCallback).execute();
    }

        public void fetchUserDataInBackground(User user, GetUserCallback callback) {
        progressDialog.show();
        new aaAsyncTask(user, callback).execute();

    }

        public class aaAsyncTask extends AsyncTask<Void, Void, ArrayList<User>> {
        User user;
        GetUserCallback userCallback;

        public aaAsyncTask(User user, GetUserCallback usercallback) {
            this.user = user;
            this.userCallback = usercallback;

        }

         protected ArrayList<User> doInBackground(Void... params) {

        ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("bloodtype", bloodd));
        dataToSend.add(new BasicNameValuePair("location", loc));
        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost(SERVER_ADDRESS + "/Search.php");


        ArrayList<User> userlist = null;
        User returnedUser=null;

        try {
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            HttpResponse httpResponse = client.execute(post);

            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jObject = new JSONObject(result);

            if (jObject.length() == 0) {
                userlist = null;
                Context context = getApplicationContext();
                CharSequence text = "no available donor!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

            } else {

                String resultt = EntityUtils.toString(entity);
                JSONArray jsonArray = new JSONArray(resultt);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String fname = jsonObject.getString("firstname");
                    String lname = jsonObject.getString("lastname");
                    String blood = jsonObject.getString("blood");
                    String location = jsonObject.getString("location");
                    String email = jsonObject.getString("email");
                    String age = jsonObject.getString("age");
                    String password = jsonObject.getString("password");
                    String phone = jsonObject.getString("phone");
                    int agee = Integer.parseInt(age);
                    int phonee = Integer.parseInt(phone);

                    returnedUser = new User(fname, lname, blood, location, email, password, agee, phonee);
                 userlist.add(returnedUser);

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        protected void onPostExecute(String content) {
            progressDialog.dismiss();

                displayCountryList(content);
            }
        }
    }

        private void displayCountryList(String response){

        try {

            dataAdapter = new MyCustomAdapter(this,
                    R.layout.listv, userlist);
            ListView listView = (ListView) findViewById(R.id.listView);

            listView.setAdapter(dataAdapter);


            listView.setTextFilterEnabled(true);


        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

      protected void sendSMSMessage() {
        Log.i("Send SMS", "");
        TextView phone = (TextView)findViewById(R.id.textView33);
        TextView name = (TextView)findViewById(R.id.textView31);
        String aname= name.toString();

        String txtMessage = "hello my name is "+aname+"and i need blood if you can donnate please fill the form in the app and call me";

        String phoneNo = phone.getText().toString();
        String message = txtMessage;

        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNo, null, message, null, null);
            Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
        }

        catch (Exception e) {
            Toast.makeText(getApplicationContext(), "SMS failed, please try again.", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

      class MyCustomAdapter extends ArrayAdapter<User> {

        private ArrayList<User> userlist;

        public MyCustomAdapter(Context context, int textViewResourceId,
                               ArrayList<User> userlist) {
            super(context, textViewResourceId, userlist);
            this.userlist = new ArrayList<User>();
            this.userlist.addAll(userlist);
        }

        private class ViewHolder {

            TextView name;
            TextView phone;
            TextView email;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            Log.v("ConvertView", String.valueOf(position));
            if (convertView == null) {

                LayoutInflater vi = (LayoutInflater)getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.listv, null);

                holder = new ViewHolder();
                holder.name = (TextView) convertView.findViewById(R.id.textView31);
                holder.phone = (TextView) convertView.findViewById(R.id.textView33);
                holder.email = (TextView) convertView.findViewById(R.id.textView34);


                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            User user = userlist.get(position);
            holder.name.setText(user.getFirstname());
            holder.phone.setText(user.getPhone());
            holder.email.setText(user.getEmail());


            return convertView;

        }

    }
}

在这个课程中,我试图获得一个ArrayList<User>用户是我创建的类,并用用户填充列表视图,但是应用程序总是崩溃,并且存储和获取的方法是2不使用后台用户,然后获取系统服务未解决问题请帮忙。

2 个答案:

答案 0 :(得分:1)

哦不..你是想在doInBackground()旁边显示吐司信息吗?请检查您的代码

Toast toast = Toast.makeText(context, text, duration);
            toast.show();

所以这是Android的规则。您无法从后台线程触摸UI线程。 Toast消息出现在UI线程中,导致崩溃。请删除它。

答案 1 :(得分:0)

我认为问题在于响应Json尝试在onCreate()中初始化 userList ;或者在将userList提供给listView之前添加null检查。

始终检查响应代码

 if(httpResponce.getStatusLine().getStatusCode()==200){
   HttpEntity entity = httpResponse.getEntity();
   String result = EntityUtils.toString(entity);
  }
在写这些行之前

 HttpEntity entity = httpResponse.getEntity();
 String result = EntityUtils.toString(entity);

希望这会有所帮助:)