【问题标题】:JSon array response on gridview in Fragment片段中gridview上的JSon数组响应
【发布时间】:2015-08-21 21:00:56
【问题描述】:

我是 android 开发的新手,我必须学习更多。我有一个使用片段的活动。打开主要活动,它显示了 3 个片段并使用 json 我创建了一个包含 ID 和名称的数组。我还不明白,如何将我的数组数据放在一个网格视图中,然后如何在片段上使用它。有人能帮我吗?这是我的 MainActivity

public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
String myJSON;
private ProgressDialog pDialog;



private static final String TAG_RESULTS = "result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Nome";


JSONArray serv_man = null;
ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getData();


    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

     mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {           actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }
}
protected void showList(){
    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        serv_man = jsonObj.getJSONArray(TAG_RESULTS);

        for(int i=0;i<serv_man.length();i++){
            JSONObject c = serv_man.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);

            HashMap<String,String> persons = new HashMap<String,String>();

            persons.put(TAG_NAME,name);
            persons.put(TAG_ID, id);
            tableList.add(persons);
        }

// 我应该在这里创建视图,但我还不知道如何

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

}
public void getData(){
    class GetDataJSON extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://mysite/get_collab.php");


            httppost.setHeader("Content-type", "application/json");
            InputStream inputStream = null;
            String result = null;
            try {
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
                Log.d("Log_Tag","xxx" + result);

// 这里我可以看到结果是好的

            } catch (Exception e) {
                // Oops
                Log.e("log_tag", "Error converting result " + e.toString());
            }
            finally {
                try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
            }
            return result;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Obtaining list...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }


        @Override
        protected void onPostExecute(String result){
            pDialog.dismiss();
            myJSON=result;
            showList();
        }
    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new PpFragment();
                break;
            case 1:
                fragment = new ScndFragment();

                break;
            case 2:
                fragment = new thrdFragment();

        }
        return fragment;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
        }
        return null;
    }

}

}

// 我应该想创建一个带有显示名称的网格视图的视图,并最终创建一个标准图片,如卡片视图,但对我来说可能真的太多了。我只能希望你的帮助。 谢谢

【问题讨论】:

    标签: android json android-fragments gridview


    【解决方案1】:

    我还不明白,如何将我的数组数据放在一个gridview 和 那么如何在片段上使用它。

    要使用数据填充 GridView,请使用 Adapter。 Official documantation 描述了您应该为 GridView 使用哪种适配器,您可以在网络上找到许多适配器示例。

    如果您希望 Grid 显示在 Fragment 上,而不是 Activity 本身,请将 Grid 放置到 Fragment,而不是 Activity。这是唯一的区别。

    出于教育目的,我建议您在 Activity 中填充 Grid 视图(将其放入布局 xml)并稍后添加片段。

    【讨论】:

    • 感谢您的回复。我看过官方文档,但这对我来说很难。在大多数情况下,它更简单地查看代码并研究每一行,测试、更改和验证差异。不幸的是,很多时候,你在网上找到的代码对于初学者来说很复杂。我正在学习,我有很多东西要学!感谢您的支持,对不起我的英语不好!
    【解决方案2】:

    在我看来,你可以把你的gridview和你的http请求放在一个fragment中,比如PpFragment。然后您可以使用从 Internet 获得的数据来初始化您的网格视图。

    这是 gridview 适配器:

    第 1 部分:

    private class ImageAdapter extends BaseAdapter{
        public ImageAdapter() {
        }
    
        @Override
        public int getCount() {
            return tableList.size();
        }
    
        @Override
        public Object getItem(int position) {
            return tableList.get(position);  //tableList is your data source
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
        class ViewHolder {
            TextView name;
            TextView id;
        }
    
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
    
            if(convertView==null){  
                //layout.item  is your item layout of your gridview
                convertView = getLayoutInflater().inflate(R.layout.item, null);   
                holder = new ViewHolder();
                holder.name = (TextView)convertView.findViewById(R.id.name);
                holder.id = (ImageView)convertView.findViewById(R.id.id);
                //name and id is your view of your gridview item, for the ID and NAME
    
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
    
            holder.name.setText(tableList.get(position).get("aaaa"));
            holder.id.setText(tableList.get(position).get("xxxx"));
            //Here you can assign values to your TextView with the value you get from the data source.
    
    
            return convertView;
        }   
    }
    

    您可以在下面初始化您的网格视图:

    第二部分:

    //view is your layout of one fragment,such as PpFragment.
      GridView gridView = (GridView)view.findViewById(R.id.gridviewss);
      ImageAdapter imageAdapter = new ImageAdapter();
      gridView.setAdapter(imageAdapter);
    

    gridview 布局 xml:

    第 3 部分:R.id.gridviewss:

    <GridView
      android:id="@+id/gridviewss"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:numColumns="3"
      android:horizontalSpacing="2dp"
      android:verticalSpacing="7.5dp"
      android:stretchMode="columnWidth"
      android:gravity="center"
      android:background="#F1F1F1"
      android:paddingLeft="11.5dp"
      android:paddingRight="11.5dp"
      android:paddingTop="11.5dp"
      >
    </GridView>
    

    你可以在fragment方法中启动你的http请求(上面粘贴的getData()方法),比如你的fragment PpFragment的onCreateView,然后你可以在从主机获取数据时用Part2代码初始化你的适配器(在调用方法 showList() 之后)。

    我希望这会有所帮助。

    第四部分: R.layout.frag_uno_item:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical" >
    
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/id"
         />
    
     <TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/name"
         />
    </LinearLayout>
    

    然后是 Fragment_Uno.java:

    package com.example.stackproject;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.BasicHttpParams;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.TextView;
    
    public class Fragment_Uno extends Fragment {
    String myJSON;
    private ProgressDialog pDialog;
    
    
    private static final String TAG_RESULTS = "result";
    private static final String TAG_ID = "ID";
    private static final String TAG_NAME = "Nome";
    JSONArray serv_man = null;
    ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();
    
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View view = inflater.inflate(R.layout.frag_uno, container, false);
        getData();
        return view;
    
    }
    protected void showList(){
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            serv_man = jsonObj.getJSONArray(TAG_RESULTS);
    
            for(int i=0;i<serv_man.length();i++){
                JSONObject c = serv_man.getJSONObject(i);
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);
    
                HashMap<String,String> persons = new HashMap<String,String>();
    
                persons.put(TAG_NAME,name);
                persons.put(TAG_ID, id);
                tableList.add(persons);
            }
    
            View view = getActivity().getLayoutInflater().inflate(R.layout.frag_uno, null);
            GridView gridView = (GridView) view.findViewById(R.id.gridView2);
            ImageAdapter imageAdapter = new ImageAdapter();
            gridView.setAdapter(imageAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
    }
    
    
    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String> {
    
            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://etc.collab.php");
    
                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");
    
                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
    
                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();
    
                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                    Log.d("Log_Tag", "xxx" + result);
                    //view is your layout of one fragment,such as PpFragment.
    
    
                } catch (Exception e) {
                    // Oops
                    Log.e("log_tag", "Error converting result " + e.toString());
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // pDialog = new ProgressDialog(PpFragment.this);
                //  pDialog.setMessage("Obtaining list...");
                //  pDialog.setIndeterminate(false);
                //  pDialog.setCancelable(true);
                //  pDialog.show();
            }
    
    
            @Override
            protected void onPostExecute(String result){
                //       pDialog.dismiss();
                myJSON=result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }
    
    
    public class ImageAdapter extends BaseAdapter {
        private Context mContext;
        private View layoutInflater;
    
        public ImageAdapter(Context c) {
            mContext = c;
        }
    
        public ImageAdapter() {
        }
    
        @Override
        public int getCount() {
            return tableList.size();
        }
    
        @Override
        public Object getItem(int position) {
            return tableList.get(position);  //tableList is your data source
        }
    
        @Override
        public long getItemId(int position) {
            return 0;
        }
    
    
    
        class ViewHolder {
            TextView name;
            TextView id;
        }
    
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
    
            if (convertView == null) {
                //layout.item  is your item layout of your gridview
                convertView = getActivity().getLayoutInflater().inflate(R.layout.frag_uno_item, null);
                   holder = new ViewHolder();
                   holder.name = (TextView)convertView.findViewById(R.id.name);
                   holder.id = (TextView)convertView.findViewById(R.id.id);
                //name and id is your view of your gridview item, for the ID and NAME
    
                   convertView.setTag(holder);
            } else {
                              holder = (ViewHolder) convertView.getTag();
            }
    
             holder.name.setText(tableList.get(position).get(TAG_NAME));
             holder.id.setText(tableList.get(position).get(TAG_ID));
            //Here you can assign values to your TextView with the value you get from the data source.
    
    
            return convertView;
        }
    }
    

    }

    【讨论】:

    • 非常感谢您的帮助,我真的很感激。我测试了您的建议,按照您上面所写的进行了更改,但是我还有一些问题。在您的适配器代码中,android studio 突出显示了一些类似这样的代码 convertView = getLayoutInflater().inflate(R.layout.fragment_pp_fragment, null) 并告诉我无法解析方法 getlayoutinflater,然后在 Ppfragment 中,我已经按照您告诉我的那样移动了 json 字符串, GridView gridView = (GridView) view.findViewById(R.id.gridview);无效,无法解析字符串视图。我试图理解为什么。
    • 在你的片段中,你可以使用getActivity().getLayoutInflater().inflate(R.layout.fragment_pp_fragment, null),因为你可以只使用上下文来调用getLayoutInflater()方法。而视图是您的片段视图,例如 view = getActivity().getLayoutInflater().inflate(R.layout.fragment_pp_fragment, null);
    • 谢谢!什么都没有改变!! :-) 这很正常,我是个坏学生...如果我用 getActivity() 更改,这次只是这个红色,编译器告诉我无法解析方法等...
    • 在我的fragment中,getActivity()可以被reloved~能不能给我看看你的fragment代码?
    • 谢谢莉娜,但我做了太多的改变...:( blob...我正在用片段创建一个全新的项目,然后重试。最终我会发布代码。
    【解决方案3】:

    先改这个

     public long getItemId(int position) {
    return 0;
    

    }

    public long getItemId(int position) {
    return position;
    

    }

    然后你需要迭代 hash map 。 holder.name.setText(tableList.get(position).get("aaaa")); holder.id.setText(tableList.get(position).get("xxxx"));`

    已编辑 你不需要一个 hashmap 算了。只需创建一个 morel 类并为它创建实体和 getter 设置器。并设置值,然后将其对象的 arrayList 传递给 adapter 。像下面的例子。

    public class DataObject{
    
    private boolean success;
    private String message="";
    private String hash;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public boolean isSuccess() {
        return success;
    }
    public void setSuccess(boolean success) {
        this.success = success;
    }
    public String getHash() {
        return hash;
    }
    public void setHash(String hash) {
        this.hash = hash;
    }
    

    }

    然后当您解析 .create 一个对象并为其设置参数并将其添加到 ArrayList 中。然后将其传递给适配器。就是这样,您更新的方法看起来像

    受保护的 void showList(){

    try {
        JSONObject jsonObj = new JSONObject(myJSON);
        serv_man = jsonObj.getJSONArray(TAG_RESULTS);
    
        for(int i=0;i<serv_man.length();i++){
           DataObject dt =new DataObject();
            JSONObject c = serv_man.getJSONObject(i);
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            dt.setName(name);
            dt.setId();
            tableList.add(dt);
        }
    
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

    在哪里tableList=new ArrayList&lt;DataObject&gt;();

    在类级别定义它并在你的适配器类中使用它来获取 text.like this ..

    holder.textView.setText(tableList.get(position).getName());
    

    好的,如果您遇到任何问题,请告诉我

    【讨论】:

    • 编译器标记为错误 holder.name.setText(tableList.get(position).get("aaaa"));
    • 这是全新的错误日志:D/Log_Tag﹕xxx{"result":[{"ID":"1","Nome":"Gianni"},{"ID" :"2","Nome":"Michele"},{"ID":"3","Nome":"Margherita"},{"ID":"4","Nome":"Cindy"}] } E/log_tag﹕错误转换结果 java.lang.NullPointerException
    • 好吧,感谢您的解释 ADM,但是我尝试的一切都使我的立场变得复杂!如果您查看我的代码,在我必须调用适配器之前一切正常。所以,三天以来我一直在问自己,我的错误在哪里,调用适配器或适配器。如果我使用上面发布的代码调试并记录所有进程,结果是 java.lang.NullpointerException。我惊慌失措!有人可以创建基于 xml 布局和 json 数组的自定义适配器吗?我只是不能......我投降! :(
    • 使用上面的代码并替换行.. convertView = getLayoutInflater().inflate(R.layout.frag_uno, null);通过 LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView=inflater.inflate(R.layout.list_item,null);
    • 然后确保它可以改变适配器中的那条线。否则我必须阅读你所有的代码然后才能给你一个解决方案
    猜你喜欢
    • 2019-12-04
    • 2018-01-14
    • 2010-10-26
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2017-09-17
    • 1970-01-01
    相关资源
    最近更新 更多