当前位置: 首页 > 知识库问答 >
问题:

Gridview中的Json分析不起作用

邴英毅
2023-03-14

我想在网格视图中显示我的用户(带图像)我的jSON,在数组中给出正确的响应

但在解析Json后,数据不会显示在网格视图中

我的日志猫没有给我任何错误只是显示

06-05 12:21:12.269: I/Choreographer(4047): Skipped 1134 frames!  The application may be doing too much work on its main thread.

这是我的活动

public class MeetPeople extends Activity {

private ProgressDialog pDialog;
private GridView gridView;
//private GridViewAdapter customGridAdapter;
// URL to get contacts JSON
private static String url = "http://www.get2love.webitexperts.com/nearbyusers";

// JSON Node names
private static final String TAG_CONTACTS = "";
private static final String TAG_ID = "User_Id";
private static final String TAG_NAME = "User_Full_Name";
private static final String TAG_IMAGE = "User_Image";


// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
GridViewAdapter customGridAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.meetpeople);
    //requestWindowFeature(Window.FEATURE_NO_TITLE);

    contactList = new ArrayList<HashMap<String, String>>();
    // Calling async task to get json
            new GetContacts().execute();
    //ListView lv = getListView();
    gridView = (GridView) findViewById(R.id.gridView);
    customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, contactList);
    gridView.setAdapter(customGridAdapter);

    gridView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
                        Toast.makeText(MeetPeople.this, position + "#Selected",Toast.LENGTH_SHORT).show();
                    }

                });

}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
    ArrayList<HashMap<String, String>>  contact_List = new ArrayList<HashMap<String, String>>();
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MeetPeople.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();

         UserModel user = (UserModel) getIntent().getSerializableExtra("User");
        String ID=String.valueOf(user.getUser_Id());
        String DST=String.valueOf(100);
        params.add(new BasicNameValuePair("id",ID));
        params.add(new BasicNameValuePair("distance", DST));
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST, params);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONArray contacts = new JSONArray(jsonStr);

                // Getting JSON Array node


                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String User_Id = c.getString(TAG_ID);
                    String User_Full_Name = c.getString(TAG_NAME);
                    String User_Image=c.getString(TAG_IMAGE);


                    // Phone node is JSON Object


                    // tmp hashmap for single contact

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

                    // adding each child node to HashMap key => value
                    contact.put(TAG_ID, User_Id);
                    contact.put(TAG_NAME, User_Full_Name);
                    contact.put(TAG_IMAGE, User_Image);


                    // adding contact to contact list
                    contact_List.add(contact);

                }
                return contact_List;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(final ArrayList<HashMap<String, String>> result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        contact_List=result;
        gridView = (GridView) findViewById(R.id.gridView);
        customGridAdapter = new GridViewAdapter(MeetPeople.this, R.layout.row_grid, contactList);
        gridView.setAdapter(customGridAdapter);
    /*runOnUiThread( new Runnable() {
        public void run() {
            contactList=result;

        }
    });*/

        /**
         * Updating parsed JSON data into ListView
         * */
        /*ListAdapter adapter = new SimpleAdapter(
                MeetPeople.this, contactList,
                R.layout.row_grid, new String[] { TAG_NAME
                        }, new int[] { R.id.name });

        setAdapter(customGridAdapter);*/
    }

}

}

这是我的GridViewAdapter

public class GridViewAdapter extends BaseAdapter {
private Context context;
private int layoutResourceId;
private ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

public GridViewAdapter(Context context, int layoutResourceId,ArrayList<HashMap<String, String>> data) {
   // super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    ViewHolder holder = null;

    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new ViewHolder();
        holder.imageTitle = (TextView) row.findViewById(R.id.text);
        holder.image = (ImageView) row.findViewById(R.id.image);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

  //  ImageItem item = data.get(position);
    holder.imageTitle.setText(getItem(position, "TAG_NAME"));
    holder.image.setImageBitmap(getImage(position));
    return row;
}

static class ViewHolder {
    TextView imageTitle;
    ImageView image;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return 0;
}

public String getItem(int arg0,String key) {

    return data.get(arg0).get(key);
}
 public Bitmap getImage(int pos){
String  url = data.get(pos).get("TAG_IMAGE");
 MemoryCache memoryCache=new MemoryCache();
 Bitmap bitmap=memoryCache.get(url);
 if(bitmap!=null)
    // imageView.setImageBitmap(bitmap);
     return bitmap;
 else
 {
   // queuePhoto(url, imageView);
   //  imageView.setImageResource(loader);
 }
return null;


}
@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return null;
}
 }

这是我的日志

06-05 12:20:47.039: D/StrictMode(4047):     at dalvik.system.NativeStart.main(Native Method)
06-05 12:20:53.799: D/Response:(4047): >     [{"User_Id":"49","User_Full_Name":"meet","User_Image":""},{"User_Id":"50","User_Full_Name":"meet","User_Image":"http:\/\/www.get2love.webitexperts.com\/profile_images\/1400754860profile.jpg"},{"User_Id":"51","User_Full_Name":"meet","User_Image":"http:\/\/www.get2love.webitexperts.com\/profile_images\/1400756097profile.jpg"},{"User_Id":"71","User_Full_Name":"hh","User_Image":"http:\/\/www.get2love.webitexperts.com\/profile_images\/1401479271profile.jpg"},{"User_Id":"72","User_Full_Name":"hh","User_Image":"http:\/\/www.get2love.webitexperts.com\/profile_images\/1401479340profile.jpg"},{"User_Id":"73","User_Full_Name":"lkjh","User_Image":"http:\/\/www.get2love.webitexperts.com\/profile_images\/1401479662profile.jpg"},{"User_Id":"76","User_Full_Name":"jhon","User_Image":"http:\/\/www.get2love.webitexperts.com\/profile_images\/1401714195profile.jpg"},{"User_Id":"79","User_Full_Name":"sammy","User_Image":"http:\/\/www.get2love.webitexperts.com\/profile_images\/1401889294profile.jpg"}]
 06-05 12:21:12.269: I/Choreographer(4047): Skipped 1134 frames!  The application may be doing too much work on its main thread.
 06-05 12:21:38.829: I/Choreographer(4047): Skipped 1533 frames!  The application may be doing too much work on its main thread.

有人能解决我的问题吗?我想在GridView(UserImage)中显示这些响应

请先谢谢你

在代码中编辑后的新logcat。。。。根据Answer

06-05 13:22:22.849: E/Trace(8790): error opening trace file: No such file or directory (2)
06-05 13:23:41.839: E/Buffer Error(8790): Error converting result java.lang.NullPointerException

06-05 13:23:41.839: E/JSON Parser(8790):解析数据org.json.JSONException:在06-05 13:23:51.759的字符0处输入结束: E/AndroidRuntime(8790): FATAL EXCEPTION: AsyncTask#1 06-05 13:23:51.759: E/AndroidRuntime(8790):java.lang.RuntimeException:在执行doInbackground()06-05 13:23:51.759: E/AndroidRuntime(8790): atandroid.os.AsyncTask$3.done(AsyncTask.java:299)06-05 13:23:51.759: E/AndroidRuntime(8790): atjava.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)06-05 13:23:51.759: E/AndroidRuntime(8790): atjava.util.concurrent.FutureTask.setException(FutureTask.java:124)06-05 13:23:51.759: E/AndroidRuntime(8790java.util.concurrent.FutureTask.run(FutureTask.java:137)06-05 13:23:51.759: E/AndroidRuntime(8790): atandroid.os.AsyncTask$SerialExecitor$1.run(AsyncTask.java:230)06-05 13:23:51.759: E/AndroidRuntime(8790): atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)06-05 13:23:51.759: E/AndroidRuntime(8790): atjava.util.concurrent.ThreadPoolExecitor$Worker.run(ThreadPoolExecutor.java:569)06-05 13:23:51.759: E/AndroidRuntime(8790): atjava.lang.Thread.run(Thread.java:856)06-05 13:23:51.759: E/AndroidRuntime(8790):由以下原因引起:NullPointerException 06-05 13:23:51.759: E/AndroidRuntime(8790): atcom.example.phonebook.Mainactive$loginAccess. doInbackground(Mainactive. jWindowManagerInp. addView(WindowManagerInp. java: 292)06-05 13:23:52.309:E/WindowManager(8790):在android. view。WindowManagerInp. addView(WindowManagerInp. java: 224)06-05 13:23:52.309:E/WindowManager(8790):在android. view。WindowManagerImpl$CompatModeWrapper. addView(WindowManagerInp. java: 149)06-05 13:23:52.309:E/WindowManager(8790):在android. view。Window$LocalWindowManager. addView(Windows. java: 547)06-05 13:23:52.309:E/WindowManager(8790):在android. app. Dialog. show(Dialo. java: 277)06-05 13:23:52.309:E/WindowManager(8MainActivity2 dollars. onClick(MainActivity. java: 112)06-05 13:23:52.309:E/WindowManager(8790):在android. view。View. performClick(View. java: 4084)06-05 13:23:52.309:E/WindowManager(8790):在android. view。查看$PerformClick. run(View. java: 16987)06-05 13:23:52.309:E/WindowManager(8790):在android. os。Handler. handleCallback(Handler. java: 615)06-05 13:23:52.309:E/WindowManager(8790):在android. os。Handler。调度消息(Handler. java: 92)06-05 13:23:52.309:E/WindowManager(8790):在android. os。Looper. loop(Loper. java:方法。调用(方法。java: 511)06-05 13:23:52.309:E/WindowManager(8790):在com. android. interal. os。ZygoteInit$MESTodAndArgsCaller. run(ZygoteInit. java: 789)06-05 13:23:52.309:E/WindowManager(8790):在com. android. interal. os。ZygoteInit. main(ZygoteInit. java: 556)06-05 13:23:52.309:E/WindowManager(8790):在dalvik. system。NativeStart. main(本机方法)

共有2个答案

燕志学
2023-03-14

去除

customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, contactList);
gridView.setAdapter(customGridAdapter);

从创建(Bundle savedInstanceState){。和

gridView = (GridView) findViewById(R.id.gridView);

onPostExecute(...)旁边初始化gridView=(GridView)findViewById(R.id.gridView);之前

new GetContacts().execute();
敖毅
2023-03-14

返回您的原始代码,该代码使用空联系人列表设置网格适配器。这将消除空指针异常。在GridViewAdapter中添加一个名为callNotifyDataChanged的方法。java和下面的代码。

public void callNotifyDataChanged() {
    notifyDataSetChanged();
}

在GetContacts中。onPostExecute方法,在再次设置适配器后调用此方法。

@Override
protected void onPostExecute(final ArrayList<HashMap<String, String>> result) {
    super.onPostExecute(result);
....
....



customGridAdapter.callNotifyDataChanged() ;

理想情况下,您不必重新创建适配器并再次进行设置。您应该只更改适配器中的数据,并重用同一适配器。但首先,试试我的建议,看看是否有效。

祝你好运

 类似资料:
  • 我正在解析URL中的数据,下面提到了这个错误。 原始数据从服务器完美显示。无法使用Json解析拆分数据。 请帮我解决这个错误 编辑:1 来自URL的Json响应 错误: 主要活动。JAVA

  • 问题内容: 这是我的设置: 我的文件在主文件夹内的文件夹中。 这是我的查询: 中的字眼是:美国 ,美国,美国 。 所以这行不通。有趣的是,搜索正常,但当我在文件中输入任何单词时 除外。因此,例如,当我通常在搜索中键入 我们 的内容时,就会得到结果。有了这个分析仪, 我们 什么都不会给我。 我已经完成并连接到ES服务器,但仍然无法正常工作。 编辑 一个示例: 的示例(这来自前端): 编辑#2 : 这

  • 我在使用Android GridView时遇到了奇怪的问题。我创建了一个3x4的网格,并在其中插入了按钮。我希望当用户单击按钮时,按钮的背景发生变化。这对于除了第一个按钮(索引为0 -左上角的那个)之外的所有按钮都很好。无论我做什么,OnClick事件侦听器都不会为那个按钮触发。 这是我创建视图的代码: 如果我换掉 具有 然后onClick()被触发,但背景仍然没有改变。所有其他按钮都按预期工作。

  • 问题内容: 我正在尝试使用数组中的json将多个变量从php文件发送回ajax。php文件中的代码可以完美运行,并且可以对数据库进行所有操作。但是,一旦我在ajax中添加dataType:“ json”,php文件中就什么也没有发生。我在Google上搜索了一下,有人说这可能是浏览器问题,但到目前为止,它在Firefox,Chrome或IE中均不起作用。我正在使用最新版本的jQuery。 这就是p

  • 本文向大家介绍.Net中的json操作类用法分析,包括了.Net中的json操作类用法分析的使用技巧和注意事项,需要的朋友参考一下 本文实例展示了.Net中的json操作类用法,对于进行.Net程序设计来说是非常重要的技巧。具体分析如下: 首先需要引用 System.Web.Extensions.dll 这个类库 命名空间需要加上:System.Web.Script.Serialization  

  • 问题内容: 编辑:要补充一点,同义词似乎可以与基本的查询字符串查询一起使用。 这将返回新罕布什尔州的所有结果,但对“ nh”的“匹配”查询将不返回结果。 我正在尝试将同义词添加到我的Elastic索引中的位置字段中,这样,如果我对“质量”,“马”或“马萨诸塞州”进行位置搜索,则每次都会得到相同的结果。我将同义词过滤器添加到设置中,并更改了位置映射。这是我的设置: 以及location.region