适配器中的数据但不会在Listview中丢失将Listactivity转换为ListFragment

时间:2015-10-13 22:48:27

标签: android-listview android-listfragment simpleadapter android-json android-viewbinder

我已经将许多活动转换为片段,除了一个之外,一切正常。在这个java文件的早期版本中,它扩展了ListActivity,现在我用ListFragment替换了它。最初它提供了nullPointerException,但在this post的帮助下,我设法删除了错误。现在它在Adapter中获取数据但不在listview中获取数据(我通过在日志中打印它来检查)。所以我需要在listview中显示数据。

这是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];
    }

}

,这是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>

1 个答案:

答案 0 :(得分:0)

一些建议:

  • 无需var result = confirm("Êtes-vous sûr de vouloir supprimer cette page?"); if (result == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } 及其初始化:View fragment;删除它们。

  • fragment = inflater.inflate(R.layout.listnewsjson, container, false);替换为lv = (ListView) fragment.findViewById(android.R.id.list);lv = getListView();是由getListView()定义的方法,用于返回片段ListFragment

  • 重要:将ListView中的lv.setAdapter(adapter);替换为onPostExecute()。来自setListAdapter(adapter);的文档:

  

您必须使用ListFragment.setListAdapter()将列表与适配器相关联。不要直接调用ListView.setAdapter(),否则将跳过重要的初始化。

  • ListFragment的{​​{1}}方法修改为:

    setViewValue()

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; } 会将值与视图进行普通绑定。

相关问题