Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android java.lang.OutOfMemoryError位于com.mysamples.jsonparsingdemo2.MainActivity$MovieAdapter.getView(MainActivity.java:158)_Android_Json_Android Studio_Android Studio 2.1 - Fatal编程技术网

Android java.lang.OutOfMemoryError位于com.mysamples.jsonparsingdemo2.MainActivity$MovieAdapter.getView(MainActivity.java:158)

Android java.lang.OutOfMemoryError位于com.mysamples.jsonparsingdemo2.MainActivity$MovieAdapter.getView(MainActivity.java:158),android,json,android-studio,android-studio-2.1,Android,Json,Android Studio,Android Studio 2.1,我试图解析json对象,但仍然出现错误。 以下是MainActivity.java中的代码: 错误状态为 致命异常:主 进程:com.mysamples.jsonparsingdemo2,PID:2618 java.lang.OutOfMemoryError package com.mysamples.jsonparsingdemo2; import android.content.Context; import android.os.AsyncTask; import android.sup

我试图解析json对象,但仍然出现错误。 以下是MainActivity.java中的代码: 错误状态为

致命异常:主 进程:com.mysamples.jsonparsingdemo2,PID:2618 java.lang.OutOfMemoryError

package com.mysamples.jsonparsingdemo2;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.mysamples.jsonparsingdemo2.models.MovieModels;

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


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

public class MainActivity extends ActionBarActivity {


    private ListView listView;

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

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

        }




public class JSONTask extends AsyncTask<String,String,List<MovieModels>> {

    @Override
    protected List<MovieModels> doInBackground(String... urls) {
        HttpURLConnection httpURLConnection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(urls[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            InputStream stream = httpURLConnection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer sBuffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine())!= null){
                sBuffer.append(line);
            }

            //Organizing the JSON object the JSON OBJECT
            String finalJson = sBuffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("movies");

            //getting the objects from the url
            List<MovieModels> modelList = new ArrayList<>();
            for (int j = 0; j <parentArray.length() ; j++) {
                JSONObject finalObject = parentArray.getJSONObject(j);
                MovieModels models = new MovieModels();


                //Displaying the values from the url
                models.setMovie(finalObject.getString("movie"));
                models.setYear(finalObject.getInt("year"));
                models.setRating((float) finalObject.getDouble("rating"));
                models.setDirector(finalObject.getString("director"));
                models.setDuration(finalObject.getString("duration"));
                models.setTagline(finalObject.getString("tagline"));
                models.setImage(finalObject.getString("image"));
                models.setStory(finalObject.getString("story"));


                //getting the values from castList
                List<MovieModels.Cast> castList = new ArrayList<>();
                for (int i = 0; i <finalObject.getJSONArray("cast").length() ; i++) {
                    MovieModels.Cast cast = new MovieModels.Cast();
                    cast.setName(finalObject.getJSONArray("cast").getJSONObject(i).getString("name"));
                    castList.add(cast);
                }
                models.setCastList(castList);
                modelList.add(models);
            }

            return modelList;


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {

            if (httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
            try {
                if (reader!= null){
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<MovieModels> result) {
        super.onPostExecute(result);
        MovieAdapter movieAdapter = new MovieAdapter(getApplicationContext(), R.layout.custom_row, result);
        listView.setAdapter(movieAdapter);
    }
}

public class MovieAdapter extends ArrayAdapter{

    private List<MovieModels> modelList;
    private int resource;
    private LayoutInflater inflater;
    public MovieAdapter(Context context, int resource, List<MovieModels> objects) {
        super(context, resource,  objects);
        modelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

    }

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

        if (convertView != null) {
            convertView = inflater.inflate(R.layout.custom_row,null);
        }

        //CASTING ALL THE VIEWS FROM THE CUSTOM_ROW LAYOUT
        ImageView imageView;
        TextView textViewMovie;
        TextView textViewYear;
        TextView textViewDuration;
        TextView textViewDirector;
        TextView textViewTagLine;
        TextView textViewCast;
        TextView textViewStory;
        RatingBar ratingBar;

        imageView = (ImageView)convertView.findViewById(R.id.imageView);
        textViewMovie = (TextView)convertView.findViewById(R.id.textViewMovie);
        textViewYear = (TextView)convertView.findViewById(R.id.textViewYear);
        textViewDuration =(TextView)convertView.findViewById(R.id.textViewDuration);
        textViewDirector = (TextView)convertView.findViewById(R.id.textViewDirector);
        textViewTagLine = (TextView)convertView.findViewById(R.id.textViewTagLine);
        textViewCast = (TextView)convertView.findViewById(R.id.textViewCast);
        textViewStory = (TextView)convertView.findViewById(R.id.textViewStory);
        ratingBar = (RatingBar)convertView.findViewById(R.id.ratingBarMovie);


        //DISPLAYING THE TEXT TO THE TEXTVIEWS
        textViewMovie.setText(modelList.get(position).getMovie());
        textViewYear.setText(String.valueOf(modelList.get(position).getYear()));
        textViewDuration.setText(modelList.get(position).getDuration());
        textViewDirector.setText(modelList.get(position).getDirector());
        textViewTagLine.setText(modelList.get(position).getTagline());

        //RATINGBAR
        ratingBar.setRating(modelList.get(position).getRating()/2);

        //GETTING THE CAST NAME FROM THE ARRAY
        StringBuffer castBuffer = new StringBuffer();
        for (MovieModels.Cast cast : modelList.get(position).getCastList()){
            castBuffer.append(cast.getName()+ ", ");
        }
        textViewCast.setText(castBuffer);
        textViewStory.setText(modelList.get(position).getStory());

        return convertView;
    }
}

@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_refresh) {
        new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
    }

    return super.onOptionsItemSelected(item);
}

}

因此,首先将您的JSON更改为下面的格式,为简单起见,我不在JSON中使用URL,我只写下确切的图像名称

{
      "movie": "Interstellar",
      "year": 2014,
      "rating": 8.7,
      "duration": "169 min",
      "director": "Christopher Nolan",
      "tagline": "Mankind was born on Earth. It was never meant to die here.",
      "cast": [
        {
          "name": "Matthew McConaughey"
        },
        {
          "name": "Anne Hathaway"
        },
        {
          "name": "Jessica Chastain"
        },
        {
          "name": "Wes Bentley"
        }
      ],
      "image": "interstellar.jpg",
      "story": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival."
    },
    {
      "movie": "Fantastic Four",
      "year": 2015,
      "rating": 4.0,
      "duration": "100 min",
      "director": "Josh Trank",
      "tagline": "Change is coming.",
      "cast": [
        {
          "name": "Miles Teller"
        },
        {
          "name": "Kate Mara"
        },
        {
          "name": "Michael B. Jordan"
        }
      ],
      "image": "four.jpg",
      "story": "Four young outsiders teleport to an alternate and dangerous universe which alters their physical form in shocking ways. The four must learn to harness their new abilities and work together to save Earth from a former friend turned enemy."
    }
然后进入适配器类并首先声明它

private String url_load_images="http://jsonparsing.parseapp.com/jsonData/images/";
然后转到getView方法,并按如下所示修改它

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

        if (convertView != null) {
            convertView = inflater.inflate(R.layout.custom_row,null);
        }

        //CASTING ALL THE VIEWS FROM THE CUSTOM_ROW LAYOUT
        ImageView imageView;
        TextView textViewMovie;
        TextView textViewYear;
        TextView textViewDuration;
        TextView textViewDirector;
        TextView textViewTagLine;
        TextView textViewCast;
        TextView textViewStory;
        RatingBar ratingBar;

        imageView = (ImageView)convertView.findViewById(R.id.imageView);
        textViewMovie = (TextView)convertView.findViewById(R.id.textViewMovie);
        textViewYear = (TextView)convertView.findViewById(R.id.textViewYear);
        textViewDuration =(TextView)convertView.findViewById(R.id.textViewDuration);
        textViewDirector = (TextView)convertView.findViewById(R.id.textViewDirector);
        textViewTagLine = (TextView)convertView.findViewById(R.id.textViewTagLine);
        textViewCast = (TextView)convertView.findViewById(R.id.textViewCast);
        textViewStory = (TextView)convertView.findViewById(R.id.textViewStory);
        ratingBar = (RatingBar)convertView.findViewById(R.id.ratingBarMovie);


        //DISPLAYING THE TEXT TO THE TEXTVIEWS
        textViewMovie.setText(modelList.get(position).getMovie());
        textViewYear.setText(String.valueOf(modelList.get(position).getYear()));
        textViewDuration.setText(modelList.get(position).getDuration());
        textViewDirector.setText(modelList.get(position).getDirector());
        textViewTagLine.setText(modelList.get(position).getTagline());

        //RATINGBAR
        ratingBar.setRating(modelList.get(position).getRating()/2);

        //GETTING THE CAST NAME FROM THE ARRAY
        StringBuffer castBuffer = new StringBuffer();
        for (MovieModels.Cast cast : modelList.get(position).getCastList()){
            castBuffer.append(cast.getName()+ ", ");
        }
        textViewCast.setText(castBuffer);
        textViewStory.setText(modelList.get(position).getStory());



final MovieModels models = modelList.get(position);
    Picasso.with(context)
        .load(url_load_images+models.getImage)
        .placeholder(R.drawable.user_placeholder)
        .error(R.drawable.user_placeholder_error)
        .into(imageView);

        return convertView;
    }
}

我在if语句convertView中遇到了这个错误的条件!=空到converView==空

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


    if (convertView == null) {
        convertView = inflater.inflate(R.layout.custom_row,null);
    }

内存不足,使用更少并检查是否有泄漏。最大的可能是你的形象,如果你将它们全部加载到内存中,你会很快死掉。我试图更改图像并调整其大小,但仍然出现如下错误:com.mysamples.jsonparsingdemo2.MainActivity$MovieAdapter.getViewMainActivity.java:172:此行imageView=ImageViewconvertView.findViewByIdR.id.imageView;你是如何调整图像大小的?你使用过毕加索或Glide@Gabeschen吗。请告诉ASAPNow您将在@BobCastro,google上对一个名为毕加索的库做些什么,这个库处理图像缓存,在gradle文件中添加它的依赖项,或者在lib文件夹中添加它的lib。Photoshop无法解决这个问题@BobCastro。告诉我到目前为止你已经到达了哪里,但是你没有发布你的模型classi更改“if convertView!”=如果ConvertView==null,则为null