2016-03-05 74 views
0

請幫我要回所有行和視圖列表視圖中:JSONArray返回第一行從PHP和SQL Server數據庫

ListView List; 
private ProgressDialog pDialog; 
JSONParser jParser = new JSONParser(); 
ArrayList<HashMap<String, String>> StudentList; 
private static String url_course_student = "http://10.0.2.2//mzn/android/StudentCourse.php"; 

private static final String TAG_SUCCESS = "success"; 
private static final String TAG_Student = "Student"; 
private static final String TAG_ID = "ID"; 
private static final String TAG_ModName = "ModName"; 
JSONArray Student = null; 

public StudentCourseFragment(){} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.fragment_student_course, container, false); 
    List = (ListView)rootView.findViewById(R.id.listStudentCourse); 
    StudentList = new ArrayList<HashMap<String, String>>(); 
    rootView.setFocusableInTouchMode(true); 
    rootView.requestFocus(); 
    rootView.setOnKeyListener(new OnKeyListener() 
    { 
     @Override 
     public boolean onKey(View v, int keyCode, KeyEvent event) 
     { 
      if(keyCode == KeyEvent.KEYCODE_BACK) 
      { 
       Fragment fragment = new HomeFragment(); 
       FragmentManager fragmentManager = getFragmentManager(); 
       fragmentManager.beginTransaction() 
         .replace(R.id.frame_container, fragment).commit(); 
       getActivity().getActionBar().setTitle(R.string.title); 

       return true; 
      } 
      return false; 
     } 
    }); 

    new StudentCourseClass().execute(); 

    return rootView; 
} 

class StudentCourseClass extends AsyncTask<String, String, String> { 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(getActivity()); 
     pDialog.setMessage("Loding ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    protected String doInBackground(String... args) { 

     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     JSONObject json = jParser.makeHttpRequest(url_course_student, "GET", params); 

     try { 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 

       Student = json.getJSONArray(TAG_Student); 

       for (int i = 0; i < Student.length(); i++) { 
        JSONObject c = Student.getJSONObject(i); 

        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_ModName); 

        HashMap<String, String> map = new HashMap<String, String>(); 

        map.put(TAG_ID, id); 
        map.put(TAG_ModName, name); 


        StudentList.add(map); 
       } 

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

     return null; 
    } 

    protected void onPostExecute(String file_url) { 

     pDialog.dismiss(); 

    getActivity().runOnUiThread(new Runnable() { 
      public void run() { 

       ListAdapter adapter = new SimpleAdapter(
         getActivity(), StudentList, 
         R.layout.course_customize, new String[] { TAG_ID, 
          TAG_ModName}, 
         new int[] { R.id.lblName, R.id.lblView }); 

       List.setAdapter(adapter); 

      } 
     }); 
    } 
} 

} 


<per> 

<?php 

$response = array(); 
$_POST["StudentID"]='4470'; 

if (isset($_POST["StudentID"])) { 

$StudentID = $_POST['StudentID']; 

require_once __DIR__ . '/db_connect.php'; 
$db = new DB_CONNECT(); 

$sql = "SELECT * FROM [DailyExams] where UserID = " . $StudentID; 

$stmt = sqlsrv_query($db->conn, $sql); 

if ($stmt) { 

$rows = sqlsrv_has_rows($stmt); 

if ($rows === true) { 

$response["success"] = 1; 
$i=1; 

$stmt = sqlsrv_query($db->conn, $sql); 

$result = array(); 

do { 
while ($result = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){ 

    $Student = array(); 
      $Student["ID"] = $i; 
      $Student["ModName"] = $result["ModName"]; 
      $Student["ModName"] = iconv('Windows-1256', 'UTF-8', $Student["ModName"]); 

      $response["Student"] = array(); 

      array_push($response["Student"], $Student); 

      print_r(json_encode($response)); 
      $i= $i + 1; 
} 
} while (sqlsrv_next_result($stmt)); 

sqlsrv_free_stmt($stmt); 
sqlsrv_close($db->conn); //Close the connnectiokn first 

echo json_encode($response); 

    } else { 

     $response["success"] = 0; 
     $response["message"] = "No Student found"; 

     echo json_encode($response); 
    } 
} else { 

    $response["success"] = 0; 
    $response["message"] = "No Student found"; 

    echo json_encode($response); 
} 
} else { 

$response["success"] = 0; 
$response["message"] = "Required field(s) is missing"; 

echo json_encode($response); 

} 

?> 

</per> 
+0

歡迎來到Stack Overflow!我編輯了你的問題的標題,以便更加簡潔,並將問題移到問題主體中。請在您的代碼示例中進行編輯,以應用正確的代碼樣式並正確縮進它,因爲它是不可讀的。祝你好運! – Wtower

回答

0

你必須創建一個自定義列表用於這一目的。

首先創建一個模型類:​​

public class StudentModel{ 
    public String name, id, image, description; 

    public String getName() { 
     return name; 
    } 

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

    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 
} 

後,一個適配器類:StudentAdapter

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.TextView; 
import java.util.List; 


public class StudentAdapter extends BaseAdapter { 

    // Declare Variables 
    private List<StudentModel> list; 
    private final Context context; 

    public StudentAdapter(Context context, List<StudentModel> list) { 
     this.context = context; 
     this.list=list; 
    } 

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

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

    @Override 
    public long getItemId(int position) { 
     return list.indexOf(list.get(position)); 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     LayoutInflater inflater; 

     TextView textView_name; 

     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View itemView = inflater.inflate(R.layout.artists_item, parent, 
       false); 

     textView_name=(TextView)itemView.findViewById(R.id.textView_artist); 
     textView_name.setText(list.get(position).getName()); 

     return itemView; 
    } 


} 

現在,在你的活動:

protected String doInBackground(String... args) { 

     List<NameValuePair> params = new ArrayList<NameValuePair>(); 

     JSONObject json = jParser.makeHttpRequest(url_course_student, "GET", params); 


     try { 

      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 

       Student = json.getJSONArray(TAG_Student); 

       for (int i = 0; i < Student.length(); i++) { 
        JSONObject c = Student.getJSONObject(i); 

        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_ModName); 

        HashMap<String, String> map = new HashMap<String, String>(); 

        map.put(TAG_ID, id); 
        map.put(TAG_ModName, name); 


        StudentList.add(model(TAG_ID, TAG_ModName)); 
       } 

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

     return null; 
    } 

保護無效onPostExecute(字符串file_url){

pDialog.dismiss(); 

getActivity().runOnUiThread(new Runnable() { 
     public void run() { 

       StudentAdapter adapter=new StudentAdapter(getActivity(),StudentList); 
            listView.setAdapter(adapter); 


           } 

     } 
    }); 

} 
    private StudentModel model(String id,String name) 
    { 
     StudentModel m = new StudentModel(); 
     m.setId(id); 
     m.setName(name); 
     return m; 
    } 
+0

謝謝,但JSONArray返回 [{「ID」:1,「ModName」:「Java」}] –

+0

@AbdulWahabBinYahya只有一個對象? –

+0

@AbdulWahabBinYahya好,但如果這些記錄增加,您的結果將在列表中查看。 :) –