NavigationDrawer框架中的JsonParsing错误

时间:2016-05-21 05:37:38

标签: java android json listview fragment

我试图从我的第一个片段中的url获取信息,但似乎我的第一个片段给了我2个错误

第一次出现错误

adapter = new ListViewAdapter(FirstFragment.this, arraylist);

,第二次

    public class FirstFragment extends Fragment  {


        View myView;

        @Nullable

        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            myView = inflater.inflate(R.layout.first_layout, container ,false);
            new DownloadJSON().execute();
            return myView;
        }
        JSONObject jsonobject;
        JSONArray jsonarray;
        ListView listview;
        ListViewAdapter adapter;
        ProgressDialog mProgressDialog;
        ArrayList<HashMap<String, String>> arraylist;
        static String RANK = "rank";
        static String COUNTRY = "country";
        static String POPULATION = "population";
        static String FLAG = "flag";






        // DownloadJSON AsyncTask
        private class DownloadJSON extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(FirstFragment.this);
                // Set progressdialog title
                mProgressDialog.setTitle("Actualizando Información");
                // Set progressdialog message
                mProgressDialog.setMessage("Cargando...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // Create an array
                arraylist = new ArrayList<HashMap<String, String>>();
                // Retrieve JSON Objects from the given URL address
                jsonobject = JSONfunctions
                        .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");

                try {
                    // Locate the array name in JSON
                    jsonarray = jsonobject.getJSONArray("worldpopulation");



                    for (int i = 0; i < jsonarray.length(); i++) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("rank", jsonobject.getString("rank"));
                        map.put("country", jsonobject.getString("country"));
                        map.put("population", jsonobject.getString("population"));
                        map.put("flag", jsonobject.getString("flag"));
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }

                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {
                // Locate the listview in listview_main.xml
                listview = (ListView) myView.findViewById(R.id.listview);
                // Pass the results into ListViewAdapter.java
                adapter = new ListViewAdapter(FirstFragment.this, arraylist);
                // Set the adapter to the ListView
                listview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
    }

这是我的FirstFragment类

   public class ListViewAdapter extends BaseAdapter {

        // Declare Variables
        Context context;
        LayoutInflater inflater;
        ArrayList<HashMap<String, String>> data;
        ImageLoader imageLoader;
        HashMap<String, String> resultp = new HashMap<String, String>();

        public ListViewAdapter(Context context,
                               ArrayList<HashMap<String, String>> arraylist) {
            this.context = context;
            data = arraylist;
            imageLoader = new ImageLoader(context);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            // Declare Variables
            TextView rank;
            TextView country;
            TextView population;
            ImageView flag;

            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View itemView = inflater.inflate(R.layout.listview_item, parent, false);
            // Get the position
            resultp = data.get(position);

            // Locate the TextViews in listview_item.xml
            rank = (TextView) itemView.findViewById(R.id.rank);
            country = (TextView) itemView.findViewById(R.id.country);
            population = (TextView) itemView.findViewById(R.id.population);

            // Locate the ImageView in listview_item.xml
            flag = (ImageView) itemView.findViewById(R.id.flag);

            // Capture position and set results to the TextViews
            rank.setText(resultp.get(FirstFragment.RANK));
            country.setText(resultp.get(FirstFragment.COUNTRY));
            population.setText(resultp.get(FirstFragment.POPULATION));
            // Capture position and set results to the ImageView
            // Passes flag images URL into ImageLoader.class
            imageLoader.DisplayImage(resultp.get(FirstFragment.FLAG), flag);
            // Capture ListView item click
            itemView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // Get the position
                    resultp = data.get(position);
                    Intent intent = new Intent(context, SingleItemView.class);
                    // Pass all data rank
                    intent.putExtra("rank", resultp.get(FirstFragment.RANK));
                    // Pass all data country
                    intent.putExtra("country", resultp.get(FirstFragment.COUNTRY));
                    // Pass all data population
                    intent.putExtra("population",resultp.get(FirstFragment.POPULATION));
                    // Pass all data flag
                    intent.putExtra("flag", resultp.get(FirstFragment.FLAG));
                    // Start SingleItemView Class
                    context.startActivity(intent);

                }
            });
            return itemView;
        }
    }

这是我的listviewadapter类

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        android.app.FragmentManager fragmentManager = getFragmentManager();


        if (id == R.id.nav_first_layout) {

            fragmentManager.beginTransaction().replace(R.id.content_frame,new FirstFragment()).commit();
            // Handle the camera action
        } else if (id == R.id.nav_second_layout) {

            fragmentManager.beginTransaction().replace(R.id.content_frame,new SecondFragment()).commit();

        } else if (id == R.id.nav_third_layout) {

            fragmentManager.beginTransaction().replace(R.id.content_frame,new ThirdFragment()).commit();

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

这是我的主要活动课程,如果需要

Error:(58, 31) error: no suitable constructor found for ProgressDialog(FirstFragment)
constructor ProgressDialog.ProgressDialog(Context,int) is not applicable
(actual and formal argument lists differ in length)
constructor ProgressDialog.ProgressDialog(Context) is not applicable
(actual argument FirstFragment cannot be converted to Context by method invocation conversion)


Error:(107, 23) error: constructor ListViewAdapter in class ListViewAdapter cannot be applied to given types;
required: Context,ArrayList<HashMap<String,String>>
found: FirstFragment,ArrayList<HashMap<String,String>>
reason: actual argument FirstFragment cannot be converted to Context by method invocation conversion

logcat的

def initial(request):
  return render(request,'display/home.html')

def upload(request):
    f = FileForm()
    f=FileModel.objects.all()
    print(f)
    y="Hello"

    if request.method== 'POST':
        fil=FileForm(request.POST,request.FILES)
        if fil.is_valid():
            newfile=FileModel(file=request.FILES['file'])
            newfile.save()

            return HttpResponseRedirect(reverse('display.views.list'))
    else:
           fil=FileForm()

    docs=FileModel.objects.all()



    return render(request,"display/upload.html",{"y":y})

由于

1 个答案:

答案 0 :(得分:0)

两次你都试图将片段传递给这些类的构造函数。片段不是活动,因此当构造函数需要用于实例化的上下文时,您不能仅传递片段。相反,请使用getActivity()方法。此方法返回与片段关联的活动。所以:

mProgressDialog = new ProgressDialog(getActivity());

adapter = new ListViewAdapter(getActivity(), arraylist);

进一步阅读:https://developer.android.com/reference/android/app/Fragment.html