在Android中解析并在列表视图中显示结果

时间:2016-10-05 04:56:44

标签: android

如何将此json响应转换为字符串以在列表视图中显示数据。这是我的json数据。我正在尝试在列表视图中显示数据,但它不起作用。请指导我。

{
    "courseDataSet": {
        "totalCount": 2,
        "limit": 10,
        "offset": 0,
        "rows": [
        {},
        {
            "id": 4,
            "company_id": 2,
            "user_id": 5,
            "jobType": "Requirement Form",
            "jobTitle": "Senior Web Developer",
            "skills": "core php, java,jQuery",
            "industry": "Information Technologies",
            "department": "IT Department",
            "vacancy": 2,
            "qualification": "Master",
            "degreeTitle": "MCS",
            "miniExperience": 1,
            "jobCategory": "Part-Time",
            "jobstatus": "Accepted",
            "city": "Lahore",
            "gender": "Female",
            "salaryRange": "25,000-29,999",
            "companyName": null,
            "description": "employees required",
            "posting_date": "2016-09-22",
            "applied_date": "2016-10-22",
            "companyLogo": null,
            "remember_token": null,
            "deleted_at": null,
            "created_at": "2016-09-24 04:45:39",
            "updated_at": "2016-10-01 08:00:54"
        }]
    }
}

我的适配器类

package com.example.bc120402700.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by bc120402700 on 9/27/2016.
 */
public class ContactAdapter extends ArrayAdapter {


    List list=new ArrayList();
    public ContactAdapter(Context context, int resource) {
        super(context, resource);
    }



    public void add(Contacts object) {
        super.add(object);
        list.add(object);
    }

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


    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       View row;
        row=convertView;
        ContactHolder contactHolder;
        if (row==null){


            LayoutInflater layoutInflater= (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row=layoutInflater.inflate(R.layout.row_layout,parent,false);
            contactHolder=new ContactHolder();
            contactHolder.tx_name= (TextView) row.findViewById(R.id.tx_name);
            contactHolder.tx_email= (TextView) row.findViewById(R.id.tx_email);
            contactHolder.tx_mobile= (TextView) row.findViewById(R.id.tx_mobile);
            row.setTag(contactHolder);
        }

        else {

            contactHolder=(ContactHolder)row.getTag();


        }
        Contacts contacts= (Contacts) this.getItem(position);
        contactHolder.tx_name.setText(contacts.getName());
        contactHolder.tx_email.setText(contacts.getEmail());
        contactHolder.tx_mobile.setText(contacts.getMobile());
        return row;
    }


    static class ContactHolder{


TextView tx_name,tx_email,tx_mobile;


    }
}

我的模特课

package com.example.bc120402700.myapplication;

/**
 * Created by bc120402700 on 9/27/2016.
 */
public class Contacts {

    private String name,email,mobile;


    public Contacts(String name,String email, String mobile){
        this.name=name;
        this.email=email;

        this.mobile=mobile;



    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

我的主要活动。

package com.example.bc120402700.myapplication;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    String json_string;




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


public void getjson(View view){

new AdminAllocationTask().execute();
}

    public void parsejson(View view) {


        if (json_string == null) {

            Toast.makeText(getApplicationContext(), "first get json data", Toast.LENGTH_LONG).show();

        } else {
            Intent intent = new Intent(this, DisplayListView.class);
            intent.putExtra("json_data", json_string);
            startActivity(intent);

        }
    }

    class AdminAllocationTask extends AsyncTask<Void, Void, String> {
        String json_url;

        @Override
        protected void onPreExecute() {
            json_url = "http://mantis.vu.edu.pk/GameClub/public/sendingRequestList";
        }
        String JSON_STRING;
        @Override
        protected String doInBackground(Void... voids) {

            try {



                URL url = new URL(json_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();

                while ((JSON_STRING = bufferedReader.readLine()) != null) {

                    stringBuilder.append(JSON_STRING + "\n");

                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {

            TextView textview = (TextView) findViewById(R.id.textview);
            textview.setText(result);
            json_string = result;


        }
    }
}

我的显示列表活动。

package com.example.bc120402700.myapplication;

import android.os.PersistableBundle;
import android.os.health.SystemHealthManager;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class DisplayListView extends AppCompatActivity {
String json_string;
   JSONObject jsonObject;
    JSONArray jsonArray;
    ListView listView;

    ContactAdapter contactAdapter;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_list_view);
        listView= (ListView) findViewById(R.id.listView);

        contactAdapter=new ContactAdapter(this,R.layout.activity_display_list_view);
        listView.setAdapter(contactAdapter);

        json_string=getIntent().getExtras().getString("json_data");
      System.out.print(json_string + "dskljfsldjflsd");

        try {



//            jsonObject=new JSONObject();
            JSONObject jsonObject = new JSONObject(json_string);
//            JSONArray query = jsonParse.getJSONArray("courses");

            jsonArray=jsonObject.getJSONArray("sendingReqDataSet");


            int count=0;
            String name,email,moblile;

            while (count<jsonArray.length()){
                JSONObject JO=jsonArray.getJSONObject(count);
                name=JO.getString("request_to");
                email=  JO.getString("request_by");
                moblile=JO.getString("product_name");
                Contacts contacts=new Contacts(name,email,moblile);
                contactAdapter.add(contacts);
                count++;
            }


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

    }
}

这是我的日志结果。

W/System.err: org.json.JSONException: Value [[{"id":1,"userid":5,"jobid":null,"title":null,"description":"Viral Webbs is currently seeking a Senior PHP Developer to join our team.\r\n\r\nThe ideal candidate for the Senior PHP Developer role is a self-starter who relishes the chance to take ownership over assigned projects while working collaboratively in a team environment.\r\n\r\nThe Senior PHP Developer is dedicated to his craft, and who can hit the ground running.\r\n\r\nWe need you to write beautiful, fast PHP to a high standard, in a timely and scalable way that improves the code-base of our products in meaningful ways.\r\n\r\nYou will be a part of a creative team that is responsible for all aspects of the ongoing web development from the initial specification, through to developing, testing and launching.\r\n\r\nEssential Duty and responsibilities:\r\n\r\nIntegral member of a creative team in a dynamic, fast-paced environment;\r\nDesign and develop web based applications using PHP and other web technologies;\r\nResponsible for all aspects of ongoing web development from initial specification through development, testing and launching;\r\nDevelop and deploy new features to facilitate related procedures and tools if necessary;\r\nPassion for best design and coding practices and a desire to develop bold new ideas;\r\nIdentify and encourage areas for growth and improvement within the team\r\nBuild web applications that scale in face of ever increasing traffic;\r\nBuild applications that are extendable;\r\nCoordinate with management , and other members in planning and meeting all objectives and be responsible for estimations and tracking of development efforts;\r\nWorking with and re-platforming legacy applications;\r\nBuild ecommerce applications using Magento;\r\nStrong knowledge of Wordpress websites at customizing level.\r\nWordpress theme development or plugin development will be great plus.\r\nMust have knowledge of MVC and proven experience in CodeIgniter and Laravel.\r\nExpertise in  UI\/UX will be a plus","status":null},{"id":4,"userid":5,"jobid":null,"title":null,"description":"employees required","status":null}],{"courseDataSet":{"totalCount":2,"limit":10,"offset":0,"rows":[{"id":1,"company_id":1,"user_id":5,"jobType":"Requirement Form","jobTitle":"php developer","skills":"Larvel,php","industry":"Information Technologies","department":"IT Department","vacancy":2,"qualification":"Bachelor","degreeTitle":"Bscs","miniExperience":2,"jobCategory":"Full-Time","jobstatus":"Accepted","city":"Lahore","gender":"Male","salaryRange":"25,000-29,999","companyName":null,"description":"Viral Webbs is currently seeking a Senior PHP Developer to join our team.\r\n\r\nThe ideal candidate for the Senior PHP Developer role is a self-starter who relishes the chance to take ownership over assigned projects while working collaboratively in a team environment.\r\n\r\nThe Senior PHP Developer is dedicated to his craft, and who can hit the ground running.\r\n\r\nWe need you to write beautiful, fast PHP to a high standard, in a timely and scalable way that improves the code-base of our products in meaningful ways.\r\n\r\nYou will be a part of a creative team that is responsible for all aspects of the ongoing web development from the initial specification, through to developing, testing and launching.\r\n\r\nEssential Duty and responsibilities:\r\n\r\nIntegral member of a creative team in a dynamic, fast-paced environment;\r\nDesign and develop web based applications using PHP and other web technologies;\r\nResponsible for all aspects of ongoing web development from initial specification through development, testing and launching;\r\nDevelop and deploy new features to facilitate related procedures and tools if necessary;\r\nPassion for best design and coding practices and a desire to develop bold new ideas;\r\nIdentify and encourage areas for growth and improvement within the team\r\nBuild web applications that scale in face of ever increasing traffic;\r\nBuild applications that are extendable;\r\nCoordinate wi
W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err:     at com.example.bc120402700.myapplication.DisplayListView.onCreate(DisplayListView.java:45)
W/System.err:     at android.app.Activity.performCreate(Activity.java:6664)
W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
W/System.err:     at android.app.ActivityThread.-wrap12(ActivityThread.java)
W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:154)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I/Choreographer: Skipped 47 frames!  The application may be doing too much work on its main thread.

2 个答案:

答案 0 :(得分:0)

我正在做你的解决方案,但这是一种达到你要求的模式。

1.创建您的要求的模型类。 2.从服务器获取数据并解析数据。 3.将数据传递给模型类的arraylist。 4.使用baseAdapter将此arraylist设置为lsitview。

 public class ModelExample{

        String name;
        int age;
       ModelExample(String name,int age)
        {
         this.name=name;
         this.age=age;
         }

        //here click alt+ins ,you will find a getter and setter. select all           
       // and click enter to get getter and setter methods.
          }

现在转到Activity类并创建模型类类型的arraylist。

ArrayList<ModelExample> al_modelExample=new ArrayList<>();

            //parse and get required data from server;

                   String name=jsonobj.optString("name");
                    int age=jsonobj.getInt("age");
                     al_modelExample.add(new ModelExample(name,int));

                   //to get values from arraylist.  
                    al_modelExample.get(index).getName();

如果要在不使用BaseAdapter的情况下在一行中将某些数据显示为String,则覆盖Model类中的toString()方法。

修改

因为您遇到类型不匹配错误。做到以下几点。

output =
new getURLData()
    .execute().get();

  JsonArray jarray=new JsonArray(output);

//现在从jarray中获取值。

//不要忘记在doinBackground()中返回result.toString()。

希望这有助于你

答案 1 :(得分:0)

解析json如下: -

JSONArray jsonarray = new JSONArray(json_string);
    for (int i = 0; i < jsonarray.length(); i++) {
       JSONObject jsonobject = jsonarray.getJSONObject(i);
       JSONObject jo=jsonobject.getJSONObject("sendingReqDataSet");
       JsonArray contacts=jo.getJSONArray("contacts");
    for(int j=0;j<contacts.length();j++){   
     JSONObject details = contacts.getJSONObject(j);
     String email=  details.getString("request_by");
       }
    }