如何将json图像从回收站视图传递到另一个活动

时间:2017-01-22 13:55:25

标签: android json onclick imageview android-recyclerview

请问我一直在尝试将recson视图中的json数据显示到另一个活动,但只显示textview而图像没有显示。这是我的代码

public class MainActivity extends AppCompatActivity {

public String content;

public static MainActivity parse(JSONObject object){
    MainActivity post=new MainActivity();
    post.content = Html.fromHtml(object.optString("content")).toString();
    return post;

}

ImageView thumbnail;
TextView title;

private static final String TAG = "RecyclerViewExample";
private SwipeRefreshLayout swipeRefreshLayout;
private List<FeedItem> feedsList;
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
private ProgressBar progressBar;

public MainActivity(){
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_feed_list);

    // Initialize recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    progressBar.setVisibility(View.VISIBLE);

    // Downloading data from below url
    final String url = "http://street2view.com/api/get_recent_posts/";
    new AsyncHttpTask().execute(url);
}

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
    @Override
    protected void onPreExecute() {
        setProgressBarIndeterminateVisibility(true);
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP OK
            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                parseResult(response.toString());
                result = 1; // Successful
            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {
        // Download complete. Let us update UI
        progressBar.setVisibility(View.GONE);

        if (result == 1) {
            adapter = new MyRecyclerAdapter(MainActivity.this, feedsList);
            mRecyclerView.setAdapter(adapter);
        } else {
            Toast.makeText(MainActivity.this, "Check Your Internet Connection", Toast.LENGTH_SHORT).show();
        }
    }


}



@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;


}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (item.getItemId() == R.id.about) {
        Intent settingsActivityIntent = new Intent();
        settingsActivityIntent.setClass(this, AboutActivity.class);
        this.startActivityForResult(settingsActivityIntent, 111);
        return true;
    }
    return super.onOptionsItemSelected(item);
}







@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setTitle("Quit")
            .setMessage("Do you wish to exit the app?")
            .setCancelable(false)
            .setNegativeButton(android.R.string.no, null)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            }).create().show();
}

public String stripHtmlTags(String html) {
    return Html.fromHtml(html).toString();
}




private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("posts");
        feedsList = new ArrayList<>();

        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);

            FeedItem item = new FeedItem();
            item.setTitle(post.optString("title"));
            item.setContent(post.optString("content"));
            item.setdate(post.optString("date"));
            JSONArray attachments = post.getJSONArray("attachments");
            if (null != attachments && attachments.length() > 0) {
                JSONObject attachment = attachments.getJSONObject(0);
                if (attachment != null)
                    item.setAttachmentUrl(attachment.getString("url"));
            }
            JSONArray categories = post.getJSONArray("categories");
            if (null != categories && categories.length() > 0) {
                JSONObject attachment = categories.getJSONObject(0);
                if (categories != null)
                    item.setCategories(attachment.getString("title"));
            }

            feedsList.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

}

这是我用来将数据从回收站视图发送到第二个活动的适配器类

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;

public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
    this.feedItemList = feedItemList;
    this.mContext = context;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);

    CustomViewHolder viewHolder = new CustomViewHolder(view,mContext, (ArrayList<FeedItem>) feedItemList);
    return viewHolder;


}

@Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {


    FeedItem feedItem = feedItemList.get(i);

    //Download image using picasso library
    Glide.with(mContext).load(feedItem.getAttachmentUrl())
            .error(R.color.list_item_title)
            .placeholder(R.color.list_item_title)
            .into(customViewHolder.imageView);

    //Setting text view title
    customViewHolder.textView.setText((feedItem.getTitle()));
    customViewHolder.textView2.setText(feedItem.getdate());


    customViewHolder.categories.setText(feedItem.getCategories());



}


@Override
public int getItemCount() {
    return (null != feedItemList ? feedItemList.size() : 0);
}

public class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    protected ImageView imageView;
    protected TextView textView2;
    protected TextView textView;
    protected TextView content;
    protected TextView categories;
    public RelativeLayout relativeLayout;
    ArrayList<FeedItem> feeditem = new ArrayList<FeedItem>();
    Context ctx;

    public CustomViewHolder(View view, Context ctx, ArrayList<FeedItem> feeditem) {
        super(view);

        view.setOnClickListener(this);
        this.ctx = ctx;
        this.feeditem = feeditem;
        this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
        this.textView2 = (TextView) view.findViewById(R.id.date);
        this.categories = (TextView) view.findViewById(R.id.categories);
        this.textView = (TextView) view.findViewById(R.id.title);
    }

    @Override
    public void onClick(View v) {
        int position = getAdapterPosition();
        FeedItem feeditem = this.feeditem.get(position);
        Intent intent = new Intent(this.ctx,Main2Activity.class);
        intent.putExtra("title",feeditem.getTitle());
        intent.putExtra("content",feeditem.getContent());
        Html.fromHtml(String.valueOf(intent.putExtra("content",feeditem.getContent()))).toString();
        intent.putExtra("thumbnail",feeditem.getAttachmentUrl());
        this.ctx.startActivity(intent);


    }



}

}

这是我要显示json数据的第二个活动(当我运行应用程序时,textview显示但是imageview非常感谢)

public class Main2Activity extends AppCompatActivity {
ImageView imageView;
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
        imageView = (ImageView)findViewById(R.id.contentImage);
    textView = (TextView)findViewById(R.id.title2);
    textView.setText(getIntent().getStringExtra("title"));
    imageView.setImageResource(getIntent().getIntExtra("thumbnail", 00));

}}

1 个答案:

答案 0 :(得分:0)

你可以试试这个

public class Main2Activity extends AppCompatActivity {

    ImageView imageView;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        imageView = (ImageView) findViewById(R.id.contentImage);
        textView = (TextView) findViewById(R.id.title2);

        String title = getIntent().getStringExtra("title");
        String thumbnail = getIntent().getStringExtra("thumbnail");

        textView.setText(title);
        // set image here
        Glide.with(this).load(thumbnail)
                .into(imageView);
    }
}