simpleAdapter在构造函数中显示错误

时间:2015-12-10 12:30:14

标签: java android android-context simpleadapter

我的代码中存在问题。我在这段代码中尝试了很多东西,但它没有修复。最后描述了错误。它与构造函数有关。

SelectActivityAnswer.java

package com.example.test;


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

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


import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;





public  class SelectAnswerActivity extends Fragment  {
     final static String ARG_POSITION_ANSWER = "position";
     private String jsonResult;
     private String url = "http://myip/employee_details.php";
     private ListView listView;


     public SelectAnswerActivity() {
         // Empty constructor required for fragment subclasses


     }



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

        //SimpleAdapter simpleAdapter = new SimpleAdapter(this, null, 0, null, null);
        View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);

        accessWebService();


    //  selectListAns = (ListView) rootView.findViewById(R.id.ans_list);
         // novo code abaixo
      //  ListAdapterAns adapterAns = new ListAdapterAns(this,toppings);
     //   selectListAns.setAdapter(adapterAns);
     //   selectListAns.setOnItemClickListener(new AnsItemClickListener());

        //View rootView = inflater.inflate(R.layout.activity_select_answer, container, false);
        //int i = getArguments().getInt(ARG_PLANET_NUMBER);
        //String planet = getResources().getStringArray(R.array.planets_array)[i];

        //int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                    //    "drawable", getActivity().getPackageName());
       // ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
      //  getActivity().setTitle(planet);
        return rootView;
    }

 // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

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



        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                //Toast.makeText(getApplicationContext(),
                //      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            ListDrwaer();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[] { url });
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("employee name");
                String number = jsonChildNode.optString("employee no");
                String outPut = name + "-" + number;
                employeeList.add(createEmployee("employees", outPut));
            }
        } catch (JSONException e) {
            //Toast.makeText(getApplicationContext(), "Error" + e.toString(),
            //      Toast.LENGTH_SHORT).show();
        }

        SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
                R.id.content_list_ans,
                new String[] { "employees" }, new int[] { android.R.id.text1 });
        listView.setAdapter(simpleAdapter);
        //Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();

    }

    private HashMap<String, String> createEmployee(String name, String number) {
        HashMap<String, String> employeeNameNo = new HashMap<String, String>();
        employeeNameNo.put(name, number);
        return employeeNameNo;
    }

}

该行是:

SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
                R.id.content_list_ans,
                new String[] { "employees" }, new int[] { android.R.id.text1 });
        listView.setAdapter(simpleAdapter);

错误是:

The constructor SimpleAdapter(SelectAnswerActivity, List<Map<String,String>>, int, String[], int[]) is 
 undefined. 

问题是这个(上下文)?

3 个答案:

答案 0 :(得分:1)

尝试使用Activity上下文而不是Fragment

SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), employeeList,
            R.id.content_list_ans,
            new String[] { "employees" }, new int[] { android.R.id.text1 });

答案 1 :(得分:1)

您对Context的引用是错误的。您不能在AsynTask类中拥有活动上下文。您应该尝试使用getApplicationContext()getActivity()而不是this

SelectAnswerActivity也不是Activity,它是Fragment。如果是活动,您也可以使用SelectAnswerActivity.this

答案 2 :(得分:1)

您正在引用片段的上下文,而不是您的Activity的上下文。尝试改变它。