gpt4 book ai didi

java - 使用Recyclerview解析Json

转载 作者:行者123 更新时间:2023-12-02 10:48:48 26 4
gpt4 key购买 nike

这里我试图显示测试的名称和价格。我正在采用回收器 View ,使用 JET Parsing GET 方法执行相同的操作。但我在我的生意上一无所获,并在那里展示了自己的黑人形象。这是我的代码请帮我找到解决方案。

模型类

        public class TestListsModel {

public String test_price;

public String testlist_id;

public String test_name;
}

这是我的适配器:

public class AdapterTestList  extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<TestListsModel> data= Collections.emptyList();
TestListsModel current;
int currentPos=0;

// create constructor to innitilize context and data sent from MainActivity
public AdapterTestList(Context context, List<TestListsModel> 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.test_list_row, 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;
TestListsModel current=data.get(position);
myHolder.testName.setText(current.test_name);
myHolder.testPrice.setText( current.test_price);


// 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 testName;
TextView testPrice;

// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);

testName = (TextView) itemView.findViewById(R.id.test_name);
testPrice = (TextView) itemView.findViewById(R.id.price_name);

}

}

}

这是我的 Activity 类(class):

public class HealthServicesActivity extends AppCompatActivity implements View.OnClickListener {

SharePreferenceManager<LoginModel> sharePreferenceManager;

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView testListRecylerView;
private AdapterTestList mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_health_services);
ButterKnife.bind(this);

sharePreferenceManager = new SharePreferenceManager<>(getApplicationContext());

dayTimeDisplay();

new AsyncLogin().execute();
}

private class AsyncLogin extends AsyncTask<String, String, String> {
//ProgressDialog pdLoading = new ProgressDialog(getApplicationContext());
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 {

String url_test="http://192.168.1.80/aoplnew/api/users/gettestlist/"+sharePreferenceManager.getUserLoginData(LoginModel.class).getResult().getCenterId();
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
//url = new URL("http://192.168.1.7/test/example.json");
url = new URL(url_test);

} 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 ("[]");
}

} 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<TestListsModel> data=new ArrayList<>();

//pdLoading.dismiss();
try {

JSONArray jArray = new JSONArray(result);

// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
TestListsModel testData = new TestListsModel();
testData.testlist_id= json_data.getString("testlist_id");
testData.test_name= json_data.getString("test_name");
testData.test_price= json_data.getString("test_price");

data.add(testData);
}

// Setup and Handover data to recyclerview
testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);
mAdapter = new AdapterTestList(HealthServicesActivity.this, data);
testListRecylerView.setAdapter(mAdapter);
testListRecylerView.setLayoutManager(new LinearLayoutManager(HealthServicesActivity.this));

} catch (JSONException e) {
Toast.makeText(HealthServicesActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}

}

}
}

预先感谢您的回答!

最佳答案

您需要在设置适配器之前设置setLayoutManager,如下所示。在您的代码中,您在 setLayoutManager 之前有 setAdapter(),因此您的适配器未正确设置。

请参阅此以获得进一步的解释 https://developer.android.com/guide/topics/ui/layout/recyclerview

    testListRecylerView = (RecyclerView)findViewById(R.id.test_list_recycler_view);


mAdapter = new AdapterTestList(HealthServicesActivity.this, data);
/**
* SET THE LAYOUT MANAGER BEFORE SETTING THE ADAPTER
*/

RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(HealthServicesActivity.this);
testListRecylerView.setLayoutManager(mLayoutManager);
testListRecylerView.setItemAnimator(new DefaultItemAnimator());

/**
* AND THAN SET THE ADAPTER
*/

testListRecylerView.setAdapter(mAdapter);

关于java - 使用Recyclerview解析Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52332338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com