java - listview 为空,我发现一个错误,但无法解决它

标签 java android json listview

我的抽屉导航应用程序中有这些文件

ma​​in_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="100dp"
android:background="@mipmap/itembg"
>

<ImageView
    android:id="@+id/thumb"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_centerVertical="true"
    android:layout_marginEnd="13dp"
    android:contentDescription="@string/todo"
    android:minHeight="80dp"
    android:padding="5dp" />

<RelativeLayout
    android:layout_width="wrap_content"
    android:minWidth="260dp"
    android:layout_height="wrap_content"
    android:minHeight="80dp"
    android:layout_toStartOf="@id/thumb"

    android:layout_marginEnd="10dp"
    >


    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:minWidth="260dp"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:fontFamily="@font/droidkufiregularfontfamily"
        android:text="@string/title"
        android:textColor="@color/colorRed"
        android:textSize="20sp"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
         />

    <TextView
        android:id="@+id/description"
        android:layout_width="wrap_content"
        android:minWidth="260dp"
        android:layout_height="wrap_content"
        android:minHeight="30dp"
        android:fontFamily="@font/droidkufiregularfontfamily"
        android:text="@string/description"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:layout_marginTop="55dp"
        android:layout_alignParentEnd="true"
         />

</RelativeLayout>

<TextView
    android:id="@+id/thumbID"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:text="@string/thumbID"
    android:textSize="1sp"
    />


</RelativeLayout>

fragment_main.xml

<RelativeLayout 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"
tools:context="com.emadzedan.iveandroid.iveandroid.MainFragment">

<RelativeLayout
    android:id="@+id/wordBG"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="@mipmap/wordbg">

    <TextView
        android:id="@+id/word2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_marginEnd="22dp"
        android:fontFamily="@font/droidkufiregularfontfamily"
        android:text="@string/word2"
        android:textColor="@color/colorAccent"
        android:textSize="12sp" />

    <TextView
        android:id="@+id/word1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginStart="25dp"
        android:fontFamily="@font/droidkufiregularfontfamily"
        android:text="@string/word1"
        android:textColor="@color/colorAccent"
        android:textSize="16sp" />
</RelativeLayout>


<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="100dp"
    android:layout_marginTop="60dp"
    android:layout_toEndOf="@id/wordBG"
    android:background="@color/colorRed" />

<RelativeLayout
    android:id="@+id/quickMenu"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@mipmap/quickmenubg" />

</RelativeLayout>


</RelativeLayout>

Java类如下:

HttpHandler.java

package com.emadzedan.iveandroid.iveandroid;

import android.util.Log;
import java.io.BufferedInputStream;
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.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
        //URLEncoder.encode(response, "utf-8");
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

MainClass.java

package com.emadzedan.iveandroid.iveandroid;

public class MainClass {
private String thumb;
private String title;
private String description;

public MainClass(String thumb, String title, String description) {
    this.thumb = thumb;
    this.title = title;
    this.description = description;
}

public String getThumb() {
    return thumb;
}

public void setThumb(String thumb) {
    this.thumb = thumb;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}
}

MainFragment.java

package com.emadzedan.iveandroid.iveandroid;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import static android.content.Context.MODE_PRIVATE;

public class MainFragment extends Fragment {
SharedPreferences prefs;
ArrayList<MainClass> mainClasses;
ListView listView;
MainDetailsFragment mainDetailsFragment;
TextView thumbID;
TextView title;
TextView description;

// URL to get contacts JSON
private static String url = "http://www.emadzedan.com/IVEArabicData/en/home.json";

ArrayList<HashMap<String, String>> mainList;

public MainFragment() {

}

public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.fragment_main, container, false);

    prefs = Objects.requireNonNull(getContext()).getSharedPreferences("SelectedItemsCookies", MODE_PRIVATE);

    mainClasses = new ArrayList<>();
    listView = (ListView) view.findViewById(R.id.listView);
    mainList = new ArrayList<>();
    listView = (ListView) view.findViewById(R.id.listView);

    new GetMainList().execute();







    mainDetailsFragment = new MainDetailsFragment();

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            thumbID = (TextView) view.findViewById(R.id.thumbID);
            title = (TextView) view.findViewById(R.id.title);
            description = (TextView) view.findViewById(R.id.description);

            SharedPreferences.Editor editor = getContext().getSharedPreferences("SelectedItemsCookies", MODE_PRIVATE).edit();
            editor.putString("thumbID", thumbID.getText().toString());
            editor.putString("title", title.getText().toString());
            editor.putString("description", title.getText().toString());
            editor.apply();

            MainActivity.CurrentFragment = "MainDestails";
            Objects.requireNonNull(getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, mainDetailsFragment).addToBackStack(MainActivity.CurrentFragment).commit();
        }
    });

    return view;
}

@SuppressLint("StaticFieldLeak")
private class GetMainList extends AsyncTask<Void, Void, Void> {

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

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray mainlistContent = jsonObj.getJSONArray("home");
                // looping through All Contacts
                Toast.makeText(getActivity(), mainlistContent.length()+"",Toast.LENGTH_SHORT).show();
                for (int i = 0; i < mainlistContent.length(); i++) {
                    JSONObject c = mainlistContent.getJSONObject(i);

                    String thumb = c.getString("thumb");
                    String title = c.getString("title");
                    String description = c.getString("description");
                    // tmp hash map for single contact
                    HashMap<String, String> mainListHashMap = new HashMap<>();

                    // adding each child node to HashMap key => value
                    mainListHashMap.put("thumb", thumb);
                    mainListHashMap.put("title", title);
                    mainListHashMap.put("description", description);

                    // adding contact to contact list
                    mainList.add(mainListHashMap);
                }
            } catch (final JSONException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),"Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }
        } else {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(),"Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
                }
            });
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        ListAdapter adapter = new SimpleAdapter(getActivity(), mainList, R.layout.main_list_row, new String[]{"thumb", "title", "description"}, new int[]{R.id.thumb, R.id.title, R.id.description});
        listView.setAdapter(adapter);
        //Toast.makeText(getActivity(), adapter.getCount()+"",Toast.LENGTH_SHORT).show();
    }

}
}

我相信错误出现在主 fragment 类中,但我无法解决它抛出的错误“无法从服务器获取 JSON。检查 Log Cat 是否存在可能的错误!” 错误 有人可以帮忙吗? 编辑: 错误就在这里

JSONArray mainlistContent = jsonObj.getJSONArray("home");

编辑2:

我可以获得响应,这是模拟器未连接到互联网,但现在我的应用程序崩溃了,我得到 致命异常:主要错误 有人可以帮忙吗?

最佳答案

// HTTP GET request
public String makeServiceCall(String reqUrl)  throws Exception {

    URL obj = new URL(reqUrl);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header //OPTINAL
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
       BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
       String inputLine;
       StringBuffer response = new StringBuffer();

       while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
       }
       //print result
       Log.d("Response", response.toString());
       in.close();
       return response;
    } else {
      //can not connect to server
      Log.d("Response code", responseCode +" "); 
    }
    return "";
}

你可以使用上面的代码从服务器获取json字符串,如果responseCode != 200。这意味着你出错了。

完整源代码

public class MainActivity extends AppCompatActivity {
private static String url = "http://www.emadzedan.com/IVEArabicData/en/home.json";

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

    new AsyncTask<Void, Void, Void>(){

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                makeServiceCall(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }.execute();
}

// HTTP GET request
public String makeServiceCall(String reqUrl)  throws Exception {

    URL obj = new URL(reqUrl);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header //OPTINAL
    //con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        //print result
        Log.d("Response", response.toString());
        in.close();
        return response.toString();
    } else {
        //can not connect to server
        Log.d("Response code", responseCode +" ");
    }
    return "";
}

}

关于java - listview 为空,我发现一个错误,但无法解决它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50777448/

相关文章:

java - 为什么将 (EditText) findViewById 转换为 (EditText)?

java - 使用 HTTPS 实现 RESTful Web 服务

java - 在数组声明中 int[] k,i 和 int k[],i;

android - 使用 Jack 编译器时禁用 Instant Run

android - 什么时候在 NDK 中调用全局变量的 C++ 析构函数?

java - Matlab 中的 GZIP 用于大文件

java - Android 的线程和网络

c# - 如何不将属性与 JSON 数据绑定(bind)

json - 如何通过 API 将映射函数与 JSON 对象获取结合使用

python - 使用 Python 3 将 JSON 转换为 CSV