2016-07-15 8 views
0

데이터베이스에서 모든 데이터를 가져오고 싶지만 컴파일 오류가 있으며 안드로이드가 처음입니다. 이 클래스는 모든 사용자를 테이블에서 가져 와서 listview에 이름을 표시하려는 클래스입니다. 이름이없는 경우 username이 이름이됩니다. 프레임을 사용할 수 없다는 오류가 발생했습니다. 내가 POST 요청을 보낼 때JSon을 서버에서 ListView로 가져 오는 방법은 무엇입니까?

package com.gmakerorganisation.glocator.Fragments; 

import android.app.ProgressDialog; 
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.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 

import com.android.volley.RequestQueue; 
import com.gmakerorganisation.glocator.Config; 
import com.gmakerorganisation.glocator.GetAllUsers; 
import com.gmakerorganisation.glocator.R; 

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

import java.util.ArrayList; 
import java.util.HashMap; 


public class Sendrequest extends Fragment { 
    private RequestQueue requestQueue; 
    ArrayList<HashMap<String, String>> UserList; 
    private static final String TAG_ID = "id"; 
    private static final String TAG_USERNAME = "username"; 
    private static final String TAG_NAME = "name"; 
    private static final String TAG_PHONE = "phone"; 
    private static final String TAG_PROFILE = "profile"; 

    ListView listView; 
    public Sendrequest() { 
     // Required empty public constructor 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     // Inflate the layout for this fragment 
     View v=inflater.inflate(R.layout.fragment_sendrequest, container, false); 
     listView=(ListView)v.findViewById(R.id.list); 
     new GetStudents().execute(); 

     return v; 
    } 

    private class GetStudents extends AsyncTask<Void, Void, Void> { 

     // Hashmap for ListView 

     ProgressDialog pDialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 


     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      // Creating service handler class instance 
      GetAllUsers webreq = new GetAllUsers(); 

      // Making a request to url and getting response 
      String jsonStr = webreq.makeWebServiceCall(Config.USERS_URL, GetAllUsers.GET); 

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

      UserList = ParseJSON(jsonStr); 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      /** 
      * Updating parsed JSON data into ListView 
      li * */ 

      ListAdapter adapter = new SimpleAdapter(
        getActivity().getApplicationContext(), UserList, 
        R.layout.list_item, new String[]{TAG_NAME, TAG_PHONE}, new int[]{R.id.name, 
        R.id.mobile}); 
      listView.setAdapter(adapter); 
     } 

    } 

    private ArrayList<HashMap<String, String>> ParseJSON(String json) { 
     if (json != null) { 
      try { 
       // Hashmap for ListView 
       ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>(); 

       JSONObject jsonObj = new JSONObject(json); 

       // Getting JSON Array node 
       JSONArray userrs = jsonObj.getJSONArray(null); 

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

        String id = c.getString(TAG_ID); 
        String username = c.getString(TAG_USERNAME); 
        String name = c.getString(TAG_NAME); 
        String phone = c.getString(TAG_PHONE); 
        String profile = c.getString(TAG_PROFILE); 



        // tmp hashmap for single student 
        HashMap<String, String> user = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        user.put(TAG_ID, id); 
        user.put(TAG_USERNAME, username); 
        user.put(TAG_NAME, name); 
        user.put(TAG_PHONE, phone); 
        user.put(TAG_PROFILE, profile); 

        // adding student to students list 
        studentList.add(user); 
       } 
       return studentList; 
      } catch (JSONException e) { 
       e.printStackTrace(); 
       return null; 
      } 
     } else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
      return null; 
     } 
    } 



} 

GetAllUser 클래스는

<?php 

//If a post request is detected 
if($_SERVER['REQUEST_METHOD']=='POST'){ 


    //Importing the dbConnect script 
    require_once('conn.php'); 

    $users = array(); 

      $sql = "SELECT id , username, name, phone, profile FROM glocator"; 
      $result = mysqli_query($con,$sql); 

     if (mysqli_num_rows($result)>0) { 
      while ($row =mysqli_fetch_array($result)) { 
       $users['id'] = $row['id']; 
       $users['username'] = $row['username']; 
       $users['name'] = $row['name']; 
       $users['phone'] = $row['phone']; 
       $users['profile'] = $row['profile']; 

      echo json_encode($users); 
      } 
     } 


    //Closing the database 
    mysqli_close($con); 
} 
?> 

내가 우체부를 사용하고이 때문에이 데이터를 제공 내 PHP 소스 코드입니다

package com.gmakerorganisation.glocator; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLEncoder; 
import java.util.HashMap; 
import java.util.Map; 

import javax.net.ssl.HttpsURLConnection; 

/** 
* Created by user on 14-07-2016. 
*/ 
public class GetAllUsers { 
    static String response = null; 
    public final static int GET = 1; 
    public final static int POST = 2; 

    //Constructor with no parameter 
    public GetAllUsers() { 

    } 

    /** 
    * Making web service call 
    * 
    * @url - url to make request 
    * @requestmethod - http request method 
    */ 
    public String makeWebServiceCall(String url, int requestmethod) { 
     return this.makeWebServiceCall(url, requestmethod, null); 
    } 

    /** 
    * Making service call 
    * 
    * @url - url to make request 
    * @requestmethod - http request method 
    * @params - http request params 
    */ 
    public String makeWebServiceCall(String urladdress, int requestmethod, 
            HashMap<String, String> params) { 
     URL url; 
     String response = ""; 
     try { 
      url = new URL(urladdress); 

      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(15000); 
      conn.setConnectTimeout(15000); 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 

      if (requestmethod == POST) { 
       conn.setRequestMethod("POST"); 
      } else if (requestmethod == GET) { 
       conn.setRequestMethod("GET"); 
      } 

      if (params != null) { 
       OutputStream os = conn.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(
         new OutputStreamWriter(os, "UTF-8")); 

       StringBuilder result = new StringBuilder(); 
       boolean first = true; 
       for (Map.Entry<String, String> entry : params.entrySet()) { 
        if (first) 
         first = false; 
        else 
         result.append("&"); 

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); 
        result.append("="); 
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); 
       } 

       writer.write(result.toString()); 

       writer.flush(); 
       writer.close(); 
       os.close(); 
      } 

      int responseCode = conn.getResponseCode(); 

      if (responseCode == HttpsURLConnection.HTTP_OK) { 
       String line; 
       BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       while ((line = br.readLine()) != null) { 
        response += line; 
       } 
      } else { 
       response = ""; 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return response; 
    } 
} 

{"id":"1","username":"gmaker","name":"SHUBHAM SHARMA","phone":"9711979977","profile":"http:\/\/glocator.esy.es\/profilepicture\/1."}{"id":"4","username":"somnath","name":"","phone":"9582223881","profile":""}{"id":"7","username":"shitij","name":"","phone":"9650154839","profile":""}   
+0

무엇이 오류입니까? – Jas

+2

json 구조가 잘못되었습니다 – Jas

+0

json 잘못되었습니다. json 복사 및 붙여 넣기 http://jsonprettyprint.com/ –

답변

2

Json에게 몇 가지 오류가 있습니다. J를 복사하십시오. 아들을 확인하고 여기에서 확인하십시오.

[ 
    { 
    "id":"1", 
    "username":"gmaker", 
    "name":"SHUBHAM SHARMA", 
    "phone":"9711979977", 
    "profile":"http:\/\/glocator.esy.es\/profilepicture\/1." 
    }, 
    { 
    "id":"4", 
    "username":"somnath", 
    "name":"", 
    "phone":"9582223881", 
    "profile":"" 
    }, 
    { 
    "id":"7", 
    "username":"shitij", 
    "name":"", 
    "phone":"9650154839", 
    "profile":"" 
    } 
] 

지금 당신은 몇 가지 다음 자습서를 따를 수 :

그것의 필수처럼 보인다.

Android json parsing using okhttp example with new material design library

0

하여 JSON 파일이 코드를 시도하고 루프 제거 jsonarray..so의 객체를 생성하여 데이터를 검색하는 데 사용할 수있는 array.Then 포함되어 있지 않습니다.

JSONObject jsonObj = new JSONObject(json); 

// looping through All Students 
JSONObject c = JSONObject.getJSONObject(jsonobj); 

String id = c.getString(TAG_ID); 
String username = c.getString(TAG_USERNAME); 
String name = c.getString(TAG_NAME); 
String phone = c.getString(TAG_PHONE); 
String profile = c.getString(TAG_PROFILE); 
관련 문제