Java 错误地覆盖包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42944107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Incorrectly overriding a package
提问by Kartik Sharma
I am getting this error.
我收到此错误。
03-22 11:41:20.439 20933-20933/com.androidcss.jsonexample E/RecyclerView: No adapter attached; skipping layout 03-22 11:41:20.760 20933-20933/com.androidcss.jsonexample W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-22 11:41:20.439 20933-20933/com.androidcss.jsonexample E/RecyclerView:没有附加适配器;跳过布局 03-22 11:41:20.760 20933-20933/com.androidcss.jsonexample W/art:在 Android 4.1 之前,方法 int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) 会错误地覆盖android.widget.ListView 中的 package-private 方法
MainActivity.java
主活动.java
package com.androidcss.jsonexample;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFishPrice;
private AdapterFish mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Make call to AsyncTask
new AsyncLogin().execute();
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("https://newsapi.org/v1/articles?source=the-next-web&sortBy=latest&apiKey=bdba5de1b490495796a1595f77ed3f37");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<Item> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONObject object= new JSONObject(result);
JSONArray array = object.getJSONArray("articles");
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<array.length();i++){
JSONObject json_data = array.getJSONObject(i);
Item item= new Item();
item.name= json_data.getString("title");
data.add(item);
}
// Setup and Handover data to recyclerview
mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFishPrice.setAdapter(mAdapter);
mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
AdapterFish.java
AdapterFish.java
package com.androidcss.jsonexample;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.Collections;
import java.util.List;
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<Item> data= Collections.emptyList();
Item current;
int currentPos=0;
// create constructor to innitilize context and data sent from MainActivity
public AdapterFish(Context context, List<Item> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when viewholder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.card, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in recyclerview to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
Item current=data.get(position);
myHolder.name.setText(current.getName());
// load image into imageview using glide
/*Glide.with(context).load("http://192.168.1.7/test/images/" + current.fishImage)
.placeholder(R.drawable.ic_img_error)
.error(R.drawable.ic_img_error)
.into(myHolder.ivFish);*/
}
// return total item from List
@Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView name;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.name);
}
}
}
Item.java
项目.java
package com.androidcss.jsonexample;
public class Item {
String name;
public String getName() {
return name;
}
}
回答by Zarul Izham
You need to setLayoutManager
before setAdapter
.
你需要setLayoutManager
之前setAdapter
。
回答by Mohammed Atif
You are initializing the RecyclerView
in AsynTask
, that means your ReyclerView
is not ready when view is created.
您正在初始化RecyclerView
in AsynTask
,这意味着您ReyclerView
在创建视图时还没有准备好。
Make the following changes.
进行以下更改。
//make list as global variable
private List<Item> data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//view should be initialized in UI thread
data=new ArrayList<>();
mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mRVFishPrice.setAdapter(mAdapter);
//Make call to AsyncTask
new AsyncLogin().execute();
}
Then in your onPostExecute
然后在你的 onPostExecute
replace -
代替 -
mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
mRVFishPrice.setAdapter(mAdapter);
mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));
with
和
mAdapter.notifyDatasetChanged();
and also, make sure you remove the List<Item> data
from postexecute and make it global
而且,请确保List<Item> data
从 postexecute 中删除并使其成为全局
And please use Volley to make API calls instead of implementing Custom Background Task. Volley Handles the API calls asynchronously without messing up your Actual Code.
并且请使用 Volley 进行 API 调用,而不是实现自定义后台任务。Volley 异步处理 API 调用,而不会弄乱您的实际代码。
回答by Jatin Shara
I faced the same issue. The problem was in Layout. You should first verify that if your Views and Layouts are in correct order.
我遇到了同样的问题。问题出在布局中。您应该首先验证您的视图和布局的顺序是否正确。