2015-01-07 5 views
0

여기에 PHP 코드를 통해 mysql 데이터베이스에서 이미지와 텍스트를 선택하기위한 y 코드가 있습니다. 그리고 scrolllay.All에서 선형 레이어에 표시하고 있습니다. 디스플레이의 정렬을 변경하는 것입니다. 많은 방법을 시도했지만 작동하지 않습니다. 알았어. 안드로이드에 새로 왔어. 아무도 나를 도와 주지마.이미지와 텍스트를 루프의 양면에 표시하는 방법은 무엇입니까?

JAVA

import java.io.BufferedReader; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.UnknownHostException; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.annotation.SuppressLint; 
import android.app.ActionBar.LayoutParams; 
import android.app.Fragment; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Color; 
import android.graphics.drawable.BitmapDrawable; 
import android.graphics.drawable.Drawable; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.view.Gravity; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

@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

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

    <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> 

필수 표시 스타일 http://wptrafficanalyzer.in/blog/wp-content/uploads/2012/09/listview_with_sdcard_screenshot.png

+0

먼저, 다음 XML의 행에 대해 하나의 레이아웃을 정의합니다. 이 링크를 참조하십시오 : http://developer.android.com/guide/topics/ui/layout/listview.html – Shahzeb

답변

0

레이아웃에 대한 디자인 방식이 잘못되었습니다. 서로 다른 데이터에 대해 동일한 레이아웃이 반복되는 디자인에서 이러한 레이아웃이 필요한 경우 ListView을 사용하십시오. 현재 ListView에 대해 자세히 알아볼 수 있습니다 : 당신이 그런 디자인을 구현하기 목록보기를 사용하는 데 필요한 모든의

http://developer.android.com/guide/topics/ui/layout/listview.html

+0

내 요구 사항에 맞게 코드를 수정하십시오. – Ashfaq

+0

Listview를 구현하려면 자습서를 따라야합니다. 또한 Adapter for ListView를 구현해야하며 JSON에서 데이터를 가져온 후에 해당 어댑터를 ListView로 설정해야합니다. 웹에는 수십 개의 Listview 예제가 있습니다. 그 중 일부는 다음과 같습니다. http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=9 http://www.vogella.com/tutorials/AndroidListView/article.html – Shahzeb

관련 문제