【问题标题】:The simpleAdapter shows an error in the constructorsimpleAdapter 在构造函数中显示错误
【发布时间】:2015-12-10 12:30:13
【问题描述】:

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

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. 

问题是 this(context) 吗?

【问题讨论】:

  • 你读过documentation吗?如果是这样,您会看到第一个参数必须是 Context,但您传递的是 SelectAnswerActivity。
  • 尝试改用youractivityname.this或使用getActivity()
  • 从一个片段中,第一个参数应该是getActivity()

标签: java android android-context simpleadapter


【解决方案1】:

试试这个,使用 Activity 上下文而不是 Fragment

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-28
        • 2021-09-17
        • 1970-01-01
        • 2014-08-19
        • 2014-01-03
        • 1970-01-01
        • 2018-11-15
        • 2012-07-01
        相关资源
        最近更新 更多