[英]Update textview of fragment from Adapter (asyncTask)
將文本設置為Textview有點麻煩,請檢查以下情況
因此,我有一個片段,片段中有產品名稱,價格和兩個RecyclerView
(1個肖像,1個水平),然后在項目上單擊水平RecyclerView,它將嘗試獲取該特定項目的價格,並根據服務器的響應想要將該值設置為fragment的價格TextView
,但是當我顯式更新值時它返回空指針,因此我嘗試了所有下面的代碼,這些代碼都不對我有用。
在片段中創建用於設置文本的方法,然后從AsyncTask
調用該方法(問題:未加載UI,這就是拋出空指針的原因)
使用Layooutinfleter
。
protected void onPostExecute(String s) {
super.onPostExecute(s);
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view = inflater.inflate( R.layout.fragment_product, null );
TextView tv = view.findViewById(R.id.productPricePopUp);
tv.setText(s);
System.out.println("Rohit " + tv.getText());
}
我不知道何時設置文本可以正常工作,並且它顯示我設置的文本,但不更新TextView。
是否有將文本設置為TextView的解決方案? 請幫助我找到解決方案。
水平RecyclerView位於人像RecyclerView(嵌套)中
Product.java(片段)
public class Product extends SuperBottomSheetFragment {
public TextView name,des,price;
private OnFragmentInteractionListener mListener;
public int id = 0;
public Context context;
public String server_response = null;
public int ArrayID = 0;
public RecyclerView variationRecycler;
public List<variationModel> data = new ArrayList<>();
public variationAdapter adapter;
@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view1 = inflater.inflate(R.layout.fragment_product, container, false);
final MainActivity activity;
activity = (MainActivity)getActivity();
assert activity != null;
server_response = activity.server_response;
name = view1.findViewById(R.id.productNamePopUp);
des = view1.findViewById(R.id.productDesPopUp);
price = view1.findViewById(R.id.productPricePopUp);
variationRecycler = view1.findViewById(R.id.variationRecycler);
variationRecycler.setNestedScrollingEnabled(true);
variationRecycler.setLayoutManager(new LinearLayoutManager(view1.getContext().getApplicationContext()));
variationRecycler.setHasFixedSize(true);
variationRecycler.setItemAnimator(new DefaultItemAnimator());
ArrayID = this.getArguments().getInt("id");
new ExecuteOnBack(context).execute();
return view1;
}
class ExecuteOnBack extends AsyncTask<Void,Void,Void>{
String url = null;
public Context context;
public ProgressDialog p;
@Override
protected void onPreExecute() {
super.onPreExecute();
p = new ProgressDialog(context);
p.setMessage("Please Wait...");
p.setCancelable(false);
p.show();
}
public ExecuteOnBack(Context context){
this.context = context;
}
@Override
protected Void doInBackground(Void... voids) {
try {
JSONArray array = new JSONArray(server_response);
JSONObject object1 = array.getJSONObject(ArrayID);
name.setText(object1.getString("name"));
des.setText(object1.getString("short_description"));
price.setText("Rs." + object1.getString("price"));
System.out.println("Rohit" + object1.getJSONArray("attributes").getJSONObject(0).getJSONArray("options"));
for(int k=0;k<object1.getJSONArray("attributes").length();k++){
ArrayList<optionModel> listdata = new ArrayList<optionModel>();
JSONArray jArray = object1.getJSONArray("attributes").getJSONObject(k).getJSONArray("options");
//JSONArray IDArray = object1.getJSONArray("attributes").getJSONObject(k).getJSONArray("ids");
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(new optionModel(jArray.getString(i),174));
}
}
data.add(new variationModel(object1.getJSONArray("attributes").getJSONObject(k).getString("name"),object1.getJSONArray("attributes").getJSONObject(k).getInt("id"),listdata));
}
System.out.println("Rohit" + data.get(0).getName());
adapter = new variationAdapter(data);
variationRecycler.setAdapter(adapter);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
p.dismiss();
}
}
}
variantAdapter.java(Portrait Recyclerview)
class variationHolder extends RecyclerView.ViewHolder{
public TextView name;
public TextView id;
public ArrayList<String> array = new ArrayList<>();
public RecyclerView horizontal_variation;
public variationHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.variationNameFirst);
horizontal_variation = itemView.findViewById(R.id.horizontal_variation);
horizontal_variation.setLayoutManager(new LinearLayoutManager(itemView.getContext(), LinearLayout.HORIZONTAL,false));
horizontal_variation.setHasFixedSize(true);
horizontal_variation.setItemAnimator(new DefaultItemAnimator());
// id = itemView.findViewById(R.id.variationId);
}
}
public class variationAdapter extends RecyclerView.Adapter<variationHolder> {
public List<variationModel> ListOf;
public variationAdapter(List<variationModel> listOf) {
ListOf = listOf;
}
@NonNull
@Override
public variationHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.portrait_variation, parent, false);
return new variationHolder(view);
}
@Override
public void onBindViewHolder(@NonNull variationHolder holder, int position) {
holder.name.setText(ListOf.get(position).getName());
horizontalAdapter adapter = new horizontalAdapter(this.ListOf.get(position).getData());
holder.horizontal_variation.setAdapter(adapter);
System.out.println("Rohit" + ListOf.get(position).getName());
}
@Override
public int getItemCount() {
return this.ListOf.size();
}
}
horizontalAdapter.java(水平適配器)
class horizontalHolder extends RecyclerView.ViewHolder{
public TextView name,price;
public MaterialCardView variationCard;
public horizontalHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.variationName);
variationCard = itemView.findViewById(R.id.variationCard);
price = itemView.findViewById(R.id.productPricePopUp);
}
static class ExecuteBack extends AsyncTask<String,String,String>{
String server_response;
Context context;
View v;
public ExecuteBack(Context context,View v) {
this.context = context;
this.v = v;
}
@Override
protected String doInBackground(String... url1) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(url1[0]);
urlConnection = (HttpURLConnection) url
.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
final JSONObject arr = new JSONObject(server_response);
return arr.getString("price");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view = inflater.inflate( R.layout.fragment_product, null );
TextView tv = view.findViewById(R.id.productPricePopUp);
tv.setText(s);
System.out.println("Rohit " + tv.getText());
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
}
}
public class horizontalAdapter extends RecyclerView.Adapter<horizontalHolder> {
private ArrayList<optionModel> ListOf;
public int temp;
horizontalAdapter(ArrayList<optionModel> listOf) {
ListOf = listOf;
}
@NonNull
@Override
public horizontalHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.variation_recycler, parent, false);
return new horizontalHolder(view);
}
@Override
public void onBindViewHolder(@NonNull final horizontalHolder holder, final int position) {
holder.name.setText(this.ListOf.get(position).getName());
holder.name.setTag(this.ListOf.get(position).getId());
if(temp ==position){
holder.variationCard.setCardBackgroundColor(Color.parseColor("#515C6F"));
holder.name.setTextColor(Color.parseColor("#FFFFFF"));
}else{
holder.variationCard.setCardBackgroundColor(Color.parseColor("#FFFFFF"));
holder.name.setTextColor(Color.parseColor("#515C6F"));
}
holder.variationCard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
temp = position;
new horizontalHolder.ExecuteBack(holder.itemView.getContext(),holder.itemView).execute("url");
notifyDataSetChanged();
}
});
}
@Override
public int getItemCount() {
return this.ListOf.size();
}
這是用戶界面的圖片
我相信您要更新的TextView在Fragment布局中。
假設那樣,我建議創建一個說UpdateTextCallback
的接口
public interface UpdateTextCallback {
public void updateText(String text);
}
將其實現為存在TextView
Fragment類。
public class Product extends SuperBottomSheetFragment, UpdateTextCallback {
...
..
.
class ExecuteOnBack extends AsyncTask<Void,Void,Void>{
..
.
@Override
protected Void doInBackground(Void... voids) {
...
..
.
adapter = new variationAdapter(data, Product.this);
variationRecycler.setAdapter(adapter);
...
..
.
}
}
...
..
.
public void updateText(String text) {
TextView tv = findViewById(R.id.productPricePopUp);
tv.setText(s);
System.out.println("Rohit " + tv.getText());
}
}
像這樣修改variantAdapter類的構造函數
public class variationAdapter extends RecyclerView.Adapter<variationHolder> {
public List<variationModel> ListOf;
private UpdateTextCallback updateTextCallback ;
public variationAdapter(List<variationModel> listOf, UpdateTextCallback updateTextCallback) {
ListOf = listOf;
this.updateTextCallback = updateTextCallback;
}
...
..
.
@Override
public void onBindViewHolder(@NonNull variationHolder holder, int position) {
holder.name.setText(ListOf.get(position).getName());
horizontalAdapter adapter = new horizontalAdapter(this.ListOf.get(position).getData(), updateTextCallback);
holder.horizontal_variation.setAdapter(adapter);
System.out.println("Rohit" + ListOf.get(position).getName());
}
...
..
.
}
修改horizontalAdapter類構造函數並像這樣更新文本
...
..
.
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
updateTextCallback.updateText(s);
}
...
..
.
public class horizontalAdapter extends RecyclerView.Adapter<horizontalHolder> {
private ArrayList<optionModel> ListOf;
public int temp;
private UpdateTextCallback updateTextCallback ;
horizontalAdapter(ArrayList<optionModel> listOf, UpdateTextCallback updateTextCallback) {
ListOf = listOf;
this.updateTextCallback = updateTextCallback;
}
...
..
.
}
即使TextView
不在Fragment布局中,我也希望您對如何從另一個類更新文本有個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.