如何从类中获取字符串

时间:2016-08-01 20:57:18

标签: java android

我正在使用纽约时代电影评论API制作电影评论应用,API给了我一个字符串“short_summary”,我有一个类将API中的所有信息转换为ListView,我想创建一个将向用户显示评论摘要的新活动,但我知道如何获取此信息的唯一方法就是使用MovieArrayAdapter做同样的事情。

有没有办法只能从用户点击列表的评论中获取short_summary?

MainActivity.java

package br.com.pedro.pedrodaumas;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private List<Movie> movieList = new ArrayList<>();
    private MovieArrayAdapter movieArrayAdapter;
    private ListView movieListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        movieListView = (ListView) findViewById(R.id.movieListView);
        movieArrayAdapter = new MovieArrayAdapter(this, movieList);
        movieListView.setAdapter(movieArrayAdapter);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextInputEditText search_bar;
                search_bar = (TextInputEditText) findViewById(R.id.search_bar);
                URL url = createURL(search_bar.getText().toString());
                if(url != null){
                    dismissKeyboard(search_bar);
                    GetMovieTask getLocalMovieTask = new GetMovieTask();
                    getLocalMovieTask.execute(url);
                }else {
                    Snackbar.make(findViewById(R.id.coordinatorLayout), R.string.invalid_url,
                            Snackbar.LENGTH_LONG).show();
                }

            }
        });
        movieListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    default:
                        Intent nextActivity = new Intent(MainActivity.this, ShortReview.class);
                        startActivity(nextActivity);
                        break;
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void dismissKeyboard (View view){
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
    }

    private URL createURL (String movie){
        String apiKey = getString (R.string.api_key);
        String baseUrl = getString(R.string.nyt_url);
        try{
            String urlString = baseUrl + "?api_key=" + apiKey + "&query=" + URLEncoder.encode (movie, "UTF-8");
            return new URL(urlString);
        }
        catch( Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private class GetMovieTask extends AsyncTask<URL, Void, JSONObject> {
        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        protected JSONObject doInBackground(URL... params) {
            HttpURLConnection connection = null;
            try {
                connection = (HttpURLConnection) params[0].openConnection();
                int response = connection.getResponseCode();
                if (response == HttpURLConnection.HTTP_OK){
                    StringBuilder builder = new StringBuilder ();
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
                        String line;
                        while ((line = reader.readLine()) != null){
                            builder.append(line);
                        }
                    }
                    catch (IOException e){
                        Snackbar.make(findViewById(R.id.coordinatorLayout), R.string.read_error, Snackbar.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                    return new JSONObject(builder.toString());
                }
            }
            catch (Exception e){
                Snackbar.make(findViewById(R.id.coordinatorLayout), R.string.connect_error, Snackbar.LENGTH_LONG).show();
                e.printStackTrace();
            }
            finally{
                if (connection != null){
                    connection.disconnect();
                }
            }
            return null;
        }
        protected void onPostExecute(JSONObject movie) {
            convertJSONToArrayList (movie);
            movieArrayAdapter.notifyDataSetChanged();
            movieListView.smoothScrollToPosition(0);
        }
    }

    private void convertJSONToArrayList (JSONObject forecast){
        movieList.clear();
        try{
            JSONArray results = forecast.getJSONArray("results");
            for (int i = 0; i < results.length(); i++) {
                JSONObject movie = results.getJSONObject(i);
                if(movie.isNull("multimedia")){
                    movieList.add(new Movie(movie.getString("display_title"),
                            movie.getString("publication_date"),
                            "image", movie.getString("summary_short")));
                }else {
                    JSONObject multimedia = movie.getJSONObject("multimedia");
                    movieList.add(new Movie(movie.getString("display_title"),
                            movie.getString("publication_date"),
                            multimedia.getString("src"), movie.getString("summary_short")));
                }
            }
        }
        catch (JSONException e){
            e.printStackTrace();
        }
    }

}

Movie.java

package br.com.pedro.pedrodaumas;


public class Movie {
    public final String title;
    public final String publication_date;
    public final String iconURL;
    public final String short_summary;

    public Movie(String title,String publication_date, String iconName, String short_summary) {
        this.title = title;
        this.publication_date = publication_date;
        this.iconURL = iconName;
        this.short_summary = short_summary;
    }

}

MovieArrayAdapter.java

package br.com.pedro.pedrodaumas;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MovieArrayAdapter extends ArrayAdapter<Movie> {

    private static class ViewHolder{
        ImageView movieImage;
        TextView description;
        TextView publication_date;
    }

    private Map<String, Bitmap> bitmaps = new HashMap<>();
    public MovieArrayAdapter (Context context, List<Movie>
            forecast){
        super (context, -1, forecast);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Movie review = getItem (position);
        ViewHolder viewHolder;
        if (convertView == null){
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.complete_review, parent, false);
            viewHolder.movieImage = (ImageView)convertView.findViewById(R.id.movieImage);
            viewHolder.description = (TextView)convertView.findViewById(R.id.description);
            viewHolder.publication_date = (TextView)convertView.findViewById(R.id.publication_date);
            convertView.setTag(viewHolder);
        }
        else{
            viewHolder = (ViewHolder)convertView.getTag();
        }
        if(review.iconURL == "image"){
            viewHolder.movieImage.setImageResource(R.drawable.ic_import_contacts_white_24dp);
        }
        else{
            new LoadImageTask (viewHolder.movieImage).execute (review.iconURL);
        }

        Context context = getContext();
        viewHolder.description.setText(review.title);
        viewHolder.publication_date.setText(review.publication_date);
        return convertView;
    }

    private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        private ImageView imageView;
        public LoadImageTask (ImageView imageView){
            this.imageView = imageView;
        }
        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            HttpURLConnection connection = null;
            try{
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                try(InputStream inputStream = connection.getInputStream ()){
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    bitmaps.put (params[0], bitmap);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
            finally{
                connection.disconnect();
            }
            return bitmap;
        }
        protected void onPostExecute(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);
        }
    }
}

ShortReview.java

package br.com.pedro.pedrodaumas;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class ShortReview extends AppCompatActivity {

    private TextView short_summary;
    private Movie review;

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

        short_summary = (TextView) findViewById(R.id.short_summary);
        short_summary.setText("test");
    }

}

2 个答案:

答案 0 :(得分:2)

感谢来自(https://forums.xamarin.com/discussion/38235/setcontentview-of-mainactivity-gives-null-pointer-after-adding-preference-xml-to-project)的Zainal Fahrudin和Nilanchala 我能够通过使用getSummary并将其添加到putExtra来解决我的问题。

以下是我改变的内容:

  

MainAtivity

        @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (position) {
            default:
                Movie review = movieArrayAdapter.getItem(position);
                Intent nextActivity = new Intent(MainActivity.this, ShortReview.class);
                nextActivity.putExtra("summary", review.getsummary());
                startActivity(nextActivity);
                break;
        }
    }
});

}

  

电影

public String getsummary() {
    return short_summary;
}
  

ShortReview

private TextView short_summary;
private String s_summary;

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

    Intent intent = getIntent();
    if (null != intent) {
        s_summary = intent.getStringExtra("summary");

    }
    short_summary = (TextView) findViewById(R.id.short_summary);
    short_summary.setText(s_summary);
}

答案 1 :(得分:0)

您可以使用intent extra,

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("short_summary", "the summary is here");
startActivity(intent)

然后获取第二个活动的字符串值

Bundle bundle = getIntent().getExtras();
    if (bundle!=null){
        String summary = bundle.getString("short_summary");
       }