适配器没有显示当前元素?

huangapple 未分类评论61阅读模式
标题翻译

The adapter doesn't show the current element?

问题

适配器只显示一个项目,而 JSON 包含更多项目。如何让适配器显示所有 JSON 元素?我有一个加载器,它只显示一个元素并重复显示它。JSON 中的元素没有显示在适配器中,我尝试了一些方法,但它不起作用!我如何从响应中显示和获取每个单独的元素?

适配器:

public class shelfsAdapter extends ArrayAdapter<shelfs> {
    public shelfsAdapter(MainActivity context, ArrayList<shelfs> objects) {
        super(context, 0, objects);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItem = convertView;
        if (listItem == null) {
            listItem = LayoutInflater.from(getContext())
                .inflate(R.layout.item, parent, false);
        }
        shelfs current = getItem(position);
        TextView title = (TextView) listItem.findViewById(R.id.title);
        title.setText(current.getTitle());
        TextView author = (TextView) listItem.findViewById(R.id.author);
        author.setText(current.getAuthors());
        return listItem;
    }
}

加载器:

public class LoaderApp extends AsyncTaskLoader<List<shelfs>> {
    private String url;

    public LoaderApp(Context context, String mUrl) {
        super(context);
        url = mUrl;
    }

    @Override
    protected void onStartLoading() {
        forceLoad();
    }

    @Override
    public List<shelfs> loadInBackground() {
        if (url == null) {
            return null;
        }
        List<shelfs> books = QueryUtils.fetchData(url);
        return books;
    }
}

主活动:

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<shelfs>> {
    private shelfsAdapter adapter;
    private static final String url = "https://www.googleapis.com/books/v1/volumes?q={search%20terms}";
    private static final int ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        adapter = new shelfsAdapter(this, new ArrayList<shelfs>());
        ListView listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);

        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            getSupportLoaderManager().initLoader(ID, null, this);
        }
    }

    // ...其他回调方法...
}

JSON 类:

public class QueryUtils {
    // ...其他方法...

    public static List<shelfs> ExtractJsonData(String jsonResponse) {
        List<shelfs> putshelfs = new ArrayList<>();
        try {
            JSONObject base = new JSONObject(jsonResponse);
            JSONArray items = base.getJSONArray("items");
            for (int i = 0; i < items.length(); i++) {
                JSONObject index = items.getJSONObject(i);
                JSONObject volume = index.getJSONObject("volumeInfo");
                String title = volume.getString("title");
                JSONArray authors = volume.getJSONArray("authors");
                String auth = authors.getString(0);
                shelfs currentShelf = new shelfs(title, auth);
                putshelfs.add(currentShelf);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return putshelfs;
    }
}

以上是你提供的代码的翻译部分。如有需要,你可以根据这些翻译继续操作。

英文翻译

The adapter shows only one item will JSON has more than that number how can the adapter shows all the JSON elements? i have loader and it is only shows one element and repeat it?
the JSON ger elements doesn't show in the adapter I tried things but it doesn't work !! how can I show and take every single element from the response.

the image shows the elements

适配器没有显示当前元素?

the adapter:

  public class shelfsAdapter extends ArrayAdapter &lt; shelfs &gt; {
      public shelfsAdapter(MainActivity context, ArrayList &lt; shelfs &gt; objects) {
          super(context, 0, objects);
      }@
      Override
      public View getView(int position, View convertView, ViewGroup parent) {
          View listItem = convertView;
          if (listItem == null) {
              listItem = LayoutInflater.from(getContext())
                  .inflate(R.layout.item, parent, false);
          }
          shelfs current = getItem(position);
          TextView title = (TextView) listItem.findViewById(R.id.title);
          title.setText(current.getTitle());
          TextView author = (TextView) listItem.findViewById(R.id.author);
          author.setText(current.getAuthors());
          return listItem;
      }
  }

the loader:

    public class LoaderApp extends AsyncTaskLoader&lt;List&lt;shelfs&gt;&gt; {
      private String url;


      public LoaderApp( Context context,String mUrl) {
        super(context);
        url = mUrl;
      }
      
      @Override
      protected void onStartLoading() {
        Log.v(&quot;forceload&quot;,&quot;force close dossseeeeeee!!!&quot;);
        forceLoad();
      }
    
      @Override
      public  List&lt;shelfs&gt; loadInBackground(){
        if(url==null){return  null;}
        Log.v(&quot;get books&quot;,&quot;get books&quot;);
        List&lt;shelfs&gt; books = QueryUtils.fetchData(url);
        Log.v(&quot;get query&quot;,&quot;get query&quot;);
        Log.v(&quot;equals query&quot;,&quot;equals&quot;+books.get(0)+&quot;&quot;+books.get(2));
        //  books.add(new shelfs(&quot;books&quot;,&quot;books inback &quot;));
        return books;
      }

the main Activity:

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks&lt;List&lt;shelfs&gt;&gt; {
  private   shelfsAdapter adapter;
  private static final String url = &quot;https://www.googleapis.com/books/v1/volumes?q={search%20terms}&quot;;
  private static final int ID=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     //final String url1=&quot;  https://www.googleapis.com/books/v1/volumes?q=android&amp;maxResults=1\n&quot;;
         adapter = new shelfsAdapter(this, new ArrayList&lt;shelfs&gt;());
        ListView listView = (ListView) findViewById(R.id.list);
        Log.v(&quot;geturl fine&quot;,&quot;fine get it&quot;);
        listView.setAdapter(adapter);

        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        // Get details on the currently active default data network
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        // If there is a network connection, fetch data
        if (networkInfo != null &amp;&amp; networkInfo.isConnected()) {
            // Get a reference to the LoaderManager, in order to interact with loaders.
            android.app.LoaderManager loaderManager = getLoaderManager();
            Log.v(&quot;loading &quot;,&quot;loader inflater&quot;);
            // Initialize the loader. Pass in the int ID constant defined above and pass in null for
            // the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid
            // because this activity implements the LoaderCallbacks interface).
            getSupportLoaderManager().initLoader(ID, null, this);
        }}




    @NonNull
    @Override
    public Loader&lt;List&lt;shelfs&gt;&gt; onCreateLoader(int id, @Nullable Bundle args) {
        Log.v(&quot;get load&quot;,&quot;get load on create&quot;);
        Toast.makeText(this,&quot;creat it just!!!&quot;,Toast.LENGTH_SHORT).show();
        adapter.add(new shelfs(&quot;oncreat&quot;,&quot;loadApp on create loader&quot;));

        return new LoaderApp(this,url);


    }

    @Override
    public void onLoadFinished(@NonNull Loader&lt;List&lt;shelfs&gt;&gt; loader, List&lt;shelfs&gt; data) {
    if(data != null &amp;&amp; !data.isEmpty() )
        Log.v(&quot;get load&quot;,&quot;get load on finished&quot;);
       // adapter.add(new shelfs(&quot;onloadfinish&quot;,&quot;addall??&quot;));
        adapter.addAll(data);
        adapter.notifyDataSetChanged();

        // Log.v(&quot;data add&quot;,&quot;data&quot;+data.get(0)+&quot;&quot;+data.get(6));
       // Toast.makeText(this,&quot;data&quot;,Toast.LENGTH_SHORT).show();


    }

    @Override
    public void onLoaderReset(@NonNull Loader&lt;List&lt;shelfs&gt;&gt; loader) {
        Log.v(&quot;get load&quot;,&quot;get load on reset&quot;);
        adapter.clear();

    }

and the json class:

public class QueryUtils {
    public QueryUtils(){}

    public static List&lt;shelfs&gt; fetchData(String requestUrl)  {
        if (requestUrl ==null) {return null;}
        Log.v(&quot;fetchData work!&quot;,&quot;fetchData work!&quot;);
            URL uRl=getUrl(requestUrl);
        Log.v(&quot;geturl work!&quot;,&quot;geturl work!&quot;);
        String json=null;
        try {
             json=makeHttprequest(uRl);
            Log.v(&quot;makehttp work!&quot;,&quot;makehttp work!&quot;);
        }catch (IOException e){Log.v(&quot;error fetch&quot;,&quot;error fetch&quot;);}
        List&lt;shelfs&gt; makeit=ExtractJsonData(json);
        Log.v(&quot;extractdata work!&quot;,&quot;extractdata work!&quot;);
        return makeit;
    }

    public static URL getUrl(String urlhttp) {
        URL url=null;
        try{ url=new URL(urlhttp);}
        catch (MalformedURLException e){Log.v(&quot;url error&quot;,&quot;url error&quot;,e);}
        return url;
    }


    public static String readStream(InputStream inputStream) throws IOException {
        StringBuilder stringBuilder=new StringBuilder();
        if(inputStream!=null)
        { InputStreamReader isr=new InputStreamReader(inputStream, Charset.forName(&quot;UTF-8&quot;));
        BufferedReader reader=new BufferedReader(isr);
        String line=reader.readLine();
        while(line!=null){stringBuilder.append(line);
        line=reader.readLine();}}
        return stringBuilder.toString();
    }

    public static String makeHttprequest(URL url)throws IOException{
        String jsonResponse=&quot;&quot;;
        InputStream inputStream=null;
        HttpURLConnection urlConnection=null;
        try {
            urlConnection=(HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod(&quot;GET&quot;);
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.connect();
            if(urlConnection.getResponseCode()==200)
            {inputStream=urlConnection.getInputStream();
            jsonResponse=readStream(inputStream);
                Log.e(&quot;connect error&quot;,&quot;connect&quot;);}}
            catch(IOException e){Log.e(&quot;connect error&quot;,&quot;connect error&quot;);}
            finally{
                if(urlConnection!=null){urlConnection.disconnect();}
                if(inputStream!=null){inputStream.close();}
            }
            return jsonResponse; }


    public static List&lt;shelfs&gt; ExtractJsonData(String jsonResponse){
        List&lt;shelfs&gt; putshelfs=new ArrayList&lt;&gt;();
        try {
            JSONObject base=new JSONObject(jsonResponse);
            JSONArray items=base.getJSONArray(&quot;items&quot;);
            shelfs firstShelfs=new shelfs(&quot;&quot;,&quot;&quot;);
            for(int i=0;i&lt;items.length();i++)
            {
                JSONObject index = items.getJSONObject(i);
                JSONObject volume=index.getJSONObject(&quot;volumeInfo&quot;);
                String title=volume.getString(&quot;title&quot;);
                JSONArray authors=volume.getJSONArray(&quot;authors&quot;);
                String auth=authors.getString(0);
                 firstShelfs= new shelfs(title,auth);
                putshelfs.add(i,firstShelfs);

                Log.v(&quot;gggg&quot;,&quot;net get&quot;+i+auth+title+&quot;dom&quot;);}
            Log.v(&quot;dff&quot;,&quot;json take&quot;);
        } catch (JSONException e) {
            e.printStackTrace(); }

        return  putshelfs;}

}

huangapple
  • 本文由 发表于 2020年3月16日 16:05:02
  • 转载请务必保留本文链接:https://java.coder-hub.com/60702281.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定