使用解析从编辑文本中读取字符串?

时间:2014-10-01 23:45:10

标签: java android json parsing android-activity

好的,应用程序从Url(json)填充列表视图。但我想更改应用程序,以便用户输入填充列表视图。我该如何解决这个问题。这是我到目前为止的主要活动:

package ionictech.com.onspot;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Cache;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.Cache.Entry;
import com.android.volley.Request.Method;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import ionictech.com.onspot.adapter.FeedListAdapter;
import ionictech.com.onspot.app.AppController;
import ionictech.com.onspot.data.FeedItem;


  public class OnSpotActivity extends ActionBarActivity  {

   private DrawerLayout drawerLayout;
   private String[] Menu;

   private static final String TAG = OnSpotActivity.class.getSimpleName();
   private ListView listView;
   private FeedListAdapter listAdapter;
   private List<FeedItem> feedItems;
   private String URL_FEED = "http://api.androidhive.info/feed/feed.json";

  @SuppressLint("NewApi")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_on_spot);

    listView = (ListView) findViewById(R.id.list);

    feedItems = new ArrayList<FeedItem> ();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
    getActionBar().setBackgroundDrawable(new ColorDrawable (Color.parseColor ("#ffba00")));
    getActionBar().setIcon(
            new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    // We first check for cached request
    Cache cache = AppController.getmInstance ().getmRequestQueue ().getCache();
    Entry entry = cache.get(URL_FEED);
    if (entry != null) {
        // fetch the data from cache
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else {
        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                URL_FEED, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d (TAG, "Response: " + response.toString ());
                if (response != null) {
                    parseJsonFeed(response);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to volley request queue
        AppController.getmInstance ().addToRequestQueue(jsonReq);
    }

  }

   /**
   * Parsing json reponse and passing the data to feed view list adapter
   * */
   private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("feed");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj
                    .getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("status"));
            item.setProfilePic(feedObj.getString("profilePic"));
            item.setTimeStamp(feedObj.getString("timeStamp"));

            // url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);

            feedItems.add(item);
        }

          // notify data changes to list adapater
          listAdapter.notifyDataSetChanged();
       } catch (JSONException e) {
          e.printStackTrace();
      }
   }

 }

这是我的Feed项目列表类:

package ionictech.com.onspot.adapter;

 import android.app.Activity;
 import android.content.Context;
 import android.text.Html;
 import android.text.TextUtils;
 import android.text.format.DateUtils;
 import android.text.method.LinkMovementMethod;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.BaseAdapter;
 import android.widget.TextView;

 import com.android.volley.toolbox.ImageLoader;
 import com.android.volley.toolbox.NetworkImageView;

 import java.util.List;

 import ionictech.com.onspot.FeedImageView;
 import ionictech.com.onspot.R;
 import ionictech.com.onspot.app.AppController;
 import ionictech.com.onspot.data.FeedItem;

/**
 * Created by MarcusLee on 9/30/14.
 */
 public class FeedListAdapter extends BaseAdapter {

  private Activity activity;
   private LayoutInflater inflater;
   private List<FeedItem> feedItems;

  ImageLoader imageLoader = AppController.getmInstance ().getImageLoader();

  public FeedListAdapter (Activity activity, List<FeedItem> feedItems) {
    this.activity = activity;
    this.feedItems = feedItems;
}

@Override
public int getCount() {
    return feedItems.size();
}

@Override
public Object getItem(int location) {
    return feedItems.get(location);
}

@Override
public long getItemId(int position) {
    return position;
  }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.feed_item, null);

    if (imageLoader == null)
        imageLoader = AppController.getmInstance().getImageLoader();

    TextView name = (TextView) convertView.findViewById(R.id.name);
    TextView timestamp = (TextView) convertView
            .findViewById(R.id.timestamp);
    TextView statusMsg = (TextView) convertView
            .findViewById(R.id.txtStatusMsg);
    TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
    NetworkImageView profilePic = (NetworkImageView) convertView
            .findViewById(R.id.profilePic);
    FeedImageView feedImageView = (FeedImageView) convertView
            .findViewById(R.id.feedImage1);

    FeedItem item = feedItems.get(position);

    name.setText(item.getName());

    // Converting timestamp into x ago format
    CharSequence timeAgo = DateUtils.getRelativeTimeSpanString (
            Long.parseLong (item.getTimeStamp ()),
            System.currentTimeMillis (), DateUtils.SECOND_IN_MILLIS);
    timestamp.setText(timeAgo);

    // Chcek for empty status message
    if (!TextUtils.isEmpty (item.getStatus ())) {
        statusMsg.setText(item.getStatus());
        statusMsg.setVisibility(View.VISIBLE);
    } else {
        // status is empty, remove from view
        statusMsg.setVisibility(View.GONE);
    }

    // Checking for null feed url
    if (item.getUrl() != null) {
        url.setText(Html.fromHtml ("<a href=\"" + item.getUrl () + "\">"
                + item.getUrl () + "</a> "));

        // Making url clickable
        url.setMovementMethod(LinkMovementMethod.getInstance ());
        url.setVisibility(View.VISIBLE);
    } else {
        // url is null, remove from the view
        url.setVisibility(View.GONE);
    }

    // user profile pic
    profilePic.setImageUrl(item.getProfilePic(), imageLoader);

    // Feed image
    if (item.getImge() != null) {
        feedImageView.setImageUrl(item.getImge(), imageLoader);
        feedImageView.setVisibility(View.VISIBLE);
        feedImageView
                .setResponseObserver(new FeedImageView.ResponseObserver() {
                    @Override
                    public void onError() {
                    }

                    @Override
                    public void onSuccess() {
                    }
                });
      } else {
         feedImageView.setVisibility(View.GONE);
     }

      return convertView;
  }

}

我知道输入必须发送到服务器然后读取并放入列表视图,我只是不知道方法等。任何帮助都会非常感激!

0 个答案:

没有答案