无法将我的布局更改为listview

时间:2015-01-08 05:56:00

标签: android mysql listview

这是我的代码,用于通过php从mysql数据库中选择图像和文本。它在scrollview中以linearlayout显示。我想做的就是将我的布局更改为listview,如this example. 我尝试了listview和其他很多方法,但它没有正常工作。我是android的新手,所以我很长时间都在尝试。请帮我编辑我的代码以满足我的要求。请。

JAVA

    @SuppressLint("NewApi") 
    public class News_and_events extends Fragment {

        private String jsonResult;
        private String url = "http://192.168.2.7/crescentnews/select.php";
        HttpPost httppost;
        StringBuffer buffer;
        HttpResponse response;
        HttpClient httpclient;
        List<NameValuePair> nameValuePairs;
        ProgressDialog dialog = null;
        ImageView img;
        Bitmap bitmap;
        ProgressDialog pDialog;


       // alert dialog manager
        AlertDialogManager alert = new AlertDialogManager();

        // Internet detector
        ConnectionDetector cd;

         InputStream is=null;
         String result=null;
            String line=null;
            int code;

        public News_and_events(){}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
             pDialog = new ProgressDialog(getActivity());
            View rootView = inflater.inflate(R.layout.activity_news_and_events, container, false);

            cd = new ConnectionDetector(rootView.getContext());

            // Check if Internet present
            if (!cd.isConnectingToInternet()) {
                // Internet Connection is not present
                alert.showAlertDialog(getActivity(),
                        "Internet Connection Error",
                        "Please connect to working Internet connection", false);
                // stop executing code by return
                //return.rootView;
                return rootView;
            }

            accessWebService();
            return rootView;
        }

        // Async Task to access the web
         private class JsonReadTask extends AsyncTask<String, Void, String> {
          @Override
          protected String doInBackground(String... params) { 
              List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);


           HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost(params[0]);
           try {

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            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(getActivity().getApplicationContext(),
              "Error..." + e.toString(), Toast.LENGTH_LONG).show();
           }
           return answer;
          }

          @Override
          protected void onPostExecute(String result) {
           display();
          }
         }// end async task

         public void accessWebService() {
          JsonReadTask task = new JsonReadTask();
          // passes values for the urls string array
          task.execute(new String[] { url });
         }

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


          try {
           JSONObject jsonResponse = new JSONObject(jsonResult);
           JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
           LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout); 
           //LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);

           for (int i = 0; i < jsonMainNode.length(); i++) {
               JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                final String head = jsonChildNode.optString("title");
                final String details = jsonChildNode.optString("text");
                final String date = jsonChildNode.optString("date");
                final String image = jsonChildNode.optString("img");
                //final String time = jsonChildNode.optString("time");
                //img = new ImageView(this.getActivity());
                //new LoadImage().execute("http://192.168.2.7/crescentnews/images/"+image);

                img = new ImageView(this.getActivity());
              //  Toast.makeText(getActivity(),image, Toast.LENGTH_LONG).show();

                LoadImage ldimg=new LoadImage();
                ldimg.setImage(img);
                ldimg.execute("http://192.168.2.7/crescentnews/images/"+image);


                TextView headln = new TextView(this.getActivity());
                headln.setText(head); // News Headlines
                headln.setTextSize(16);
                headln.setTextColor(Color.BLACK);
                headln.setGravity(Gravity.CENTER);
                headln.setBackgroundColor(Color.parseColor("#ffcd14"));
              //  headln.setBackgroundResource(R.drawable.menubg);
                headln.setPadding(0, 20, 0, 0);
              //  headln.setHeight(50);
                headln.setClickable(true);


                TextView dateln = new TextView(this.getActivity());
                dateln.setText(date); // News Headlines
                dateln.setTextSize(12);
                dateln.setTextColor(Color.BLACK);
                dateln.setGravity(Gravity.RIGHT);
                //dateln.setBackgroundColor(Color.parseColor("#f20056"));
                dateln.setBackgroundColor(0x00000000);
                dateln.setPadding(0, 0, 10, 10);
                dateln.setWidth(100);
                dateln.setClickable(true);



                View sep=new View(this.getActivity());
                sep.setBackgroundColor(Color.parseColor("#252525"));
                sep.setMinimumHeight(10);

                TextView detailsln = new TextView(this.getActivity());
                detailsln.setText(details); // News Details
                detailsln.setTextSize(12);
                detailsln.setTextColor(Color.BLACK);
                detailsln.setGravity(Gravity.CENTER);
                detailsln.setPadding(10, 10, 10, 10);

                int width = LayoutParams.WRAP_CONTENT;
                int height = 200;
               LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
               img.setLayoutParams(parms);
               parms.gravity = Gravity.CENTER;
               img.setPaddingRelative (15, 15, 15, 15);

                MainLL.addView(headln);
                MainLL.addView(dateln);
             //   MainLL.addView(photo);
                MainLL.addView(img);
                MainLL.addView(detailsln);
                MainLL.addView(sep);

                img.setClickable(true);

               // img.buildDrawingCache();  
               // final Bitmap bmap = img.getDrawingCache();
                headln.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
                        intent.putExtra("head",head.toString());
                        intent.putExtra("details",details.toString());
                        intent.putExtra("date",date.toString());
                        intent.putExtra("image", image);
                        startActivity(intent);       

                    }
                });

                dateln.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                       // TODO Auto-generated method stub
                    Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
                    intent.putExtra("head",head.toString());
                    intent.putExtra("details",details.toString());
                    intent.putExtra("date",date.toString());
                    intent.putExtra("image", image);
                    startActivity(intent);       
                    }
                });

                img.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                        // TODO Auto-generated method stub
                    Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
                    intent.putExtra("head",head.toString());
                    intent.putExtra("details",details.toString());
                    intent.putExtra("date",date.toString());
                    intent.putExtra("image", image);
                    startActivity(intent);       
                    }
                });

                detailsln.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                           // TODO Auto-generated method stub
                        Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
                        intent.putExtra("head",head.toString());
                        intent.putExtra("details",details.toString());
                        intent.putExtra("date",date.toString());
                        intent.putExtra("image", image);
                        startActivity(intent);       
                        }
                    });
           }
          } catch (JSONException e) {
           Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
             Toast.LENGTH_SHORT).show();
          }
           }

         private class LoadImage extends AsyncTask<String, String, Bitmap> {
             ImageView img;
                         @Override
                             protected void onPreExecute() {
                                 super.onPreExecute();

                                 pDialog.setMessage("Loading Image ....");
                                 pDialog.show();


                         }
             public void setImage(ImageView img ){
             this.img=img;
             }

             protected Bitmap doInBackground(String... args) {
                 try {
                     bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
                     } 
                 catch (Exception e) { e.printStackTrace(); }
                 return bitmap;
             }

             protected void onPostExecute(Bitmap image) {
                  if(image != null){
                      img.setImageBitmap(image);

                      pDialog.dismiss(); 
                  }
                  pDialog.dismiss(); 
             } 

         }

         public static boolean isInternetReachable()
         {
             try {
                 //make a URL to a known source
                 URL url = new URL("http://www.google.com");

                 //open a connection to that source
                 HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();

                 //trying to retrieve data from the source. If there
                 //is no connection, this line will fail
                 Object objData = urlConnect.getContent();

             } catch (UnknownHostException e) {
                 e.printStackTrace();
                 return false;
             }
             catch (IOException e) {
                 e.printStackTrace();
                 return false;
             }
             return true;
         }
    }

XML     

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"![enter image description here][1]
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:baselineAligned="false"

         >

        <LinearLayout
                android:id="@+id/newslayout"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:background="#ffffff"

                >     

            </LinearLayout>


    </LinearLayout>



    </ScrollView>

    </LinearLayout>

1 个答案:

答案 0 :(得分:0)

您无法从AsyncTask中调用display()来在listview中显示结果。

您应该按照以下步骤

  1. 在创建内部,调用AsyncTask从服务器获取数据并将其填充到数组列表中。当异步任务正在运行时,请确保显示进度对话框,以便用户无法在UI线程中执行任何操作。

  2. 在创建内部,请初始化您的列表视图。

  3. 在AsyncTask的Post执行中,在填充了arraylist中的所有元素之后,调用适配器来填充listview。

  4. 定义一个扩展BaseAdapter的适配器,您可以使用该适配器从数组列表中填充listview。

  5. 您可能需要查看this link以获取类似的工作示例。