заполнить просмотр списка фрагментом с помощью json rereiver php mysql - PullRequest
0 голосов
/ 19 июня 2019

Я довольно новичок во фрагментации, но мой код кажется мне достаточно логичным, но все равно он либо вылетает, либо не дает никакого результата. Я не представляю, что с ним не так, я загружаю файл json из phpAPI, который включает в себя рекламу "annances", анализирующую их и перечисляющую в виде списка внутри фрагмента, вот мой класс фрагмента и адаптер

, если кто-то может сослаться на код, из которого я могу узнать, или дать подсказку, откудая ошибся с этим, спасибо

public class MainFragment extends Fragment{

private String URLstring = "http://192.168.1.38/api/annonce/read.php";
private static ProgressDialog mProgressDialog;
private ListView lv;
ArrayList<DataModel> dataModelArrayList = new ArrayList<DataModel> ();
private ListAdapter1 listAdapter1;

public static MainFragment newInstance() {
    MainFragment fragment = new MainFragment();
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v=inflater.inflate(R.layout.main_fragment, container, false);


    lv  = v.findViewById(R.id.lv);

    new JsonTask().execute(URLstring); 
    return v;
}

private class JsonTask extends AsyncTask<String, String, String> {
    protected void onPreExecute() {

    }

    protected String doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line;
            String file_name="";
            while ((line = reader.readLine()) != null) {
                try {
                    JSONObject dataobj = new JSONObject(line);
                    DataModel playerModel = new DataModel();
                    playerModel.setPhoto_principale(dataobj.getString("Photo_principale"));
                    playerModel.setTitre_annonce(dataobj.getString("Titre_annonce"));
                    playerModel.setDescription(dataobj.getString("Description"));
                    playerModel.setQuartier(dataobj.getString("Quartier"));
                    dataModelArrayList.add(playerModel);
                }
                catch (Exception e){}
                buffer.append(line + "\n");
            }
            return buffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        setupListview();

    }



}

private void setupListview(){
    removeSimpleProgressDialog();  //will remove progress dialog
    listAdapter1 = new ListAdapter1(getActivity(),dataModelArrayList); // Here we talk about getActivity() because you are using Fragment not 
    //an actual activity so you call it getActivity()
    lv.setAdapter(listAdapter1);

}

public static void removeSimpleProgressDialog() {
    try {
        if (mProgressDialog != null) {
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }
        }
    } catch (IllegalArgumentException ie) {
        ie.printStackTrace();

    } catch (RuntimeException re) {
        re.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

}

Вот класс адаптера

public class ListAdapter1 extends BaseAdapter {

private Context context;
private ArrayList<DataModel> dataModelArrayList;
public ListAdapter1(Context context, ArrayList<DataModel> dataModelArrayList) {

    this.context = context;
    this.dataModelArrayList = dataModelArrayList;
}
@Override
public int getViewTypeCount() {
    return getCount();
}
@Override
public int getItemViewType(int position) {

    return position;
}

@Override
public int getCount() {
    return dataModelArrayList.size();
}

@Override
public Object getItem(int position) {
    return dataModelArrayList.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        holder = new ViewHolder();
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.item_list, null);

        holder.photo_principale = (ImageView) convertView.findViewById(R.id.image);
        holder.titre_annonce = (TextView) convertView.findViewById(R.id.titre_annonce);
        holder.description = (TextView) convertView.findViewById(R.id.description);
        holder.quartier = (TextView) convertView.findViewById(R.id.quartier);

        convertView.setTag(holder);
    }else {
        // the getTag returns the viewHolder object set as a tag to the view
        holder = (ViewHolder)convertView.getTag();
    }

    Picasso.get().load(dataModelArrayList.get(position).getPhoto_principale()).into(holder.photo_principale);
    holder.titre_annonce.setText(dataModelArrayList.get(position).getTitre_annonce());
    holder.description.setText(dataModelArrayList.get(position).getDescription());
    holder.quartier.setText(dataModelArrayList.get(position).getQuartier());

    return convertView;
}

private class ViewHolder {
    // changed protected to public
    public  TextView titre_annonce, description, quartier;
    public ImageView photo_principale;
}

1 Ответ

0 голосов
/ 19 июня 2019

Использовать библиотеку залпов для обработки JSON. Ознакомьтесь с этим ответом Как вы используете Android Volley API?

Другие ссылки

https://www.geeksforgeeks.org/volley-library-in-android/ https://developer.android.com/training/volley/index.html

Некоторые важные контрольные точки

  1. Проверка URL-адреса на компьютере
  2. Проверка подключения вашего телефона к локальному хосту, проверкаэта ссылка https://www.webucator.com/blog/2016/05/accessing-your-local-web-server-from-a-mobile-device-using-xampp/

Между тем

Создание экземпляра класса адаптера в методе onCreateView и передача соответствующих параметров

@ Переопределение общего представления onCreateView(LayoutInflater inflater, контейнер ViewGroup, Bundle saveInstanceState) {

View v=inflater.inflate(R.layout.main_fragment, container, false);


lv  = v.findViewById(R.id.lv);
//note this change
listAdapter1 = new ListAdapter1(getActivity(),dataModelArrayList);

new JsonTask().execute(URLstring); 
return v;

}

Но чтобы упростить вашу работу, просто используйте залп в следующий раз

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...