android Ошибка раздувания фрагмента класса

Я разработал одно приложение, в котором я должен отображать карту. Широта и долгота, которые я получил от API-веб-службы.

У меня есть один пользовательский базовый адаптер для отображения необработанного файла всех данных.

Мои остальные данные установлены очень хорошо.

Но когда я использовал фрагмент в своем необработанном файле, я получил ошибку.

в этой строке,

     vi = inflater.inflate(R.layout.raw_file, null);

также попробовать это:

      vi = inflater.inflate(R.layout.chat_raw_3, parent , true); 

or

      vi = inflater.inflate(R.layout.chat_raw_3, parent , false);

or

      vi = inflater.inflate(R.layout.chat_raw_3, null, false);

в методе getView(...).

в файле raw_file.xml я добавляю следующий фрагмент:

     <fragment
            android:id="@+id/map_sender"
            android:layout_width="150dp"
            android:layout_height="150dp"
            class="com.google.android.gms.maps.SupportMapFragment"
      />

Я получил следующую ошибку в logcat:

     android.view.InflateException: Binary XML file line #113: Error   inflating class fragment
        at   android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
     .
     .
     .
     Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.fragment" on path: DexPathList

Важно то, что он отлично работает с другой моей активностью (которая не использует надувание необработанного файла), но при использовании необработанного файла пользовательского адаптера выдает вышеуказанную ошибку.

Я ищу много вариантов в Интернете, но не нашел решения, поэтому, пожалуйста, помогите мне решить этот вопрос.

ИЗМЕНИТЬ

Моя вся структура класса, как показано ниже:

 public class My_Activity extends ListActivity {

  // all variable declaration here

   @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen);
    initialize();

  }

  private void initialize()
  {
        // all fields initialize here

        // set value to custom adapter
        new setAdapter().execute();

  }

  public class setAdapter extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();


    }

    @Override
    protected String doInBackground(String... params) {

        // other things
        return "yes";
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        try {
            adpt = new MyAdapter(getApplicationContext(), arr);
            setListAdapter(adpt);
            adpt.notifyDataSetChanged();
            getListView().setSelection(adpt.getCount() - 1);

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


    }
}
private class MyAdapter extends BaseAdapter implements LocationListener  {
 ArrayList<HashMap<String, String>> arr;
 HashMap<String, String> map;
 Context c;
 LayoutInflater inflater;
 private GoogleMap map_sender, map_reciver;
 double latitude;
 double longitude;

public MyAdapter(Context activity, ArrayList<HashMap<String, String>> arr) {

    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    c = activity;
    arr = arr;
}

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

@Override
public Object getItem(int position) {
    return null;
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)

   // I got error in following line ========== error below line =======
        vi = inflater.inflate(R.layout.raw_file, null);

    map_sender = ((MapFragment) getFragmentManager().findFragmentById(R.id.map_sender))
            .getMap();

    TextView tv_room_name = (TextView) vi.findViewById(R.id.tv_room_name);
    TextView tv_raw_date = (TextView) vi.findViewById(R.id.tv_raw_date);

    HashMap<String, String> product = new HashMap<String, String>();
    product = arr.get(position);


    String fiile_type_locations = product.get("file_type_location").toString();
    String file_beam_latitudes = product.get("file_latitude").toString();
    String file_beam_longitudes = product.get("file_longitude").toString();

    tv_room_name.setVisibility(View.VISIBLE);
    tv_room_name.setText("");

   if (!fiile_type_locations.equals("")) {

        // here i set map
    }
    return vi;
}

@Override
public void onLocationChanged(Location location) {

}

}

Мой raw_file.xml выглядит следующим образом:

  <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">


      <LinearLayout
    android:id="@+id/rl_raw_date"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:visibility="visible">

    <TextView
        android:id="@+id/tv_raw_date"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:gravity="center"
        android:text="Date" />

    <TextView
        android:id="@+id/tv_room_name"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_marginLeft="10dp"
        android:singleLine="true"
        android:text="senderName"
        android:textSize="14sp"
        android:visibility="gone" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/contentWithBackground_sender_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:orientation="vertical"
        android:paddingBottom="10dp"
        android:paddingRight="10dp"
        android:visibility="gone">

      <!-- binary xml file inflating following first line -->

       <fragment
            android:id="@+id/map_sender"
            android:layout_width="150dp"
            android:layout_height="150dp"
            class="com.google.android.gms.maps.MapFragment"
            />
       <!-- <fragment
            android:id="@+id/map_sender"
            class="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="150dp"
            android:layout_height="150dp" />-->

    </LinearLayout>
 </LinearLayout>

person Joseph Mekwan    schedule 17.09.2015    source источник
comment
вы включили библиотеку support-v4 или support-v7 в зависимость вашего проекта?   -  person Android Team    schedule 17.09.2015
comment
Здравствуйте, @AndroidWeblineindia Моя зависимость выглядит следующим образом: { compile fileTree (dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.0.0' compile 'com.google.android .gms:игровые сервисы:6.5.87' }   -  person Joseph Mekwan    schedule 17.09.2015
comment
он использовал com.android.support:appcompat-v7:22.0.0   -  person Joseph Mekwan    schedule 17.09.2015
comment
эй.. попробуй использовать adpt = new MyAdapter(My_Activity.this, arr); .   -  person SRB Bans    schedule 19.09.2015
comment
привет @sourabhbans это не работает .. та же ошибка   -  person Joseph Mekwan    schedule 19.09.2015


Ответы (2)


У вас есть два альтернативных решения этого вопроса:

Первое альтернативное решение: используйте Imageview вместо фрагмента и установите URL-адрес статической карты для этого изображения. Это лучший способ, а также не сильно нагружать.

Второе решение: используйте MapView вместо фрагмента.

Описание первого решения:

Используйте статический URL-адрес карты, чтобы показать статическую автономную карту для просмотра изображения.

 url = "http://maps.google.com/maps/api/staticmap?center=" + Latitude + "," + Longitude + "&zoom=15&size=200x200&sensor=false"

Используйте Imageview в вашем raw_file вместо фрагмента, например

   <ImageView
            android:id="@+id/your_imageview"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:maxWidth="250dp"
            android:src="@drawable/ic_launcher"
            android:textColor="@android:color/white"
            android:visibility="visible" />

И используйте в java-файле с помощью ImageLoader:

1)  ImageLoader imageLoader;
2)  imageLoader = new ImageLoader(Your_Activity.this);
3)  imageLoader.DisplayImage("http://maps.google.com/maps/api/staticmap?center=" + Latitide + "," + Longitude + "&zoom=15&size=200x200&sensor=false", your_imageview);

Просто все закончилось :)

Описание второго способа:

Используйте Mapview вместо фрагмента в вашем raw_file

как следующее:

 <com.google.android.gms.maps.MapView
            android:id="@+id/mapview"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:visibility="gone"/>

И в вашем java-файле:

1)  MapView mapView;
    GoogleMap map

2)  mapView = (MapView) vi.findViewById(R.id.mapview);

3)   mapview_receiver.onCreate(savedInstanceState);

                // Gets to GoogleMap from the MapView and does initialization stuff
                map_recive = mapview_receiver.getMap();
                map_recive.getUiSettings().setMyLocationButtonEnabled(false);
                map_recive.setMyLocationEnabled(true);

                // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
                try {
                    MapsInitializer.initialize(Chat_Screen_Activity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                map_recive.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 3));
                // Zoom in, animating the camera.
                map_recive.animateCamera(CameraUpdateFactory.zoomTo(6), 100, null);

Хорошо, ваша работа сделана!!!

Но лучше всего сравнивать оба URL-адреса первого изображения (статическая автономная карта), после нажатия на которые вы также отображаете карту в другом действии.

Он не загружается, когда вы прокручиваете свой список и отображаете его с такой же скоростью без загрузки, так что это лучший способ.

person Nirav Mehta    schedule 22.09.2015
comment
первый... лучший... :) - person Joseph Mekwan; 23.09.2015

Использовать

map_sender = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_sender)).getMap();

активность в частном контексте; // Глобально Тогда

public MyAdapter(Context activity, ArrayList<HashMap<String, String>> arr) {


    this.activity = activity;
    arr = arr;
}

Отредактированный ответ

Затем передайте LayoutInflater

 LayoutInflater inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

if(convertView == null){
     convertView = inflater.from(activity).inflate(R.layout.raw_file, null);
person IntelliJ Amiya    schedule 17.09.2015
comment
@JosephMekwan Я думаю, вы добавили карту во фрагмент? - person IntelliJ Amiya; 17.09.2015
comment
В настоящее время весь остальной код в комментарии просто открывает ‹фрагмент... /› и прямая ошибка переходит в эту строку... начало ‹фрагмента.. - person Joseph Mekwan; 17.09.2015
comment
@JosephMekwan Хорошо. Можете ли вы опубликовать свой код в формате xml? - person IntelliJ Amiya; 17.09.2015
comment
Удалить inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); из конструктора - person IntelliJ Amiya; 17.09.2015
comment
при сбое набора (SupportMapFragment) getSupportFragmentManager() - person IntelliJ Amiya; 17.09.2015
comment
stackoverflow.com/questions/16967328/ - person IntelliJ Amiya; 17.09.2015
comment
все равно падает на той же строке... :( - person Joseph Mekwan; 17.09.2015
comment
@JosephMekwan хорошо. Я проверю свой код. Имейте терпение - person IntelliJ Amiya; 17.09.2015
comment
Вы расширили FragmentActivity в своем родительском классе? - person IntelliJ Amiya; 17.09.2015
comment
Здравствуйте, родительский класс @IntelliJ Amiya, расширяющий ListActivity - person Joseph Mekwan; 17.09.2015
comment
Давайте продолжим обсуждение в чате. - person Joseph Mekwan; 17.09.2015
comment
from(context).inflate(R.layout.your_layout, это, правда); - person IntelliJ Amiya; 18.09.2015