简体   繁体   中英

The simpleAdapter shows an error in the constructor

I am with a problem in my code . I tried many things in this code , However it does not fix . In the end the error is described. It is something related with constructor.

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;
    }

}

The line is:

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

The error is :

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

Is the problem this(context) ?

Try this, using Activity context instead of Fragment

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

Your reference to the Context is wrong. You cannot have the activity context in the AsynTask class. You should try one of getApplicationContext() or getActivity() instead of this .

Also SelectAnswerActivity is not and Activity, its a Fragment . If it was activity you could have also used SelectAnswerActivity.this

You are referencing the context of the fragment, not the one of your Activity. Try changing that.

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