简体   繁体   English

我正在尝试使用JSON格式显示来自MySQL数据库的数据,但我一直收到以下错误

[英]I am trying to display data from MySQL database using JSON Format but i keep getting the following error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myexample/com.example.myexample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference

My MainActivity Looks like this: 我的MainActivity看起来像这样:

public class MainActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {

private List<School> listSchools;

//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;

//Volley Request Queue
private RequestQueue requestQueue;

//The request counter to send ?page=1, ?page=2  requests
private int requestCount = 1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //Initializing Views
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    if (recyclerView != null) {
        recyclerView.setHasFixedSize(true);
    }
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSchools = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(this);

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(this);

    //initializing our adapter
    adapter = new SchoolRecyclerAdapter(listSchools, this);

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    if (fab != null) {
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
}
//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar


    //JsonArrayRequest of volley

    //Returning the request
    return new JsonArrayRequest(Configu.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response
                    parseData(response);
                    //Hiding the progressbar

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    //If an error occurs that means end of the list has reached
                    Toast.makeText(MainActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the school object
        School school = new School();
        JSONObject json;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            school.setImageUrl(json.getString(Configu.TAG_IMAGE_URL));
            school.setName(json.getString(Configu.TAG_NAME));
            school.setCity(json.getString(Configu.TAG_CITY));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the school object to the list
        listSchools.add(school);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}

@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);
}}}

My Manifest is as follows: 我的清单如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myexample">
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Your help would be greatly appreciated. 您的帮助将不胜感激。

You are not initializing the school list really in the scope.Try this way: 您并未真正在范围内初始化学校名单。

public class MainActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {

        private List<School> listSchools;

        //Creating Views
        private RecyclerView recyclerView;
        private RecyclerView.Adapter adapter;

        //Volley Request Queue
        private RequestQueue requestQueue;

        //The request counter to send ?page=1, ?page=2  requests
        private int requestCount = 1;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            //Initializing Views
            recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            if (recyclerView != null) {
                recyclerView.setHasFixedSize(true);
            }
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
            recyclerView.setLayoutManager(layoutManager);

            //Initializing our superheroes list
            listSchools = new ArrayList<>();
            requestQueue = Volley.newRequestQueue(this);

            //Calling method to get data to fetch data
            getData(listSchools);

            //Adding an scroll change listener to recyclerview
            recyclerView.setOnScrollChangeListener(this);

            //initializing our adapter
            adapter = new SchoolRecyclerAdapter(listSchools, this);

            //Adding adapter to recyclerview
            recyclerView.setAdapter(adapter);

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            if (fab != null) {
                fab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();
                    }
                });
            }
        }
        //Request to get json from server we are passing an integer here
        //This integer will used to specify the page number for the request ?page = requestcount
        //This method would return a JsonArrayRequest that will be added to the request queue
        private JsonArrayRequest getDataFromServer(int requestCount, List<School> listSchools) {
            //Initializing ProgressBar


            //JsonArrayRequest of volley

            //Returning the request
            return new JsonArrayRequest(Configu.DATA_URL + String.valueOf(requestCount),
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            //Calling method parseData to parse the json response
                            parseData(response, listSchools);
                            //Hiding the progressbar

                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                            //If an error occurs that means end of the list has reached
                            Toast.makeText(MainActivity.this, "No More Items Available", Toast.LENGTH_SHORT).show();
                        }
                    });
        }

        //This method will get data from the web api
        private void getData(List<School> listSchools) {
            //Adding the method to the queue by calling the method getDataFromServer
            requestQueue.add(getDataFromServer(requestCount, listSchools));
            //Incrementing the request counter
            requestCount++;
        }

        //This method will parse json data
        private void parseData(JSONArray array, List<School> listSchools) {
            for (int i = 0; i < array.length(); i++) {
                //Creating the school object
                School school = new School();
                JSONObject json;
                try {
                    //Getting json
                    json = array.getJSONObject(i);

                    //Adding data to the superhero object
                    school.setImageUrl(json.getString(Configu.TAG_IMAGE_URL));
                    school.setName(json.getString(Configu.TAG_NAME));
                    school.setCity(json.getString(Configu.TAG_CITY));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //Adding the school object to the list
                listSchools.add(school);
            }

            //Notifying the adapter that data has been added or changed
            adapter.notifyDataSetChanged();
        }

        //This method would check that the recyclerview scroll has reached the bottom or not
        private boolean isLastItemDisplaying(RecyclerView recyclerView) {
            if (recyclerView.getAdapter().getItemCount() != 0) {
                int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
                if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
                    return true;
            }
            return false;
        }

        //Overriden method to detect scrolling
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            //Ifscrolled at last then
            if (isLastItemDisplaying(recyclerView)) {
                //Calling the method getdata again
                getData();
            }
        }

        @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);
        }}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试从 MySql 中的数据库检索数据时出现“java.lang.ClassNotFoundException: com.mysql.jdbc.Driver”错误 - I am getting " java.lang.ClassNotFoundException: com.mysql.jdbc.Driver " error while trying to retrieve data from the database in MySql 我正在尝试从 Excel 表中获取数据并将这些测试数据传递到登录和密码字段中,但出现以下错误 - I am trying to get data from excel sheet and pass those test data into the login & password field but I am getting following error 我正在尝试使用回收站视图从 Firebase 数据库中检索数据,但出现错误 - i am trying to retrieve the data from fire base database using recycler view but i am getting errors in it 我正在尝试使用 getter 和 setter 从我的 firebase 数据库中检索数据,但收到错误提示无法转换对象 - I am trying to retrieve data from my firebase database using getter and setter but getting an error says can't convert the object 我正在尝试使用休眠xml映射连接到mysql数据库,但出现此错误 - I am trying to connect to a mysql database with hibernate xml mapping but I am getting this error 当我试图解密获得以下错误 - When I am trying to decrypt getting following error 当我试图从 springboot 中的 Mysql 数据库中获取数据时,我收到以下错误“给定的 id 不能为空” - As iam trying to fetch the data from Mysql Database in springboot iam getting following error of "The given id must not be null" 我正在尝试将值从数据库传递给 js。 但是我收到了一个步进错误? - I am trying to pass values from Database to js. But i am getting an error of stepup? 我正在尝试使用zip4j jar文件提取受密码保护的ZIP文件,但出现以下错误 - I am trying to extract password-protected ZIP files using zip4j jar file but i am getting error for following JTable 错误:我试图在文本字段中显示来自 JTable 的选定行值,但我不断收到此错误: - JTable error: I'm trying to display the selected row values from a JTable in the textfield but I keep getting this error:
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM