在Android JSON新闻应用

时间:2017-05-10 12:11:48

标签: java android json android-fragments android-volley

我正在创建一个新闻应用,我是新手,在MainActivity.Java中有一些错误我无法解决它们。需要帮助!

这是我的MainActivity.Java

  package com.example.arumugam.newsreader;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;
import java.lang.String;
import java.util.List;
public class MainActivity extends Fragment {
    public MainActivity() {
        // Required empty public constructor
    }
    private List<newsItem> newsFeed = new ArrayList<>();





    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.activity_main, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle    savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("News");

        RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

        JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
                "https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray newsItem = response.getJSONArray("newsItems");

                            for (int i = 0; i < newsItem.length(); i++) {

                                JSONObject temp = newsItem.getJSONObject(i);

                                String title = temp.getString("title");
                                String description = temp.getString("description");
                                String url = temp.getString("url");
                                String urlToImage = temp.getString("urlToImage");

                                newsFeed.add(new newsItem(title, description, url, urlToImage));
                            }

                        } catch (JSONException e){
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        queue.add(newsReq);


        ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
        ListView newsItems =(ListView) (getActivity().findViewById(R.id.newsItems));
        newsItems.setAdapter(adapter);
    }




    private class customAdapter extends ArrayAdapter<newsItem>{
        Activity context;
        customAdapter(List<newsItem> newsFeed, Activity context) {
            super(getActivity(), R.layout.item, newsFeed);
            this.context = context;

        }

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

            if (convertView == null){
                convertView = getActivity().getLayoutInflater().inflate(R.layout.item, parent, false);
            }
            newsItem currentItem = newsFeed.get(position);

            ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
            TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
            TextView newsDesc = (TextView) convertView.findViewById(R.id.desc);

            newsImage.setImageResource(R.mipmap.ic_launcher);
            newsHeading.setText(currentItem.getNewsHeading());
            newsDesc.setText(String.valueOf((currentItem.getNewsDesc())));

            return convertView;
        }
    }
}

这是我的newsItem.java

public class newsItem {
    private String newsHeading;
    private String newsDesc;
    private String newsDescSmall;
    private String time;
    private String date;
    private  String url;
    private String imageURL;

    public newsItem(String newsHeading, String newsDesc, String date, String time) {
        this.newsHeading = newsHeading;
        this.newsDesc = newsDesc;
        this.time = time;
        this.date = date;
        this.url = url;
        this.imageURL = imageURL;
        this.newsDescSmall = this.newsDesc.substring(0, 50) + "...";
    }

    public String getNewsHeading() {
        return newsHeading;
    }

    public String getNewsDesc() {
        return newsDesc;
    }

    public String getNewsDescSmall() {
        return newsDescSmall;
    }

    public String getTime() {
        return time;
    }

    public String getDate() {
        return date;
    }

    public String getUrl() {
        return url;
    }

    public String getImageURL() {
        return imageURL;
    }
}

这是我的item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical" android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:padding="10dp">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/leftIco"
        android:src="@mipmap/ic_launcher"
        android:maxHeight="70dp"
        android:maxWidth="70dp"
        android:adjustViewBounds="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Description"
        android:lineSpacingExtra="-3dp"
        android:id="@+id/desc"
        android:layout_alignBottom="@+id/leftIco"
        android:layout_alignLeft="@+id/heading"
        android:layout_alignStart="@+id/heading" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:text="Heading Text"
        android:textStyle="bold"
        android:id="@+id/heading"
        android:scrollHorizontally="true"
        android:maxLines="1"
        android:layout_marginBottom="15dp"
        android:ellipsize="end"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/leftIco"
        android:layout_toEndOf="@+id/leftIco"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp" />
</RelativeLayout>

我面临的问题是这一行

ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());

提前谢谢..

Error on Android Studio Logcat Error

05-10 19:39:01.191 1232-1318/system_process E/Parcel: Class not found when unmarshalling: com.truecaller.service.MissedCallReminder
java.lang.ClassNotFoundException: com.truecaller.service.MissedCallReminder
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:400)
at android.os.Parcel.readParcelableCreator(Parcel.java:2508)
at android.os.Parcel.readParcelable(Parcel.java:2462)
at android.os.Parcel.readValue(Parcel.java:2365)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732)
at android.os.BaseBundle.unparcel(BaseBundle.java:268)
at android.os.Bundle.putAll(Bundle.java:226)
at android.content.Intent.fillIn(Intent.java:8273)
at
com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:244)
at com.android.server.am.PendingIntentRecord.sendWithResult(PendingIntentRecord.java:205)
at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:7305)
at android.app.PendingIntent.send(PendingIntent.java:836)
at com.android.server.AlarmManagerService$DeliveryTracker.deliverLocked(AlarmManagerService.java:3187)
at com.android.server.AlarmManagerService.deliverAlarmsLocked(AlarmManagerService.java:2620)
at com.android.server.AlarmManagerService$AlarmThread.run(AlarmManagerService.java:2741)
Caused by: java.lang.ClassNotFoundException: com.truecaller.service.MissedCallReminder
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:1346)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:1406)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at java.lang.Class.classForName(Native Method) 
at java.lang.Class.forName(Class.java:400) 
at android.os.Parcel.readParcelableCreator(Parcel.java:2508) 
at android.os.Parcel.readParcelable(Parcel.java:2462) 
at android.os.Parcel.readValue(Parcel.java:2365) 
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732) 
at android.os.BaseBundle.unparcel(BaseBundle.java:268) 
at android.os.Bundle.putAll(Bundle.java:226) 
at android.content.Intent.fillIn(Intent.java:8273) 
at com.android.server.am.PendingIntentRecord.sendInner(PendingIntentRecord.java:244) 
at com.android.server.am.PendingIntentRecord.sendWithResult(PendingIntentRecord.java:205) 
at com.android.server.am.ActivityManagerService.sendIntentSender(ActivityManagerService.java:7305) 
at android.app.PendingIntent.send(PendingIntent.java:836) 
at com.android.server.AlarmManagerService$DeliveryTracker.deliverLocked(AlarmManagerService.java:3187) 
at com.android.server.AlarmManagerService.deliverAlarmsLocked(AlarmManagerService.java:2620) 
at com.android.server.AlarmManagerService$AlarmThread.run(AlarmManagerService.javat:2741) 
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

4 个答案:

答案 0 :(得分:0)

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;
import java.lang.String;
import java.util.List;
public class MainActivity extends Fragment {
    private List<newsItem> newsFeed = new ArrayList<>();



    public MainActivity() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.activity_main, container, false);


        getActivity().setTitle("News");

        RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

        JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
                "https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray newsItem = response.getJSONArray("newsItems");

                            for (int i = 0; i < newsItem.length(); i++) {

                                JSONObject temp = newsItem.getJSONObject(i);

                                String title = temp.getString("title");
                                String description = temp.getString("description");
                                String url = temp.getString("url");
                                String urlToImage = temp.getString("urlToImage");

                                newsFeed.add(new newsItem(title, description, url, urlToImage));





                                ArrayAdapter<newsItem> adapter = new customAdapter(newsFeed,getActivity());
                                ListView newsItems =(ListView) (getActivity().findViewById(R.id.newsItems));
                                newsItems.setAdapter(adapter);


                            }

                        } catch (JSONException e){
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        queue.add(newsReq);



        return view;

    }




    private class customAdapter extends ArrayAdapter<newsItem>{
        Context context;
        customAdapter(List<newsItem> newsFeed, Context context) {
            super(getActivity(), R.layout.item, newsFeed);

            this.context = context;
        }

        @NonNull
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            newsItem currentItem = newsFeed.get(position);
            if (convertView == null){
                convertView = getActivity().getLayoutInflater().inflate(R.layout.item, parent, false);
            }


            ImageView newsImage = (ImageView) convertView.findViewById(R.id.leftIco);
            TextView newsHeading = (TextView) convertView.findViewById(R.id.heading);
            TextView newsDesc = (TextView) convertView.findViewById(R.id.desc);

            newsImage.setImageResource(R.mipmap.ic_launcher);
            newsHeading.setText(currentItem.getNewsHeading());
            newsDesc.setText(String.valueOf((currentItem.getNewsDesc())));

            return convertView;
        }
    }
}

答案 1 :(得分:0)

您应该更改customAdapter类

 customAdapter(List<newsItem> newsFeed, Context context) {
        super(getActivity(), R.layout.item, newsFeed);
        this.context = context;
    }

它肯定会工作....

我希望这个答案可以帮助你......

答案 2 :(得分:0)

最终找到解决方案。

修改了MainActivity.java

       import android.os.Bundle;
        import android.support.v7.app.AppCompatActivity;
        import android.support.v7.widget.LinearLayoutManager;
        import android.util.Log;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ImageView;
        import android.widget.ListView;
        import android.widget.TextView;
        import android.support.v7.widget.RecyclerView;
        import com.android.volley.Request;
        import com.android.volley.RequestQueue;
        import com.android.volley.Response;
        import com.android.volley.VolleyError;
        import com.android.volley.toolbox.JsonObjectRequest;
        import com.android.volley.toolbox.Volley;

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

        import java.util.ArrayList;
        import java.lang.String;
        import java.util.List;

        import static android.view.LayoutInflater.from;

public class MainActivity extends AppCompatActivity {
    private List<newsItem> newsFeed = new ArrayList<>();



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

        engine();
        MainActivity.this.setTitle("News");}
    private void engine() {

        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

        JsonObjectRequest newsReq = new JsonObjectRequest(Request.Method.GET,
                "https://raw.githubusercontent.com/sumbganesh/temp/master/convertjson.json",
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {


                        try {

                            JSONArray newsItem = response.getJSONObject("root").getJSONArray("articles");


                            for (int i = 0; i < newsItem.length(); i++) {

                                JSONObject temp = newsItem.getJSONObject(i);


                                String title = temp.getString("title");
                                String description = temp.getString("description");
                                String url = temp.getString("url");
                                String urlToImage = temp.getString("urlToImage");

                                newsFeed.add(new newsItem(title, description, url, urlToImage));

                            }
                            RecyclerView.Adapter adapter = new customAdapter(MainActivity.this,newsFeed);
                            RecyclerView newsItems =(RecyclerView) findViewById(R.id.newsItems);
                            LinearLayoutManager llm=new
                                    LinearLayoutManager(MainActivity.this);
                            newsItems.setLayoutManager(llm);
                            newsItems.setAdapter(adapter);


                        } catch (JSONException e){
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        queue.add(newsReq);


    }

    private class customAdapter extends RecyclerView.Adapter<MyViewHolder> {
        private final List<newsItem> newsfeedlist;

        public customAdapter(MainActivity mainActivity, List<newsItem> newsFeed) {
            this.newsfeedlist= newsFeed;
        }


        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().from(parent.getContext()).inflate(R.layout.item,parent,false);
             return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            newsItem items = newsfeedlist.get(position);
            holder.newsImage.setImageResource(R.mipmap.ic_launcher);
            holder.newsHeading.setText(items.getNewsHeading());
            holder.newsDesc.setText(items.getNewsDesc());


        }

        @Override
        public int getItemCount() {
            return newsfeedlist.size();
        }
    }

    private class MyViewHolder extends RecyclerView.ViewHolder{

        public ImageView newsImage;
        public TextView newsHeading;
        public TextView newsDesc;

        public MyViewHolder(View itemView) {

            super(itemView);
            newsImage = (ImageView) itemView.findViewById(R.id.leftIco);
            newsHeading = (TextView) itemView.findViewById(R.id.heading);
            newsDesc = (TextView) itemView.findViewById(R.id.desc);

        }
    }
}

将片段更改为Activity并将ArrayAdapter更改为Recycler视图

答案 3 :(得分:-1)

请分享您的customAdapter代码或参考本教程 Listview with customadapter

注意:使用recylerView代替listview以获得更好的性能。 创建一个凌空单例类。