Я не могу установить текст (читать из папки с активами) в мой список

В моем приложении я хочу прочитать мой текст из ресурса. Теперь у меня есть текст в папке с активами, и я думаю, что моя проблема в том, что я не могу установить свой текст в свой список. Перед этим я читаю свой текст из массива, но когда я изменяю его, у меня есть исключения. Как я могу прочитать мой из актива?

вот мой код:

 public class ProductListFragment extends Fragment implements 
 SearchView.OnQueryTextListener {

 public static final String ARG_ITEM_ID = "product_list";
 ArrayList<String> dataItems = new ArrayList<String>();
 static Activity activity;
 ListView productListView;
 InputStream in;
 BufferedReader reader;
 Context context;
 String line = "1";
List<Product> products;
ProductListAdapter productListAdapter;
SearchView search_view;
SharedPreference sharedPreference;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = getActivity();
    sharedPreference = new SharedPreference();

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_product_list, container,
            false);
    findViewsById(view);
    search_view = (SearchView) view.findViewById(R.id.search_view);



    productListAdapter = new ProductListAdapter(activity, products);
    productListView.setAdapter(productListAdapter);
    ReadText();
    for (int i = 0; i < 100; i++) {

        Product wp = new Product(dataItems.get(i));
        products.add(wp);
    }

    search_view.setOnQueryTextListener(this);

    return view;
}


private void findViewsById(View view) {
    productListView = (ListView) view.findViewById(R.id.list_product);
}

@Override
public void onResume() {
    getActivity().setTitle(R.string.app_name);
    //getActivity().getActionBar().setTitle(R.string.app_name);
    super.onResume();
}


@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    productListAdapter.getFilter().filter(newText);
    return false;
}

public static class ProductListAdapter extends ArrayAdapter<Product> implements Filterable {

    private Context context;
    List<Product> products;
    SharedPreference sharedPreference;
    List<Product> mStringFilterList;
    ValueFilter valueFilter;


    public ProductListAdapter(Context context, List<Product> products) {
        super(context, R.layout.product_list_item, products);

        this.context = context;
        this.products = products;
        sharedPreference = new SharedPreference();
        mStringFilterList = products;
    }

    private class ViewHolder {
        TextView productNameTxt;
        ImageView favoriteImg;
        ImageButton share;
    }

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

    @Override
    public Product getItem(int position) {
        return products.get(position);
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.product_list_item, null);
            holder = new ViewHolder();
            holder.productNameTxt = (TextView) convertView
                    .findViewById(R.id.txt_pdt_name);
            holder.share = (ImageButton) convertView.findViewById(R.id.share);
            holder.favoriteImg = (ImageView) convertView
                    .findViewById(R.id.imgbtn_favorite);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Product product = (Product) getItem(position);
        holder.productNameTxt.setText(PersianReshape.reshape(product.getName()));
        holder.productNameTxt.setTypeface(G.defaultFont);
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                String shareBody = products.get(position).toString();

                sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
                context.startActivity(Intent.createChooser(sharingIntent, "Share via"));
            }
        });
        holder.favoriteImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);

                String tag = button.getTag().toString();
                if (tag.equalsIgnoreCase("grey")) {
                    sharedPreference.addFavorite(activity, products.get(position));
                    Toast.makeText(activity,
                            activity.getResources().getString(R.string.add_favr),
                            Toast.LENGTH_SHORT).show();

                    button.setTag("red");
                    button.setImageResource(R.drawable.heart_red);
                } else {
                    sharedPreference.removeFavorite(activity, products.get(position));
                    button.setTag("grey");
                    button.setImageResource(R.drawable.heart_grey);
                    Toast.makeText(activity,
                            activity.getResources().getString(R.string.remove_favr),
                            Toast.LENGTH_SHORT).show();
                }

                //    return true;
            }
        });
    /*If a product exists in shared preferences then set heart_red drawable
     * and set a tag*/
        if (checkFavoriteItem(product)) {
            holder.favoriteImg.setImageResource(R.drawable.heart_red);
            holder.favoriteImg.setTag("red");
        } else {
            holder.favoriteImg.setImageResource(R.drawable.heart_grey);
            holder.favoriteImg.setTag("grey");
        }

        return convertView;
    }


    public boolean checkFavoriteItem(Product checkProduct) {
        boolean check = false;
        List<Product> favorites = sharedPreference.getFavorites(context);
        if (favorites != null) {
            for (Product product : favorites) {
                if (product.equals(checkProduct)) {
                    check = true;
                    break;
                }
            }
        }
        return check;
    }

    @Override
    public void add(Product product) {
        super.add(product);
        products.add(product);
        notifyDataSetChanged();
    }

    @Override
    public void remove(Product product) {
        super.remove(product);
        products.remove(product);
        notifyDataSetChanged();
    }

    public Filter getFilter() {
        if (valueFilter == null) {
            valueFilter = new ValueFilter();
        }
        return valueFilter;
    }

    private class ValueFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                ArrayList<Product> filterList = new ArrayList<Product>();


                for (int i = 0; i < mStringFilterList.size(); i++) {
                    //  if ( (mStringFilterList.get(i).getName().toUpperCase() )
                    //  .contains(constraint.toString().toUpperCase())) {
                    if ((mStringFilterList.get(i).getName()).contains(constraint.toString())) {
                        Product product = new Product(mStringFilterList.get(i)
                                .getId(), mStringFilterList.get(i)
                                .getName());

                        filterList.add(product);
                    }
                }
                results.count = filterList.size();
                results.values = filterList;
            } else {
                results.count = mStringFilterList.size();
                results.values = mStringFilterList;
            }
            return results;

        }

        @Override
        protected void publishResults(CharSequence constraint,
                                      Filter.FilterResults results) {
            products = (List<Product>) results.values;
            notifyDataSetChanged();
        }

    }
}

and here my text read line by line:
   private void ReadText() {
    try {
        in = this.context.getAssets().open("text.txt");
        reader = new BufferedReader(new InputStreamReader(in));
        while (line != null) {
            line = reader.readLine();
            if (line != null)
                dataItems.add(line);
            else
                break;
        }

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

1 ответ

Поместите ваш текстовый файл в каталог /assets под проектом Android. Используйте класс AssetManager для доступа к нему.

AssetManager am = context.getAssets();
InputStream is = am.open("text.txt");

Другой пример:

 private String readTxt(){

     InputStream inputStream = getResources().openRawResource(R.raw.toc);
//     InputStream inputStream = getResources().openRawResource(R.raw.internals);
     System.out.println(inputStream);
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

     int i;
  try {
   i = inputStream.read();
   while (i != -1)
      {
       byteArrayOutputStream.write(i);
       i = inputStream.read();
      }
      inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

     return byteArrayOutputStream.toString();
    }
}

Узнайте больше на:

/questions/2799063/chtenie-prostogo-tekstovogo-fajla/2799087#2799087

Другие вопросы по тегам