2016-07-14 2 views
0

데이터베이스에서 모든 데이터를 검색하고 싶지만 컴파일 오류가 있으며 Android를 처음 사용하고 있습니다. 이 클래스는 모든 사용자를 테이블에서 가져 와서 listview에 이름을 표시하려는 클래스입니다. 이름이없는 경우 username이 이름이됩니다. 프레임을 사용할 수 없다는 오류가 발생했습니다. 내가 POST 요청을 보낼 때Arraylist에서 Json Array 가져 오기

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

당신이 게시대로 구문 오류가 있기 때문에 당신이 서버에서 동일한 응답을 –

+0

응답 데이터가 사용자의 요구 사항과 같아졌고 –

+0

응답에 구문 오류가 있습니다. 한 번 확인하십시오. – Sairam

답변

0

다음 코드를 사용해 보자. u는 오류에 직면하는 경우가 .IT이처럼해야 JSON 응답하지

public class Sendrequest extends Fragment { 
ArrayList<ArrayList<String>> User_List; 
     private RequestQueue requestQueue; 
     ArrayAdapter<String> adapter; 
     List<String>names; 
     ArrayList<String> User; 
     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); 
User_List = new ArrayList<ArrayList<String>>(); 
User =new ArrayList<String>(); 
      showusers(); 
      listView=(ListView)v.findViewById(R.id.listView); 
      adapter = new ArrayAdapter(listView.getContext(), android.R.layout.simple_list_item_1, User_List); 
      listView.setAdapter(adapter); 
      listView.setEmptyView(v.findViewById(R.id.emptyElement)); 


      return v; 
     } 
     void showusers(){ 

      StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.USERS_URL, 
        new Response.Listener<JSONArray>() { 
         @Override 
         public void onResponse(JSONArray response) { 

          try 
          { 
           JSONArray jsonArray = new JSONArray(response); 
           for(int i=0;i<jsonArray.length();i++){ 
            JSONObject jresponse = 
              jsonArray.getJSONObject(i); 
            String id = 
              jresponse.getString("id"); 
            String username = 
              jresponse.getString("username"); 
            String phone = 
              jresponse.getString("phone"); 
            String name = 
              jresponse.getString("name"); 
            User.add(id); 
            User.add(username); 
            User.add(phone); 
            User.add(name); 
           User_List.add(i,User);} 


          } 
          catch (Exception e) 
          { 

          } 
         } 
        }); 
        new Response.ErrorListener() { 
         @Override 
         public void onErrorResponse(VolleyError error) { 

          Toast.makeText(getActivity().getApplicationContext(), error.getMessage(),Toast.LENGTH_LONG).show(); 
         } 
        }); 

      }; 
    } 
+0

아니 작동하지 않습니다. – Shubham

0

먼저 응답이 잘못 알고있는이

[{ 
    "0": "1", 
    "id": "1", 
    "1": "gmaker", 
    "username": "gmaker", 
    "2": "SHUBHAM SHARMA", 
    "name": "SHUBHAM SHARMA", 
    "3": "9711979977", 
    "phone": "9711979977" 
}, { 
    "0": "4", 
    "id": "4", 
    "1": "somnath", 
    "username": "somnath", 
    "2": "", 
    "name": "", 
    "3": "9582223881", 
    "phone": "9582223881" 
}, { 
    "0": "7", 
    "id": "7", 
    "1": "shitij", 
    "username": "shitij", 
    "2": "", 
    "name": "", 
    "3": "9650154839", 
    "phone": "9650154839" 
}]