2012-01-07 4 views
0

이것은 원격 mySQL 데이터베이스에서 채워진 ListActivity를 작성한 첫 시도입니다. 로컬 SQLite 데이터베이스에서 데이터를 가져 오는 동안이 잘 작동했다. 대신 원격 데이터베이스에서 데이터를 가져 오기 위해 클래스를 수정해야하므로 튜토리얼 및 문서를 따라 수업을 조정하려고했습니다. 내 견해가 복잡하고 'getExtras'를 사용하기 때문에이를 파악할 수 없습니다.ListActivity에 빈 화면이 있습니다.

제 질문은 : 이제 개정판에서 LogCat에 오류없이 반환 된 빈 목록이 표시됩니다. 그래서 당신은 무엇을 볼 수 있습니다 내 수업에 잘못입니까? 추천?

public class QueryDisplayList extends ListActivity { 

    private static final String PHP_KEY = "PHP_KEY"; 
    private static final String QUERY_ORDER = "QUERY_ORDER"; 

    JSONArray jArray; 
    String result = null; 
    InputStream is = null; 
    StringBuilder sb = null; 

    // private Object tvLabel = null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     Bundle extras = getIntent().getExtras(); 
     setContentView(R.layout.list_view2); 

     /** 
     * Get the query string from last activity and pass it to this 
     * activity----------------------------------------------------- 
     */ 
     // String p = null; 
     // if (extras != null) { 
     // p = extras.getString(PHP_KEY); 
     // } 
     loadQuery(); 
    } 

    void loadQuery() { 

     new Thread(new Runnable() { 

      public void run() { 

       String qO = getIntent().getStringExtra("QUERY_ORDER"); 
       String php = getIntent().getStringExtra("PHP_KEY"); 

       ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
       // http post 
       try { 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost(
          "http://10.0.2.2/App/php/" + php + qO + ".php"); 

        Log.e("log_tag", "Fetched " + php + qO + ".php"); 

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 

       } catch (Exception e) { 

        Log.e("log_tag", "Error in http connection " + e.toString()); 
       } 

       // convert response to string 
       try { 
        BufferedReader reader = new BufferedReader(
          new InputStreamReader(is, "iso-8859-1"), 8); 
        sb = new StringBuilder(); 
        sb.append(reader.readLine() + "\n"); 

        String line = "0"; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 

        is.close(); 
        result = sb.toString(); 

       } catch (Exception e) { 
        Log.e("log_tag", "Error converting result " + e.toString()); 
       } 

      } 
     }).start(); 

     setListAdapter(new QueryAdapter(this, result)); 
    } 

    /** 
    * The Query Adaptor -------------------------------------------- 
    */ 

    private class QueryAdapter extends ArrayAdapter<String> { 

     private Activity context; 

     public QueryAdapter(Activity context, String result) { 
      super(context, R.layout.list_view2); 
      this.context = context; 
     } 

     public View getView(int position, View convertView, ViewGroup parent) { 
      LayoutInflater inflater = context.getLayoutInflater(); 
      View rowView = inflater.inflate(R.layout.list_item, null, true); 

      try { 
       jArray = new JSONArray(result); 
       JSONObject json_data = null; 

       for (int i = 0; i < jArray.length(); i++) { 

        json_data = jArray.getJSONObject(i); 

        final String tvLabel = json_data.getString("label"); 
        TextView labelTxt = (TextView) convertView 
          .findViewById(R.id.label); 
        if (labelTxt != null) { 
         labelTxt.setText("(" + tvLabel + ")"); 
        } 

        final String tvTitle = json_data.getString("title"); 
        TextView titleTxt = (TextView) convertView 
          .findViewById(R.id.listTitle); 
        if (titleTxt != null) { 
         titleTxt.setText(tvTitle); 
        } 

        String tvDescription = json_data.getString("description"); 
        TextView descriptionTxt = (TextView) convertView 
          .findViewById(R.id.caption); 
        if (descriptionTxt != null) { 
         descriptionTxt.setText(tvDescription); 
        } 

        String tvDate = json_data.getString("date"); 
        TextView dateTxt = (TextView) convertView 
          .findViewById(R.id.dateAdded); 
        if (dateTxt != null) { 
         dateTxt.setText(tvDate); 
        } 

        String tvGoto = json_data.getString("gotoURL"); 
        TextView gotoTxt = (TextView) convertView 
          .findViewById(R.id.dummy); 
        if (gotoTxt != null) { 
         gotoTxt.setText(tvGoto); 
        } 

        gotoTxt.setVisibility(View.GONE); 
        convertView.setTag(gotoTxt); 

        final String ni = json_data.getString("intent"); 

        final ListView lv = getListView(); 
        lv.setEnabled(true); 
        lv.setClickable(true); 

        /** 
        * Click Listeners -------------------------------- 
        */ 
        lv.setOnItemClickListener(new OnItemClickListener() { 

         @Override 
         public void onItemClick(AdapterView<?> arg0, View v, 
           int arg2, long arg3) { 

          // -- Set the domain name in the strings.xml file 
          // once 
          // the 
          // DNS is established for the website. 
          String mDomain = getResources().getString(
            R.string.domain); 

          String url = ""; 
          url = mDomain + (String) v.getTag(); 

          String intent = ni; 
          Class<?> nIntent = null; 
          try { 
           nIntent = Class 
             .forName("com.andaerosystems.andaero.utili." 
               + intent); 
          } catch (ClassNotFoundException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 

          Intent i = new Intent(QueryDisplayList.this, 
            nIntent); 
          i.putExtra("PHP_KEY", tvLabel); 
          i.putExtra("KEY_URL", url); 
          i.putExtra("KEY_SUBTITLE", tvTitle); 
          i.putExtra("KEY_LABEL", tvLabel); 
          i.putExtra("KEY_INTENT", intent); 
          i.putExtra("QUERY_ORDER", "ASC"); 
          i.putExtra("KEY_YPOS", "0.0"); 
          QueryDisplayList.this.startActivity(i); 

          Log.e("tag", url); 
         } 
        }); 
       } 
      } catch (JSONException e1) { 
       Toast.makeText(getBaseContext(), "No label Found", 
         Toast.LENGTH_LONG).show(); 
      } catch (ParseException e1) { 
       e1.printStackTrace(); 
      } 
      return rowView; 
     } 
    } 
} 

답변

0

코드를 빠르게 살펴 봤습니다. 이 시도.

void loadQuery() { 

     new Thread(new Runnable() { 

      public void run() { 

       String qO = getIntent().getStringExtra("QUERY_ORDER"); 
       String php = getIntent().getStringExtra("PHP_KEY"); 

       ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
       // http post 
       try { 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost(
          "http://10.0.2.2/App/php/" + php + qO + ".php"); 

        Log.e("log_tag", "Fetched " + php + qO + ".php"); 

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 
        is = entity.getContent(); 

       } catch (Exception e) { 

        Log.e("log_tag", "Error in http connection " + e.toString()); 
       } 

       // convert response to string 
       try { 
        BufferedReader reader = new BufferedReader(
          new InputStreamReader(is, "iso-8859-1"), 8); 
        sb = new StringBuilder(); 
        sb.append(reader.readLine() + "\n"); 

        String line = "0"; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 

        is.close(); 
        result = sb.toString(); 
        YourActivity.this.runOnUiThread(new Runnable(){ 

      @Override 
      public void run() { 
       YourActivity.this.setListAdapter(new QueryAdapter(this, result)); 
      }}); 

       } catch (Exception e) { 
        Log.e("log_tag", "Error converting result " + e.toString()); 
       } 


      } 
     }).start(); 


    } 
+0

Thnx! 그게 앞으로 나아 갔지만 지금은 치명적인 예외 : 주 'java.lang.ClassCastException : com.andaerosystems.andaero.utili.QueryDisplayList $ 1 $ 1을 android.content.Context com.andaerosystems.andaero에서 캐스팅 할 수 없습니다. utili.QueryDisplayList $ QueryAdapter' 여기에서 무엇을해야할지 모르십니까? 더 이상 도움이 필요합니까? Thnx! @Nikola Despotoski – CelticParser

+0

잘못된 캐스팅을하고 있습니다 ... 예외가 발생한 행을 확인하십시오. –

0

단계별로 디버그하고 결과 값을 체크 아웃 했습니까?

예 : json 파일을 구문 분석 할 때 오타 또는 getString()의 오류로 인해 프로세스가 중지됩니다.

0

우선, 응답을 받기 전에 어댑터가 만들어지기 때문에 HttpPost에서받은 새로운 결과를 어댑터로 전달하지 마십시오.

또한 getView은 이와 같이 사용되지 않습니다. 그것이하는 일은 목록에 하나의 항목을 만드는 것입니다. 당신이하고있는 일은 모든 아이템을 만드는 것입니다. 수행해야 할 작업은 데이터를 구문 분석하고 분석 된 데이터가있는 목록을 어댑터에 추가하는 것입니다.

이 예를 보려면 http://sudarmuthu.com/blog/using-arrayadapter-and-listview-in-android-applications을보십시오.

관련 문제