0

J'ai converti plusieurs activités en fragments, tous fonctionnent bien sauf un. Dans la version précédente de ce fichier java, il était en train d'étendre ListActivity, maintenant je l'ai remplacé par ListFragment. Initialement, il donnait une exception nullPointerException, mais avec l'aide de this post, j'ai réussi à supprimer l'erreur. Maintenant, il récupère des données dans l'adaptateur mais pas dans listview (que j'ai vérifié en l'imprimant dans le journal). J'ai donc besoin de montrer les données dans listview.Données dans l'adaptateur mais ne se trouvant pas dans Listview | convertit Listactivity en ListFragment

Voici le code Java:

import java.text.DecimalFormat; 
import java.util.ArrayList; 
     import java.util.HashMap; 
     import org.json.JSONArray; 
     import org.json.JSONException; 
     import org.json.JSONObject; 
import android.content.res.Resources; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.drawable.BitmapDrawable; 

import android.app.ListActivity; 
     import android.app.ProgressDialog; 
     import android.content.Intent; 
import android.graphics.drawable.Drawable; 
import android.graphics.drawable.GradientDrawable; 
import android.os.AsyncTask; 
     import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.ListFragment; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
     import android.widget.AdapterView.OnItemClickListener; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.ListAdapter; 
     import android.widget.ListView; 
import android.widget.RelativeLayout; 
import android.widget.SimpleAdapter; 
     import android.widget.TextView; 
import java.io.InputStreamReader; 
import java.net.URL; 
import java.io.BufferedReader; 
import java.net.URLConnection; 
import android.support.v4.app.Fragment; 


public class listtojson extends ListFragment { 

    private ProgressDialog pDialog; 

    // URL to get contacts JSON 
    // public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listFileDir.php"; 
    public static String url = "http://www.newsvoice.in/upload_audio_sawdhan/listnews.php"; 
    //public static String url = "http://www.newsvoice.in/sites/listNewsSites.php"; 

    // JSON Node names 
    private static final String TAG_CONTACTS = "contacts"; 
    private static final String TAG_ID = "id"; 
    private static final String TAG_NAME = "name"; 
    private static final String TAG_SIZE = "size"; 
    private static final String TAG_PHONE_URL = "url"; 
    private static final String TAG_FILETYPE = "filetype"; 
    private static final String TAG_FILETYPETXT = "filetypetxt"; 
    private static final String TAG_DETAILS = "details"; 
    private static final String TAG_FILEPATH = "filepath"; 
    private static final String TAG_LOCATION = "location"; 
    private static final String TAG_DATETIME = "datetime"; 
    private static final String TAG_USERNAME = "username"; 
    private static final String TAG_HIGHALERT= "highalert"; 
    // public ImageLoader imageLoader; 
    public int ssid ; 
    // contacts JSONArray 
    JSONArray contacts = null; 
    public TextView view1; 
    ListView lv; 
    // Hashmap for ListView 
    ArrayList<HashMap<String, String>> contactList; 
    View fragment; 
    LinearLayout llLayout; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     FragmentActivity faActivity = (FragmentActivity) super.getActivity(); 

     llLayout = (LinearLayout) inflater.inflate(R.layout.listnewsjson, container, false); 

     contactList = new ArrayList<HashMap<String, String>>(); 
     fragment = inflater.inflate(R.layout.listnewsjson, container, false); 
    return llLayout; 
    } 
    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 

     super.onActivityCreated(savedInstanceState); 

    lv = (ListView) fragment.findViewById(android.R.id.list); 




     lv.setOnItemClickListener(new OnItemClickListener() { 

      public void onItemClick(AdapterView<?> parent, View view, 
            int position, long id) { 
       String name = ((TextView) view.findViewById(R.id.name)) 
         .getText().toString(); 
       String size = ((TextView) view.findViewById(R.id.size)) 
         .getText().toString(); 
       String description = ((TextView) view.findViewById(R.id.url)) 
         .getText().toString(); 
       String details = ((TextView) view.findViewById(R.id.details)) 
         .getText().toString(); 
       String location = ((TextView) view.findViewById(R.id.location)) 
         .getText().toString(); 
       String datetime = ((TextView) view.findViewById(R.id.datetime)) 
         .getText().toString(); 
       String filetype = ((TextView) view.findViewById(R.id.filetypetxt)) 
         .getText().toString(); 
       String username = ((TextView) view.findViewById(R.id.username)) 
         .getText().toString(); 
       //String highalert = ((TextView) view.findViewById(R.id.highalert)).getText().toString(); 
       //ImageView thumb_image=(ImageView)view.findViewById(R.id.filetype); 
       // ImageView image = (ImageView) view.findViewById(R.id.filetype); 
// thumb image 
       //= String filetype = ((ImageView) view.findViewById(R.id.filetype)) 
       //= .getText().toString(); 
       // Starting single contact activity 
       /* Intent in = new Intent(getApplicationContext(), 
         fileDownloader.class); 
       in.putExtra(TAG_NAME, name); 
       in.putExtra(TAG_SIZE, cost); 
       in.putExtra(TAG_PHONE_URL, description); 
       startActivity(in); 
*/ 

       Intent in = new Intent(getActivity().getApplicationContext(), jsondetailActivity.class); 
       // passing sqlite row id 
       //= in.putExtra(TAG_ID, sqlite_id); 
       in.putExtra(TAG_ID, String.valueOf(id)); 
       in.putExtra(TAG_NAME, name); 
       in.putExtra(TAG_DETAILS, details); 
       in.putExtra(TAG_LOCATION, location); 
       in.putExtra(TAG_DATETIME, datetime); 
       in.putExtra(TAG_FILETYPE, filetype); 
       in.putExtra(TAG_PHONE_URL, description); 
       in.putExtra(TAG_SIZE, size); 
       in.putExtra(TAG_USERNAME, username); 
       startActivity(in); 

      } 
     }); 

     // Calling async task to get json 
     new GetContacts().execute(); 
     //return llLayout; 
    } 

    /** 
    * Async task class to get json by making HTTP call 
    * */ 
    private class GetContacts extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Showing progress dialog 
      pDialog = new ProgressDialog(getActivity()); 
      pDialog.setMessage("Loading People News"); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      // Creating service handler class instance 
      ServiceHandler sh = new ServiceHandler(); 
      try { 

       // Making a request to url and getting response 
       // String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

       URL requestUrl = new URL(url); 
       Log.e("Debug", " Sapp 1 : " + requestUrl.toString()); 
       URLConnection con = requestUrl.openConnection(); 
       BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 

       StringBuilder sb=new StringBuilder(); 
      //Reader rd=new Readable(in); 
      int cp; 
      try { 
        while((cp=in.read())!=-1){ 
        sb.append((char)cp); 
       }} 
       catch(Exception e){ 
       } 
       String jsonStr=sb.toString(); 
      Log.e("Response: ", "> " + jsonStr); 

      if (jsonStr != null) { 
       try { 
        JSONObject jsonObj = new JSONObject(jsonStr); 

        // Getting JSON Array node 
        contacts = jsonObj.getJSONArray(TAG_CONTACTS); 

        // looping through All Contacts 
        for (int i = 0; i < contacts.length(); i++) { 
         JSONObject c = contacts.getJSONObject(i); 

         String id = c.getString(TAG_ID); 
         String name = c.getString(TAG_NAME); 
         String size = c.getString(TAG_SIZE); 
         String url = c.getString(TAG_PHONE_URL); 
         String details = c.getString(TAG_DETAILS); 
         String location = c.getString(TAG_LOCATION); 
         String datetime = c.getString(TAG_DATETIME); 
         String filetype = c.getString(TAG_FILETYPE); 
         String username = c.getString(TAG_USERNAME); 
         String highalert = c.getString(TAG_HIGHALERT); 

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

         // adding each child node to HashMap key => value 
         contact.put(TAG_ID, id); 
         contact.put(TAG_NAME, name); 
         contact.put(TAG_SIZE, size); 
         contact.put(TAG_PHONE_URL, url); 
         contact.put(TAG_DETAILS, details); 
         contact.put(TAG_LOCATION, location); 
         contact.put(TAG_DATETIME, datetime); 
         contact.put(TAG_FILETYPE, filetype); 
         contact.put(TAG_FILETYPETXT, filetype); 
         contact.put(TAG_USERNAME, username); 
         contact.put(TAG_HIGHALERT, highalert); 
         // Log.e("Debug", " Sapp 7 : " + name); 

         // adding contact to contact list 
         contactList.add(contact); 

        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } else { 
       Log.e("ServiceHandler", "Couldn't get any data from the url"); 
      } 
      }catch(Exception ec){ 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
      // Dismiss the progress dialog 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 
      /** 
      * Updating parsed JSON data into ListView 
      * */ 
     ListAdapter adapter = new SimpleAdapter(
        getActivity(), contactList, 
        R.layout.list_selector, new String[] { TAG_NAME, TAG_SIZE, 
        TAG_PHONE_URL,TAG_FILETYPE, TAG_FILETYPETXT,TAG_DETAILS,TAG_LOCATION,TAG_DATETIME, TAG_USERNAME, TAG_HIGHALERT}, new int[] { R.id.name, 
        R.id.size, R.id.url, R.id.filetype,R.id.filetypetxt, R.id.details, R.id.location, R.id.datetime, R.id.username, R.id.highalert }); 
      Log.e("Debug", " Sapp 10" + TAG_NAME+contactList.toString()); 
//Here it is printing the array in Log 

     //Problem seems here 

     SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() { 

       @Override 
       public boolean setViewValue(View view, Object data, 
              String textRepresentation) { 
        Log.e("Debug", " Sapp 11"+view.getId()); 
        if (view.getId() == R.id.name) { 
         ((TextView) view).setText((String) data); 
         return true; 
        } else if (view.getId() == R.id.size) { 
         ((TextView) view).setText((String) data); 
        } else if (view.getId() == R.id.url) { 
         ((TextView) view).setText((String) data); 
        } else if (view.getId() == R.id.details) { 
         ((TextView) view).setText((String) data); 
        } else if (view.getId() == R.id.location) { 
         ((TextView) view).setText((String) data); 
        } else if (view.getId() == R.id.datetime) { 
         ((TextView) view).setText((String) data); 
        } else if (view.getId() == R.id.filetypetxt) { 
         ((TextView) view).setText((String) data); 
        } else if (view.getId() == R.id.username) { 
         ((TextView) view).setText((String) data); 
        } else if (view.getId() == R.id.highalert) { 
         GradientDrawable gd = new GradientDrawable(); 
         gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient 
         gd.setCornerRadius(0); 
         gd.setSize(10,20); 

         // view.findViewById(R.id.name).setBackgroundDrawable(gd); 
         String halert=(String.valueOf((String) data)); 
         if(halert.equals("1")) { 

          ((TextView) view).setText(" "); 
          ((TextView) view).setBackgroundDrawable(gd); 

          return true; 
          } 
         else { return true; } 


        } else if (view.getId() == R.id.filetype) { 
         // (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data); 
         Resources res =getResources(); 
         String tnew=(String.valueOf((String) data)); 
         String tst=tnew; 
         int sidd=0; 
         // Log.e("Debug", " Sapp 7:"+(String)data+":"); 
         if(tst.equals("c")) { ssid = R.drawable.ca; } 
         else if(tst.equals("d")) { ssid = R.drawable.da; } 
         else if(tst.equals("e")) { ssid = R.drawable.ea; } 
         //s=2130837566; 
         Log.e("Debug", " Sapp 8 :"+ssid+":"); 
         Bitmap bmp = BitmapFactory.decodeResource(res, ssid); 
         BitmapDrawable ob = new BitmapDrawable(getResources(), bmp); 
         ((ImageView) view).setImageDrawable(ob); 
         ((ImageView) view).setImageBitmap(bmp); 
         return true; 
        } 
        return false; 
       } 
      }; 
      ((SimpleAdapter) adapter).setViewBinder(viewBinder); 
      lv.setAdapter(adapter); 
      registerForContextMenu(lv); 
     } 
    } 
    public static String getFileSize(long size) { 
     if (size <= 0) 
      return "0"; 
     final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; 
     int digitGroups = (int) (Math.log10(size)/Math.log10(1024)); 
     return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups]; 
    } 

} 

et voici xml:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical"> 
    <!-- Main ListView 
     Always give id value as list(@android:id/list) 
    --> 
    <ListView 
     android:id="@android:id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:divider="#b5b5b5" 
     android:dividerHeight="1dp" 
     android:listSelector="@drawable/list_selector" 
     /> 
</LinearLayout> 

Répondre

0

Quelques suggestions:

  • Pas besoin de View fragment; et son initialisation: fragment = inflater.inflate(R.layout.listnewsjson, container, false); les supprimer.

  • Remplacer lv = (ListView) fragment.findViewById(android.R.id.list); par lv = getListView();. getListView() est une méthode définie par ListFragment qui renvoie ListView du fragment.

  • IMPORTANT: Remplacer lv.setAdapter(adapter); dans onPostExecute() avec setListAdapter(adapter);. De la documentation de ListFragment:

Vous devez utiliser ListFragment.setListAdapter() pour associer la liste avec un adaptateur. N'appelez pas directement ListView.setAdapter() sinon l'initialisation importante sera ignorée.

  • Modifier la méthode setViewValue() de viewBinder à:

    @Override 
    public boolean setViewValue(View view, Object data, 
    String textRepresentation) { 
         Log.e("Debug", " Sapp 11" + view.getId()); 
         if (view.getId() == R.id.highalert) { 
           GradientDrawable gd = new GradientDrawable(); 
           gd.setColor(0xffff0000); // Changes this drawbale to use a single color instead of a gradient 
           gd.setCornerRadius(0); 
           gd.setSize(10, 20); 
           // view.findViewById(R.id.name).setBackgroundDrawable(gd); 
           String halert = (String.valueOf((String) data)); 
           if (halert.equals("1")) { 
             ((TextView) view).setText(" "); 
             ((TextView) view).setBackgroundDrawable(gd); 
           } else { 
             // TODO: Should remove gradient color here because views are recycled. 
           } 
           return true; 
         } 
         if (view.getId() == R.id.filetype) { 
           // (view1 = (TextView) findViewById(R.id.filetypetxt)).setText((String) data); 
           Resources res = getResources(); 
           String tnew = (String.valueOf((String) data)); 
           String tst = tnew; 
           int sidd = 0; 
           // Log.e("Debug", " Sapp 7:"+(String)data+":"); 
           if (tst.equals("c")) { 
             ssid = R.drawable.ca; 
           } else if (tst.equals("d")) { 
             ssid = R.drawable.da; 
           } else if (tst.equals("e")) { 
             ssid = R.drawable.ea; 
           } 
           //s=2130837566; 
           Log.e("Debug", " Sapp 8 :" + ssid + ":"); 
           Bitmap bmp = BitmapFactory.decodeResource(res, ssid); 
           BitmapDrawable ob = new BitmapDrawable(getResources(), bmp); 
           ((ImageView) view).setImageDrawable(ob); 
           ((ImageView) view).setImageBitmap(bmp); 
           return true; 
         } 
         return false; 
    } 
    

ViewBinder a besoin que pour traiter les cas où vous avez besoin de faire quelque chose en plus (comme le réglage des images en couleur ou chargement arrière-plan sur la base passé -dans les valeurs de données dans votre cas) que de simplement lier des valeurs aux vues. La liaison ordinaire des valeurs aux vues est fournie par SimpleAdapter par défaut.