2017-04-09 13 views
-2

ここで私は自分のコードを共有しています。どのようにリストビューでこのデータを解析できるのですか。最初はJson Parserを使用していますが、これは動作しません。今私はこれを解析してリストビューを見ることはできません。このおかげで私を助けてください。Android ListView Jsonでデータを解析する

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.TextView; 

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

import java.util.ArrayList; 


public class HomeScreen extends Activity { 

    ListView listview; 
    String url; 
    ArrayList<ParticipantItem> participantArrayList; 
    ParticipantsAdapter pAdapter; 
    JSONArray jsonOuterArray; 
    private ProgressDialog pDialog; 
    ImageView menu, refresh; 
    Integer a; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.home_screen); 
     participantArrayList = new ArrayList<ParticipantItem>(); 
     listview = (ListView) findViewById(R.id.listview); 

     url = "http://findcourse.net/search_result.php?search=&study_field=17";//"http://findcourse.net/search_result.php?search=" + keywordvalue_get + sf_spinner_get + sl_spinner_get + si_spinner_get + sm_spinner_get; 
     refresh = (ImageView) findViewById(R.id.refresh); 
     menu = (ImageView) findViewById(R.id.menu); 

     new GetData().execute(); 
     System.out.println("The square root of " + url); 
     listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, 
            int position, long id) { 

      } 
     }); 


    } 

    ////////////////////// 
    private class GetData extends AsyncTask<String, String, String> { 

     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(HomeScreen.this); 
      pDialog.setMessage("Loading..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected void onPostExecute(String result) { 
      pDialog.dismiss(); 


      if (jsonOuterArray.length() > 0) { 
       for (int i = 0; i <= jsonOuterArray.length(); i++) { 
        a = jsonOuterArray.length(); 

        JSONObject jsonObj; 
        try { 
         jsonObj = jsonOuterArray.getJSONObject(i); 

         JSONObject message = jsonObj.getJSONObject("result"); 
         String offered_by_detail = message.getString("offered_by"); 

         String course = message.getString("course"); 
         String logo = message.getString("logo"); 
         String total_views = message.getString("total_views"); 
         String total_course_offered = message.getString("total_course_offered"); 
         String feature_course = message.getString("feature_course"); 
         String total_views_course = message.getString("total_views_course"); 
         String course_info = message.getString("course_info"); 
         String duration = message.getString("duration"); 
         String tution_fee = message.getString("tution_fee"); 
         String other_payable_fee = message.getString("other_payable_fee"); 
         String intake = message.getString("intakesandroid"); 
         String campus = message.getString("campusandroid"); 
         String entry_requirement = message.getString("entry_requirement"); 
         String longitude = message.getString("longitude"); 
         String latitude = message.getString("latitude"); 
         String search_filter = message.getString("search_filter"); 
         String institute_info = message.getString("institute_info"); 
         // Toast.makeText(HomeScreen.this, institute_info, Toast.LENGTH_SHORT).show(); 

         TextView search_filtera = (TextView) findViewById(R.id.search_filter); 

         // search_filtera.setText("Search for " + String.valueOf(a) + " institutions offering in Agriculture courses"); 
         search_filtera.setText(search_filter); 


         participantArrayList.add(new ParticipantItem(offered_by_detail, logo, course, total_views, course_info, duration, tution_fee, other_payable_fee, intake, campus, entry_requirement, longitude, latitude, search_filter, institute_info, total_course_offered, feature_course, total_views_course)); 
        } catch (JSONException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
         pDialog.dismiss(); 
        } 
       } 

      } else { 

      } 
      pAdapter = new ParticipantsAdapter(getApplicationContext(), participantArrayList); 
      listview.setAdapter(pAdapter); 

     } 

     protected String doInBackground(final String... args) { 
      HttpHandler sh = new HttpHandler(); 
      jsonOuterArray = new JSONArray(); 
      String jsonOuterArray = sh.makeServiceCall(url); 
      return null; 

     } 
    } 



} 
+0

あなたはapiを投稿できますか? – HaroldSer

+0

http://findcourse.net/search_result.php?search=&study_field=17 – SAK

+0

@SAKあなたのログを投稿すると、あなたはjsonの解析で間違っていると思います。 –

答えて

0

エラーは、あなたのdoInBackground()でnullを返すことが原因である可能性があります。その後、JSON

try { 
     ObjectMapper objectMapper = new ObjectMapper(); 
     TypeReference<List<ParticipantItem>> mapType = new 
         TypeReference<List<ParticipantItem>>() {}; 
     participantArrayList= objectMapper.readValue(jsonOuterArray,mapType) ; 

     } catch (IOException e) { 
       e.printStackTrace(); 
     } 
0

からのオブジェクトの一覧をretriveする

あなたのJSONのマッピングを簡単にする、あなたのGradleファイルに以下を追加

compile 'com.fasterxml.jackson.core:jackson-databind:2.3.2' 

あなたJsonArray長はあなたから割り当てる必要が空でありますあなたのAsyntaskの応答。それは以下のコードを参照してください。

HttpManager:ジャワ

public class HttpManager { 

public static String getResponse(RequestPackage p) { 

    BufferedReader reader = null; 
    String uri = p.getUri(); 

    //Managing GET request using appending parameter to the url 
    if(p.getMethod().equals("GET")) { 

     uri += "?" + p.getEncodedParams(); 
    } 

    try { 

     URL url = new URL(uri); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     con.setRequestMethod(p.getMethod()); 

     //Managing POST request using OutPutStream 
     if (p.getMethod().equals("POST")) { 
      con.setDoOutput(true); 
      OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream()); 
      writer.write(p.getEncodedParams()); 
      writer.flush(); 
     } 

     StringBuilder sb = new StringBuilder(); 
     reader = new BufferedReader(new InputStreamReader(con.getInputStream())); 

     String line; 
     while ((line = reader.readLine()) != null) { 

      sb.append(line + "\n"); 

     } 
     return sb.toString(); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
     return null; 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } 
      catch (IOException ex) { 
       ex.printStackTrace(); 
       return null; 
      } 
     } 
    } 

} 

}

RequestPackage.Java

public class RequestPackage { 
private String uri; 
private String method = "GET"; 
private Map<String,String> params = new HashMap<>(); 

public Map<String, Integer> getParamsInt() { 
    return paramsInt; 
} 

public void setParamsInt(Map<String, Integer> paramsInt) { 
    this.paramsInt = paramsInt; 
} 

private Map<String,Integer> paramsInt = new HashMap<>(); 

public String getUri() { 
    return uri; 
} 

public void setUri(String uri) { 
    this.uri = uri; 
} 

public String getMethod() { 
    return method; 
} 

public void setMethod(String method) { 
    this.method = method; 
} 

public Map<String, String> getParams() { 
    return params; 
} 

public void setParams(Map<String, String> params) { 
    this.params = params; 
} 

public void setParams(String key, String value) { 
    params.put(key,value); 
} 


public String getEncodedParams() { 
    StringBuilder sb = new StringBuilder(); 
    for(String key : params.keySet()) { 
     String value = null; 

     try{ 
      value = URLEncoder.encode(params.get(key),"UTF-8"); 
     } 
     catch(UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 

     if(sb.length() > 0) 
     { 
      sb.append("&"); 
     } 

     sb.append(key + "=" + value); 
    } 
    return sb.toString(); 
} 

}

MainActivity.Java

public class MainActivity extends AppCompatActivity { 
private ProgressDialog pDialog; 
ArrayList<Result> participantArrayList; 
ParticipantsAdapter pAdapter; 
Integer a; 
JSONArray jsonOuterArray=null; 

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


    //For GET request parameter pass through the url. 
    RequestPackage regPackage = new RequestPackage(); 
    regPackage.setMethod("GET"); 
    regPackage.setUri("http://findcourse.net/search_result.php?search=&study_field=17"); 
    new webTask().execute(regPackage); 
} 

public class webTask extends AsyncTask<RequestPackage, String, String> { 

    @Override 
    protected void onPreExecute() { 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Loading..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 

     //You can also use progress dialog here 
     Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    protected String doInBackground(RequestPackage... requestPackages) { 

     String content = HttpManager.getResponse(requestPackages[0]); 
     return content; 
    } 

    @Override 
    protected void onPostExecute(String result) { 

     //Webserver will return response in a result variable. 
     String response = result; 
     Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show(); 
     pDialog.dismiss(); 
     try { 
      JSONArray jsonArray = new JSONArray(response); 
      for (int i = 0; i < jsonArray.length(); i++) { 
       JSONObject item = (JSONObject) jsonArray.get(i); 
       JSONObject message = item.getJSONObject("result"); 

       String offered_by_detail = message.getString("offered_by"); 

       String course = message.getString("course"); 
       String logo = message.getString("logo"); 
       String total_views = message.getString("total_views"); 
       String total_course_offered = message.getString("total_course_offered"); 
       Toast.makeText(MainActivity.this, 
         logo+ offered_by_detail + course, Toast.LENGTH_LONG).show(); 

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

    } 

} 

}

関連する問題