简单的Android图像解析

时间:2014-09-09 01:33:57

标签: java android json url bitmap

我正在尝试解析图像URL并在ListView中显示图像,但我继续收到ProtocalNotFound异常/ JSON异常没有null的值。我很确定我已经接近将图像URL转换为位图,但我已经接受了一些小事。任何正确方法的想法都会有所帮助。我的课程如下,包括Feed的网址。现在,我正在尝试转换loadImageFromWebOperations方法中的图像URL。如果您需要更多信息,请与我们联系。

Android类:

public class mainViewController extends ListFragment 
{

    mainViewController context = this;

    // Progress Dialog
        private ProgressDialog pDialog;

        // testing on Emulator:
        //private static final String READ_COMMENTS_URL = "https://shipstudent.com/androidapp/comments.php";
        private static final String READ_COMMENTS_URL = "https://shipstudent.com/complaint_desk/androidcentralwall.php";

        // JSON IDS:
        @SuppressWarnings("unused")
        private static final String TAG_SUCCESS = "success";
        private static final String TAG_TITLE = "title";
        private static final String TAG_POSTS = "posts";
        @SuppressWarnings("unused")
        private static final String TAG_POST_ID = "IDPosts";
        private static final String TAG_USERNAME = "username";
        private static final String TAG_MESSAGE = "body";
        private static final String TAG_PROFILE_PICTURE = "profile_picture";
        //private static final String TAG_POSTED = "posted";

        // it's important to note that the message is both in the parent branch of
        // our JSON tree that displays a "Post Available" or a "No Post Available"
        // message,
        // and there is also a message for each individual post, listed under the
        // "posts"
        // category, that displays what the user typed as their message.

        // An array of all of our comments
        private JSONArray allPosts = null;
        // manages all of our comments in a list.
        private ArrayList<HashMap<String, String>> mCommentList;

    public mainViewController()
    {
    }

    String[] mainFeed = {};

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

//       // TODO Auto-generated method stub
//          ArrayAdapter<String> adapter = new ArrayAdapter<String>(
//                  inflater.getContext(), android.R.layout.simple_list_item_1,
//                  mainFeed);
//
//          setListAdapter(adapter);


         return super.onCreateView(inflater, container, savedInstanceState);
     }

        @Override
        public void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            // loading the comments via AsyncTask
            new LoadComments().execute();
        }

        public void addComment(View v) {
//          Intent i = new Intent(ReadComments.this, writePostViewController.class);
//          startActivity(i);
        }

        /**
         * Retrieves recent post data from the server.
         */
        public void updateJSONdata() {


            mCommentList = new ArrayList<HashMap<String, String>>();

            JSONParser jParser = new JSONParser();

            JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

            try {

                allPosts = json.getJSONArray(TAG_POSTS);

                // looping through all posts according to the json object returned
                for (int i = 0; i < allPosts.length(); i++) {
                    JSONObject c = allPosts.getJSONObject(i);

                    // gets the content of each tag
                    String title = c.getString(TAG_TITLE);
                    String content = c.getString(TAG_MESSAGE);
                    String username = c.getString(TAG_USERNAME);
                    File sdCard = Environment.getExternalStorageDirectory();
                    String profile_picture = c.getString(loadImageFromWebOperations(TAG_PROFILE_PICTURE.replaceAll(" ", "%20"),sdCard.getAbsolutePath() + "/dir1/dir2"));
//                  String profile_picture = c.getString(TAG_PROFILE_PICTURE);
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(TAG_TITLE, title);
                    map.put(TAG_MESSAGE, content);
                    map.put(TAG_USERNAME, username);
                    map.put(TAG_PROFILE_PICTURE, profile_picture);

                    // adding HashList to ArrayList
                    mCommentList.add(map);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



        @SuppressWarnings("resource")
        public static String loadImageFromWebOperations(String url, String path) {
            try {
                InputStream is = (InputStream) new URL(url).getContent();

                System.out.println(path);
                File f = new File(path);

                f.createNewFile();
                FileOutputStream fos = new FileOutputStream(f);
                try {

                    byte[] b = new byte[100];
                    int l = 0;
                    while ((l = is.read(b)) != -1)
                        fos.write(b, 0, l);

                } catch (Exception e) {

                }

                return f.getAbsolutePath();
            } catch (Exception e) {
                System.out.println("Exc=" + e);
                return null;

            }
        }

        /**
         * Inserts the parsed data into the listview.
         */
        private void updateList() {
            // For a ListActivity we need to set the List Adapter, and in order to do
            //that, we need to create a ListAdapter.  This SimpleAdapter,
            //will utilize our updated Hashmapped ArrayList, 
            //use our single_post xml template for each item in our list,
            //and place the appropriate info from the list to the
            //correct GUI id.  Order is important here.
            ListAdapter adapter = new SimpleAdapter(this.getActivity(), mCommentList,
                    R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
                            TAG_USERNAME, TAG_PROFILE_PICTURE }, new int[] { R.id.title, R.id.message,
                            R.id.username ,R.id.imageView1});

            // I shouldn't have to comment on this one:
            setListAdapter(adapter);

            // Optional: when the user clicks a list item we 
            //could do something.  However, we will choose
            //to do nothing...
            ListView lv = getListView();    
            lv.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    // This method is triggered if an item is click within our
                    // list. For our example we won't be using this, but
                    // it is useful to know in real life applications.

                }
            });
        }


        public class LoadComments extends AsyncTask<Void, Void, Boolean> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
//              pDialog = new ProgressDialog(mainViewController.this);
//              pDialog.setMessage("Loading Posts...");
//              pDialog.setIndeterminate(false);
//              pDialog.setCancelable(true);
//              pDialog.show();
            }

            @Override
            protected Boolean doInBackground(Void... arg0) {
                updateJSONdata();
                return null;

            }

            @Override
            protected void onPostExecute(Boolean result) {
                super.onPostExecute(result);
                //pDialog.dismiss();
                updateList();
            }
        }

     @Override
        public void onListItemClick(ListView l, View v, int position, long id) 
        {
            // TODO Auto-generated method stub
            super.onListItemClick(l, v, position, id);
        }
}

logcat的:

09-08 21:29:01.281: I/System.out(17363): Exc=java.net.MalformedURLException: Protocol not found: profile_picture
09-08 21:29:01.281: W/System.err(17363): org.json.JSONException: No value for null
09-08 21:29:01.321: W/System.err(17363):    at org.json.JSONObject.get(JSONObject.java:355)
09-08 21:29:01.321: W/System.err(17363):    at org.json.JSONObject.getString(JSONObject.java:515)
09-08 21:29:01.321: W/System.err(17363):    at com.rynovation.kline.mainViewController.updateJSONdata(mainViewController.java:128)
09-08 21:29:01.321: W/System.err(17363):    at com.rynovation.kline.mainViewController$LoadComments.doInBackground(mainViewController.java:230)
09-08 21:29:01.371: W/System.err(17363):    at com.rynovation.kline.mainViewController$LoadComments.doInBackground(mainViewController.java:1)
09-08 21:29:01.371: W/System.err(17363):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
09-08 21:29:01.371: W/System.err(17363):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-08 21:29:01.371: W/System.err(17363):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-08 21:29:01.371: W/System.err(17363):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-08 21:29:01.371: W/System.err(17363):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-08 21:29:01.371: W/System.err(17363):    at java.lang.Thread.run(Thread.java:841)

1 个答案:

答案 0 :(得分:0)

问题出在这里 String profile_picture = c.getString(loadImageFromWebOperations(TAG_PROFILE_PICTURE.replaceAll(“”,“%20”),sdCard.getAbsolutePath()+“/ dir1 / dir2”));

首先让他们为密钥值,然后加载网址。