Android: переработчик просмотра адаптер - PullRequest
0 голосов
/ 16 октября 2018

Я новичок в виджете представления переработчика, я хочу получить свои данные из URL-адреса API и вывести список данных в представление переработчика, у меня есть следующие классы: recyclerAdapter, recyclerView, MainActivity, row.

данные загружаются из API успешно, но не устанавливает строку json, полученную из API, в представлении переработчика, а представление переработчика отображается белым и пустым.любое тело может найти проблему в моем коде?

MainActivity.java код:

public class MainActivity extends AppCompatActivity {
    final String member_id = "2";
    final String get_cash_url = "http://famila1.ir/khabgah/get_khabgah_cash.php?member_id=" + member_id;

    private RecyclerView rc;
    private RecyclerView.Adapter adapter;
    private List<recyclerView> cashList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rc = findViewById(R.id.rc);
        rc.setHasFixedSize(true);
        rc.setLayoutManager(new LinearLayoutManager(this));
        cashList = new ArrayList<>();
        loadUrlData();

    }

    private void loadUrlData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                get_cash_url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println(response);
                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("bedehkariHa");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jo = array.getJSONObject(i);
                        recyclerView temp = new recyclerView(jo.getString("hazine"), jo.getString("tarikh"), jo.getString("tozihat"), jo.getString("member_id"), "kir");
                        cashList.add(temp);
                    }
                    adapter = new recyclerAdapter(cashList, getApplicationContext());
                    rc.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                progressDialog.setMessage("somthing was wrong during runnig app...");
                progressDialog.show();
                System.out.println("error: "+error);
            }
        }
        );
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }
}

recyclerView.java код:

public class recyclerView {
private String hazine,tarikh,tozihat,madarkharj,harSahm;
public recyclerView(String hazine,String tarikh,String tozihat,String madarkharj,String harSahm ) {
    this.hazine = hazine;
    this.harSahm = harSahm;
    this.madarkharj = madarkharj;
    this.tarikh = tarikh;
    this.tozihat = tozihat;
}
public String getHazine(){return hazine;}
public String getTarikh(){return tarikh;}
public String getTozihat(){return tozihat;}
public String getMadarkharj(){return madarkharj;}
public String getHarSahm(){return harSahm;}

}

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

public static final String KEY_NAME = "name";
public static final String KEY_LASTNAME = "lastname";
public static final String KEY_IMAGE = "image";
public static final String KEY_HAZINE = "hazine";
public static final String KEY_TARIKH = "date";
public static final String KEY_MADARKHARJ = "member_id";

private List<recyclerView> cashlist;
private Context context;

Класс адаптера Recycler такой:

public recyclerAdapter(List<recyclerView> cashlist, Context context){
    this.cashlist = cashlist;
    this.context = context;

}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.row,viewGroup,false);

    return new recyclerAdapter.ViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {
    final recyclerView recyclerviews = cashlist.get(position);
    viewHolder.hazine.setText(recyclerviews.getHazine());
    viewHolder.harSahm.setText(recyclerviews.getHarSahm());
    viewHolder.tarikh.setText(recyclerviews.getTarikh());
    viewHolder.tozihat.setText(recyclerviews.getTozihat());

    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context, "TEST is Toasted", Toast.LENGTH_SHORT).show();
        }
    });

}

@Override
public int getItemCount() {
    return cashlist.size();
}

// Внутри этого класса у нас будет другой класс для ViewHolder, таким образом

public class ViewHolder extends RecyclerView.ViewHolder{

    TextView hazine,harSahm,tozihat,tarikh;


    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        hazine = (TextView) itemView.findViewById(R.id.mablaq_hazine);
        harSahm = (TextView) itemView.findViewById(R.id.bedehkariha_dong);
        tarikh = (TextView) itemView.findViewById(R.id.tarikh_hazine);
        tozihat = (TextView) itemView.findViewById(R.id.babate_hazine);
    }
}

}

и это row.xml:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" android:background="@android:color/white" >

    <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:padding="5dp"
                android:background="@android:color/holo_blue_bright" android:layout_marginBottom="5dp"
        >
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:padding="3dp"
                    android:background="@android:color/holo_blue_dark">
                <TextView
                        android:text="سهم شما:"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/tarikh_hazine2"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"
                />
                <TextView
                        android:text="قالب پرداخت"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/bedehkariha_dong"
                        android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"/>
                <TextView
                        android:text="مبلغ کل: "
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/mablaq_hazine2"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"/>
                <TextView
                        android:text="مبلغ کل"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/mablaq_hazine" android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"/>
            </LinearLayout>
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:padding="3dp"
                    android:background="@android:color/holo_blue_dark">
                <TextView
                        android:text="تاریخ:"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/tarikh_hazine22"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"
                />
                <TextView
                        android:text="تاریخ"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/tarikh_hazine" android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"
                        android:inputType="textMultiLine"
                />
            </LinearLayout>
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:padding="3dp"
                    android:background="@android:color/holo_blue_dark">
                <TextView
                        android:text="توضیحات: "
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/babate_hazine2"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"
                />
                <TextView
                        android:text="هزینه بابت......"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/babate_hazine" android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"
                        android:inputType="textMultiLine"
                        android:gravity="right"/>
            </LinearLayout>
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:layout_marginTop="2dp">
                <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" android:layout_weight="1" android:padding="2dp">
                    <TextView
                            android:text="پرداخت از: "
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none"
                            android:background="@android:color/white" android:gravity="center"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz1" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FF75AD06" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz2" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_green_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz3" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FF75AD06" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz4" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_green_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz5" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#75ad06" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz6" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_green_dark" android:padding="2dp"
                    />
                </LinearLayout>
                <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" android:layout_weight="1" android:padding="2dp">
                    <TextView
                            android:text="هزینه شریکی با:"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none"
                            android:background="@android:color/white" android:gravity="center"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba1"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FFF10D0D" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba2"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_red_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba3"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FFF10D0D" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba4"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_red_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba5"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FFF10D0D" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba6"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_red_dark" android:padding="2dp"
                    />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

Ответы [ 3 ]

0 голосов
/ 16 октября 2018

Согласно результату JSON, ключ bedehkariHa не существует, и это может вызвать ошибку синтаксического анализа, JSONException.Поэтому вместо этого:

 JSONArray array = jsonObject.getJSONArray("bedehkariHa");

используйте это, чтобы получить JSONArray, связанный с bedehkari_ha :

 JSONArray array = jsonObject.getJSONArray("bedehkari_ha");
0 голосов
/ 16 октября 2018

Я бы сначала посмотрел на ваш общий подход.Кажется, вы создаете запрос Volley ... Держу пари, что он не единственный в вашем приложении?

Сделать "NetworkService" singleton , который содержит контекст приложения, и вызвать его какслой обслуживания ... вместо того, чтобы вызывать новый экземпляр Volley для каждого класса, который вам нужен!

Вот один, который я написал для своих приложений ... Я опустил много методов и оставил вам сМетод GetRequest.Вы можете добавить URLEncoding для параметров в сервисе.

Вы можете вызвать это просто в активности / фрагменте:

 HashMap<String,String> urlParams = new HashMap<>();
        urlParams.put("param1","value1");

        VolleyRequestService.getInstance(this).getJSONObject(urlParams, true, new GetJSONObjectRequestable() {
            @Override
            public void onSuccessfulAPIResponse(JSONObject response) {

            }

            @Override
            public void onFailedAPIResponse(VolleyRequestService.ErrorType errorType, String description) {

            }
        },"https://myendpoint.com/endpoint.php");

И в сервисе:

package devdroidjonno.com.tests.Networking;

import android.content.Context;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class VolleyRequestService {
    private static final String DEBUG = "VolleyRequestService";
    private static final String authCode = "87fe987vwefb987eb9w87wv";
    private static VolleyRequestService ourInstance = null;
    private static RequestQueue requestQueue;

    private VolleyRequestService(Context applicationContext) {
        this.requestQueue = Volley.newRequestQueue(applicationContext);
        Log.d(DEBUG, "Init Volley Service " + this.hashCode());
    }

    public static VolleyRequestService getInstance(Context context) {
        if (ourInstance == null) {
            ourInstance = new VolleyRequestService(context.getApplicationContext());
        }
        return ourInstance;
    }

    // A GET request to an endpoint that returns a JSONObject. 
    public void getJSONObject(HashMap<String, String> urlParams, final boolean requiresAuthHeader, final GetJSONObjectRequestable callback, String endpointURL) {
        endpointURL += "?";
        for (Map.Entry mapEntry : urlParams.entrySet()) {
            endpointURL += mapEntry.getKey() + "=" + mapEntry.getValue() + "&";
        }
        Log.d(DEBUG, endpointURL);
        requestQueue.add(new JsonObjectRequest(Request.Method.GET, endpointURL, null, response -> {
            Log.d(DEBUG, response.toString());
            try {
                if (response.has("error")) {
                    callback.onFailedAPIResponse(ErrorType.APIERROR, response.getString("error"));
                } else {
                    callback.onSuccessfulAPIResponse(response);
                }
            } catch (Exception e) {
                callback.onFailedAPIResponse(ErrorType.EXCEPTION, e.getLocalizedMessage());
                e.printStackTrace();
            }
        }, error -> callback.onFailedAPIResponse(ErrorType.VOLLEYERROR, error.getMessage())) {
            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                if (requiresAuthHeader) headers.put("Authorization", authCode);
                return headers;
            }
        });
    }

    public enum ErrorType {
        NOERROR, APIERROR, VOLLEYERROR, AUTHERROR, EXCEPTION
    }

}

И, наконец, обратный звонок ...

package devdroidjonno.com.tests.Networking;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;


public interface GetJSONObjectRequestable {
    void onSuccessfulAPIResponse(JSONObject response) throws JSONException, IOException;

    void onFailedAPIResponse(VolleyRequestService.ErrorType errorType, String description);
}
0 голосов
/ 16 октября 2018

Проблема синтаксического анализа сначала я получил. Изменить

 JSONArray array = jsonObject.getJSONArray("bedehkariHa");

Кому:

 JSONArray array = jsonObject.getJSONArray("bedehkari_ha");

Затем проверить

...