简体   繁体   中英

Show json file from url to listview inside fragment

I recently learn about android programming. Now, i'm tying to fetch data from php with json to my android app.

Here is my script

Bamanual.java

package com.example.boby.firstapp;

import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;


public class Bamanual extends Fragment {
    ListView listView;
    ArrayList<HashMap<String, String>> list_data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bamanual, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("Menu Ba Manual");
        getJSON("http://192.168.3.223:84/fppb/andro_login/fppb");
    }

    private void loadIntoListView(String json) throws JSONException {
        ArrayList<String> items = new ArrayList<String>();

        JSONArray jsonArray = new JSONArray(json);
        String[] ba = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            String name=obj.getString("ItemCode");
            String photo=obj.getString("PhotoName");
            items.add(name);
        }
        ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_expandable_list_item_1, items);
        listView = (ListView) listView.findViewById(R.id.listView1);
        listView.setAdapter(mArrayAdapter);
        //Toast.makeText(getActivity(), jsonArray.toString(), Toast.LENGTH_LONG).show();
    }

    private void getJSON(final String urlWebService) {

        class GetJSON extends AsyncTask<Void, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                try {
                    loadIntoListView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            protected String doInBackground(Void... voids) {

                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;

                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }

                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }

            }
        }

        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }
}

and here is my fragment fragment_bamanual.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >
    </ListView>


</FrameLayout>

So, when I run it, my app is force close. So, how can I fix it ? Did I miss something ?

Thanks in advance and sorry for my bad English.

I get this in my logcat.

12-12 09:59:21.382 14806-15139/com.example.boby.firstapp E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE) 
12-12 09:59:21.388 14806-15139/com.example.boby.firstapp E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE) 
12-12 09:59:30.235 14806-14806/com.example.boby.firstapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.boby.firstapp, PID: 14806
                                                                           java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.ListView.findViewById(int)' on a null object reference
                                                                               at com.example.boby.firstapp.Bamanual.loadIntoListView(Bamanual.java:55)
                                                                               at com.example.boby.firstapp.Bamanual.access$000(Bamanual.java:25)
                                                                               at com.example.boby.firstapp.Bamanual$1GetJSON.onPostExecute(Bamanual.java:73)
                                                                               at com.example.boby.firstapp.Bamanual$1GetJSON.onPostExecute(Bamanual.java:62)
                                                                               at android.os.AsyncTask.finish(AsyncTask.java:695)
                                                                               at android.os.AsyncTask.-wrap1(Unknown Source:0)
                                                                               at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                               at android.os.Looper.loop(Looper.java:164)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

I'm not sure without any error message but I think view binding is weird. Please check below codes. Find listView from rootView because your listView can be null.

public class Bamanual extends Fragment {
    ListView listView;
    ArrayList<HashMap<String, String>> list_data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_bamanual, container, false);
        listView = (ListView) rootView.findViewById(R.id.listView1);
        return rootView;
    }

If you check this part String name=obj.getString("ItemCode"); String photo=obj.getString("PhotoName"); items.add(name); . I want to send both , how can i achieve that

public class Bamanual extends Fragment {
    ListView listView;
    ArrayList<Photo> list_data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_bamanual, container, false);
        listView = (ListView) rootView.findViewById(R.id.listView1);
        return rootView;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("Menu Ba Manual");
        getJSON("http://192.168.3.223:84/fppb/andro_login/fppb");
    }

    private void loadIntoListView(String json) throws JSONException {
        List<Photo> items = new ArrayList<Photo>();

        JSONArray jsonArray = new JSONArray(json);
        String[] ba = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            String code=obj.getString("ItemCode");
            String name=obj.getString("PhotoName");
            items.add(new Photo(code, name);
        }
        ArrayAdapter<Photo> mArrayAdapter = new ArrayAdapter<Photo>(getActivity(),android.R.layout.simple_expandable_list_item_1, items);
        listView.setAdapter(mArrayAdapter);
        //Toast.makeText(getActivity(), jsonArray.toString(), Toast.LENGTH_LONG).show();
    }

Photo

public class Photo {
    String code;
    String name;

    public Photo(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public String getName() {
        return name;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM