gpt4 book ai didi

java - 从适配器更新 fragment 的 TextView (asyncTask)

转载 作者:行者123 更新时间:2023-12-02 01:24:35 24 4
gpt4 key购买 nike

我在将文本设置为 Textview 时遇到了一点问题,请检查以下情况

所以,我有一个 fragment ,在 fragment 中我有产品名称、价格和两个 RecyclerView (1 个纵向,1 个水平),在项目上单击水平 RecyclerView,它将尝试获取价格那个特定的项目和服务器的响应我想将该值设置为 fragment 的价格TextView,但是当我显式更新值时它返回空指针,我尝试了下面的所有代码,但它们都不适合我.

  1. 在 fragment 中创建用于设置文本的方法,并从 AsyncTask 调用该方法(问题:UI 未加载,这就是抛出空指针的原因)

  2. 使用 Layoutinfleter

.

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?请帮我找到解决方案。

Horizontal RecyclerView is inside portrait RecyclerView (Nested)

Product.java( fragment )

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

variationAdapter.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();
}
}

horizo​​ntalAdapter.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();
}

这是ui的图片

enter image description here

最佳答案

我相信您尝试更新的 TextView 位于 Fragment 布局中。

假设,我会建议创建一个接口(interface),例如 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());
}

}

像这样修改variationAdapter类构造函数

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());
}
...
..
.
}

修改horizo​​ntalAdapter类构造函数并像这样更新文本

...
..
.
@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 布局中,我希望您已经了解如何从另一个类更新文本。

关于java - 从适配器更新 fragment 的 TextView (asyncTask),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57130874/

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