2015-12-07 33 views
0

我有一個問題,我的列表視圖,它在仿真器上,但不是在真實的設備上。我使用2個真實設備進行了測試,但沒有填充。我使用json從數據庫中獲取listview數據。 Json結果是好的,因爲它打印到logcat並在仿真器上填充listview。ListView不能在真實設備上工作

ListView中的Java:

 public class ActivityRequestsFrom extends MainActivity implements AdapterView.OnItemClickListener { 

    ______________________________________________________________________________ 

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

    lv = (ListView) findViewById(R.id.listRequests); 

    RequestsAdapter adapter = new RequestsAdapter(this, arrRequest_Name, arrRequest_Number, 
      arrRequest_Username, arrRequest_Result, imageId); 

    lv.setAdapter(adapter);  
    lv.setOnItemClickListener(this); 

     } 

    ______________________________________________________________________________ 

    class RequestsAdapter extends ArrayAdapter<String> 
       { 
        Context context; 
        List<String> Request_Name; 
        List<String> Request_Number; 
        List<String> Request_Username; 
        List<String> Request_Result; 
        Integer[] imgid; 

    RequestsAdapter(Context c, List<String> Request_Name, 
        List<String> Request_Number, List<String> Request_Username, 
        List<String> Request_Result, Integer[] imgid) 
        { 

    super(c, R.layout.activity_requests_single, R.id.textName, Request_Name); 
        this.context=c; 
        this.Request_Name=Request_Name; 
        this.Request_Number=Request_Number; 
        this.Request_Username=Request_Username; 
        this.Request_Result=Request_Result; 
        this.imgid=imgid; 
        } 


    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
        // TODO Auto-generated method stub 
    View row=convertView;    
    if(row==null) 
     { 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    row = inflater.inflate(R.layout.activity_requests_single, parent, false);  } 
    TextView txtName = (TextView) row.findViewById(R.id.textName); 
    TextView txtNumber = (TextView) row.findViewById(R.id.textNumber); 
    TextView txtUsername = (TextView) row.findViewById(R.id.textUsername); 
    TextView txtResult = (TextView) row.findViewById(R.id.textResult); 
    ImageView imageView = (ImageView) row.findViewById(R.id.imageView); 
    Map<String, Integer> drawableMap = new HashMap<String, Integer>(); 
    drawableMap.put("ok",R.drawable.request_pending_from); 
    drawableMap.put("pending",R.drawable.request_pending_from);   
    drawableMap.put("rejected",R.drawable.request_rejected_from); 
      drawableMap.put("blocked",R.drawable.request_blocked_from); 
      txtName.setText(Request_Name.get(position)); 
      txtNumber.setText(Request_Number.get(position)); 
      txtUsername.setText(Request_Username.get(position)); 
      txtResult.setText(Request_Result.get(position)); 
      //imageView.setImageResource(imgid[position]); 
    imageView.setImageResource(drawableMap.get(Request_Result.get(position).toLowerCase())); 
    return row; 
         } 
        } 

    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
        // TODO Auto-generated method stub 

    TextView tvUsername = (TextView) view.findViewById(R.id.textUsername); 
    usernameSelected = tvUsername.getText().toString(); 

    TextView tvResult = (TextView) view.findViewById(R.id.textResult); 
    resultSelected = tvResult.getText().toString(); 

    if (resultSelected.equals("Pending")) 
     { 
     pendingOptions();     
     } 

    else if (resultSelected.equals("Rejected")) 
     { 
     rejectedOptions(); 
     } 

    else if (resultSelected.equals("Blocked")) 
     { 
     blockedOptions(); 

     } 

    else 
     { 
     } 


    } 

ListView的佈局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<ListView 
    android:id="@+id/listRequest" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 
</ListView> 

的ListView單個佈局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" > 

<TextView 
    android:id="@+id/textName" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_below="@+id/LLdummy" 
    android:text="Name" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:textStyle="italic" 
    android:layout_marginLeft="10dp" 
    /> 

<TextView 
    android:id="@+id/textUsername" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textNumber" 
    android:layout_alignParentRight="true" 
    android:layout_below="@+id/textNumber" 
    android:text="Username" 
    android:textAppearance="?android:attr/textAppearanceSmall" /> 



<TextView 
    android:id="@+id/textNumber" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textName" 
    android:layout_below="@+id/textName" 
    android:text="Number" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:textStyle="bold" /> 

<ImageView 
    android:id="@+id/imageView" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignRight="@+id/LLdummy" 
    android:layout_centerVertical="true" 
    android:src="@drawable/request_pending_to" /> 

的Json

private class JsonReadTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... params) { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(params[0]); 
     try { 
     HttpResponse response = httpclient.execute(httppost); 
     jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); 
     } 


     catch (ClientProtocolException e) { 
     e.printStackTrace(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 
     return null; 
     } 

     private StringBuilder inputStreamToString(InputStream is) { 
     String rLine = ""; 
     StringBuilder answer = new StringBuilder(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 

     try { 
     while ((rLine = rd.readLine()) != null) { 
     answer.append(rLine); 
     } 
     } 

     catch (IOException e) { 
     // e.printStackTrace(); 
     Toast.makeText(getApplicationContext(),"Error..." + e.toString(), Toast.LENGTH_LONG).show(); 
     } 
     return answer; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
     try{ 
     ListDrwaer(); //has ConnectionException (when it cannot reach server) 
     }catch (Exception e){ 
      Toast.makeText(getApplicationContext(), "Please check your connection..", Toast.LENGTH_LONG).show(); 
      } 
     } 
    }// end async task 

    public void accessWebService() { 
     JsonReadTask task = new JsonReadTask(); 
     // passes values for the urls string array 
     task.execute(new String[] { "http://server/file.php?pIMEI="+IMEI }); 
     } 

    // build hash set for list view 
    public void ListDrwaer() { 

     try { 
     JSONObject jsonResponse = new JSONObject(jsonResult); 
     JSONArray jsonMainNode = jsonResponse.optJSONArray("request_info"); 

     for (int i = 0; i < jsonMainNode.length(); i++) { 
     JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 

     String request_name = jsonChildNode.optString("Request_Name"); 
     String request_number = jsonChildNode.optString("Request_Number"); 
     String request_username = jsonChildNode.optString("Request_Username"); 
     String request_result = jsonChildNode.optString("Request_Result"); 

     arrRequest_Name.add(request_name); 
     arrRequest_Number.add(request_number); 
     arrRequest_Username.add(request_username); 
     arrRequest_Result.add(request_result); 

     System.out.println("Request_Name: "+request_name); 
     System.out.println("Request_Number: "+request_number); 
     System.out.println("Request_Username: "+request_username); 
     System.out.println("Request_Result: "+request_result); 

     } 
     } catch (JSONException e) { 
      System.out.println("Json Error Requests" +e.toString()); 
      Toast.makeText(getApplicationContext(), "No Requests Pending", Toast.LENGTH_SHORT).show(); 

     } 
} 

呼叫異步

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

    ... 

    accessWebService(); 

    //ListView 
    lv = (ListView) findViewById(R.id.listRequests); 

    RequestsAdapter adapter = new RequestsAdapter(this, arrRequest_Name, arrRequest_Number, arrRequest_Username, arrRequest_Result, imageId); 
    lv.setAdapter(adapter); 
    lv.setOnItemClickListener(this); 
+0

凡/時/你是如何填補這些名單? – codeMagic

+0

沒有任何強制關閉發生? –

+0

@codeMagic我編輯,包括JSON代碼,我添加數據到列表視圖 – user3560827

回答

2

的這裏的問題是,當Adapter設置在ListView數據沒有收到。這是因爲數據被填充在AysncTask中,這是異步本質上。這意味着它會在後臺,而其他代碼運行(即ListView填充運行。

所以,在onPostExecute()你需要使用notifyDataSetChanged()ListView知道有新項目來填充。

@Override 
    protected void onPostExecute(String result) { 
    // your code 

    adapter.notifyDataSetChanged(); // this line here 
}// end async task 

在你的榜樣,這顯然需要你作出Adapter一個成員變量或將它傳遞給你的AsyncTask

+0

因此,假設模擬器比實際設備更快地運行後臺任務是安全的。 – user3560827

+1

@ user3560827不,我不會這樣認爲。可能發生的情況是,該任務偶爾會在真實設備上完成。重要的是要知道它可能會或可能不會(但很可能不會)在其他代碼運行之前完成。因此,請務必確保您能夠解釋並將相關代碼放在適當的位置。 – codeMagic

相關問題