2016-10-05 4 views
-4

このjsonレスポンスを文字列に変換してリストビューにデータを表示する方法これは私のjsonデータです。私はリストビューでデータを表示しようとしていますが、動作していません。Androidでの解析とリストビューでの結果の表示

{ 
    "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; 
    } 
} 

MY主な活動。

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; 


     } 
    } 
} 

MY表示リスト動作。

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. 
+0

をアンドロイドでJSONデータを解析し、listview.thereするためにそれをバインドする方法をGoogleで検索してくださいは、例 –

+0

利用がたくさんありますMoshiコンバーターを追加して、それはあなたのリスト内の解析応答を提供します。 –

+0

私はリストビューで結果を表示するためのすべてのタスクを行ったこれは私のログです – waleed

答えて

0

私はあなたの解決策を実行していますが、これは要件を満たすためのパターンです。

1.要件のモデルクラスを作成します。 2.サーバーからデータを取得し、データを解析します。 3.データをモデルクラスタイプのarraylistに渡します。 4. baseAdapterを使用して、このarraylistをlsitviewに設定します。

ここで、アクティビティクラスにジャンプし、モデルクラスタイプの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を使用せずに1行の文字列など、いくつかのデータを表示したいならば、ModelクラスのtoString()メソッドをオーバーライドします。

EDIT

あなたは型の不一致エラーを取得しているとして。次のようにしてください。

// jarrayから値を取得するようになりました。

// doinBackground()でresult.toString()を返すことを忘れないでください。これはあなた

+0

ありがとう。私は私のモデルとアクティビティを投稿して、それを見て、どこが間違っているのか教えてください。 – waleed

+0

私は私の質問を更新しました。 – waleed

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"); 
     } 
    } 
関連する問題