当前位置: 首页 > 知识库问答 >
问题:

listview为空,我捕获到一个错误,但无法解决它

温凯
2023-03-14
<?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>
<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>
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();
}
}
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;
}
}
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();
    }

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

共有1个答案

边永贞
2023-03-14
// 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 "";
}
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 "";
}

}
 类似资料:
  • https://maven.apache.org/xsd/maven-4.0.0.xsd“>4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.6.release com.bookstore bookstore 0.0.1-snapshot bookstore这是我的项目的描述。 http://localhost:8081/M

  • 失败:生成失败,出现异常。 > 其中:Script'C:\src\flatter\packages\flatter\u tools\gradle\app\u plugin\u loader。梯度线:18 问题:评估脚本时出现问题。 无法加载FastStringService > 尝试:使用--stacktrac选项运行以获取堆栈跟踪。使用--info或--debug选项运行以获取更多日志输出。使用

  • 现在我正在尝试从git运行克隆应用程序https://github.com/frinder/frinder-app但问题是该应用程序制作了很长时间,所以应该改变bulid.gradle 但是当我尝试相同的同步实现“com.android.支持:动画矢量可绘制:28.0.0”,但如果我删除它,请继续向我显示错误28.0.0它显示如下 但我不知道是什么造成了不完全相同的版本 这是应用程序build.g

  • 问题内容: 对于Java的最终结业,我们在测试中包含“异常”部分,其中包括try,catch和finally调用。当我尝试将示例代码放入Eclipse时,遇到了错误并抛出了新的领域。所有错误都显示“无法解析键入”。 如何解决此问题,以便可以学习/查看代码应该执行的操作? Q4类 Q4Exception类 问题答案: 我认为值得一提的是,在Eclipse中,Ctrl + Shif + O可以为您解决

  • unsatisfiedDependencyException:创建文件[D:\priya\cre-audit-service\target\类\com\ads\cre\api\controller\fieldValuesController.class]中定义的名为“field valuesController”的bean时出错:通过构造函数参数1表示的不满足的依赖项;嵌套异常为org.sprin

  • 我开始在leetcode上编码,然后在playground中打开它,并将该代码放入本地json jar,然后导入json jar,但仍然看到json无法解析的错误。 错误行:返回json.value(input).ToString(); 如有任何帮助,将不胜感激。 提前道谢。