I'm developing an Android app using Google Sheets as a database.
I have information about books in a Google Sheet (title, author, cover, date, etc). I want to retrieve this information and show it in a "Listview" in the "Spreadsheets" Activity. I created a "BookItem" object and an "BookAdapter" adapter. In the "Spreadsheets.java" I have the read method, called "getDataFromApi()". I know that this method works, but I don't know how to adapt it to my "BookAdapter" and show the information on the ListView.
This is mi code:
public class BookItem {
static String title_item;
static Drawable cover_item; //probar con String
public BookItem(String title, Drawable cover){
super();
this.title_item = title;
this.cover_item = cover;
}
public String getTitle() {
return title_item;
}
public void setTitle(String title){
this.title_item = title;
}
public static Drawable getCover() {
return cover_item;
}
public void setCover(Drawable cover) {
this.cover_item = cover;}
This is my BookAdapter:
public class BookAdapter extends BaseAdapter {
private ArrayList<BookItem> items;
List<BookItem> items;
private Context context;
public BookAdapter (Context context, List<BookItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public BookItem getItem(int position) {
return this.items.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
private static class ViewHolder {
public final ImageView cover_item;
public final TextView title_item;
public ViewHolder (ImageView cover_item, TextView title_item){
this.cover_item = cover_item;
this.title_item = title_item;
}
}
#Override
public View getView (int position, View view, ViewGroup viewGroup) {
ImageView cover_item;
TextView title_item;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.fila_lista_miestanteria, viewGroup, false); //se mete aqui en getView por ser baseAdapter
title_item = (TextView) view.findViewById(R.id.book_title_item);
cover_item = (ImageView) view.findViewById(R.id.book_cover_item);
view.setTag(R.id.book_title_item, title_item);
view.setTag(R.id.book_cover_item, cover_item);
}
else {
cover_item = (ImageView) view.getTag(R.id.book_cover_item);
title_item = (TextView)view.getTag(R.id.book_title_item);
}
BookItem bookItem = getItem(position);
cover_item.setImageDrawable(bookItem.getCover());
title_item.setText(bookItem.getTitle());
return view;
}
}
public class Spreadsheets extends Activity {
static String book_title, book_author, book_date, book_category, book_description, book_rating, book_cover;
static String read_only = "no";
static String book_favorite = "no";
static GoogleAccountCredential mCredential;
private ListView bookList;
private TextView mOutputText;
ProgressDialog mProgress;
Context context;
List<String> rst;
List<BookItem> resultados;
BookAdapter adapter;
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spread);
// mOutputText = (TextView) findViewById(R.id.outputText);
bookList = (ListView) findViewById(R.id.bookList);
// mOutputText.setText("");
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Google Sheets...");
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
System.out.print("read only es igual a "+ read_only);
new MakeRequestTask(mCredential).execute();
}
public void rellenar(){
System.out.println("VOY A HACER NEW BOOK ADAPTER ");
adapter = new BookAdapter(context, resultados);
bookList.setAdapter(adapter);
System.out.println("SETADAPTER");
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
}
#Override
protected List<String> doInBackground(Void... params) {
try {
if(read_only.equals("no")) {
setDataToApi();
return null;
}
else {
return getDataFromApi();
}
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private List<String> getDataFromApi() throws IOException {
String range = "Sheet1!A1:H";
List<String> results = new ArrayList<String>();
ValueRange response = CreateSpreadsheets.mService.spreadsheets().values()
.get(CreateSpreadsheets.spreadsheet_id, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
for (List row : values) {
results.add(row.get(0) + ", " + row.get(7));
}
}
//funcion();
return results;
}
private void setDataToApi() throws IOException {
String range = "Sheet1!A2:H";
List<List<Object>> values = new ArrayList<>();
List<Object> data1 = new ArrayList<>();
data1.add(book_title);
data1.add(book_author);
data1.add(book_date);
data1.add(book_category);
data1.add(book_description);
data1.add(book_rating);
data1.add(book_cover);
data1.add("a");
values.add(data1);
ValueRange valueRange = new ValueRange();
valueRange.setMajorDimension("ROWS");
valueRange.setRange(range);
valueRange.setValues(values);
ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse response =
CreateSpreadsheets.mService.spreadsheets().values().append(CreateSpreadsheets.spreadsheet_id, range, body)
.setValueInputOption("RAW")
.execute();
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
// mOutputText.setText("No results returned.");
} else {
if(read_only.equals("no")) {
Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
startActivity(intent);
// mOutputText.setText("Se ha añadido un libro a su lista");
}
else {
System.out.println("VOY A RELLENAR LA LISTA");
rellenar();
}
}
}
#Override
protected void onCancelled() {
}
}
}
The "spread.xml" is a list, and the "fila_list_miestanteria.xml" is a TextView&ImageView to show the book info.
Thank you so much!
Related
I am trying to make a news app, data obtained from RSS feed. I get xml response from the feed. And I am using XmlPullParser to parse the xml. The parsing is a success. I can see the values in my log.
But somehow I am not able to fill them in my recyclerView. It's all just blank. My java class is:
public class RssNewsActivity extends AppCompatActivity {
private static final String TAG = RssNewsActivity.class.toString();
RssFeedAdapter adapter;
RecyclerView recyclerView_rssFeed;
SwipeRefreshLayout swipeRefreshLayout;
private List<RssModel> listResponseModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_news);
initialize();
recyclerView_rssFeed.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView_rssFeed.setLayoutManager(linearLayoutManager);
adapter = new RssFeedAdapter(RssNewsActivity.this, listResponseModel);
recyclerView_rssFeed.setAdapter(adapter);
fetchNewsFeed();
//if user swipes the recycler then refresh content page
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
fetchNewsFeed();
}
});
}
private void initialize() {
swipeRefreshLayout = findViewById(R.id.swipeRefresh_rssFeed);
recyclerView_rssFeed = findViewById(R.id.recyclerView_rssFeed);
listResponseModel = new ArrayList<>();
}
private void fetchNewsFeed() {
String url = "here is my news feed url";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
listResponseModel.clear();
try {
listResponseModel = parseNewsFeed(response);
} catch (XmlPullParserException | IOException e) {
Log.e(TAG, e.getMessage());
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
private List<RssModel> parseNewsFeed(String response) throws XmlPullParserException,
IOException {
XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
parserFactory.setNamespaceAware(true);
XmlPullParser xmlPullParser = parserFactory.newPullParser();
xmlPullParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
xmlPullParser.setInput(new StringReader(response));
return processParsing(xmlPullParser);
}
private List<RssModel> processParsing(XmlPullParser xmlPullParser) throws IOException, XmlPullParserException {
List<RssModel> listRssFeed = new ArrayList<>();
int eventType = xmlPullParser.getEventType();
RssModel rssModel = null;
xmlPullParser.nextTag();
while (eventType != XmlPullParser.END_DOCUMENT) {
String eltName;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
eltName = xmlPullParser.getName();
if ("item".equals(eltName)) {
rssModel = new RssModel();
} else if (rssModel != null) {
if ("title".equals(eltName)) {
String title = xmlPullParser.nextText();
rssModel.setTitle(title);
Log.d(TAG, "title: " + title);
} else if ("link".equals(eltName)) {
String link = xmlPullParser.nextText();
rssModel.setLink(link);
Log.d(TAG, "link: " + link);
}
}
break;
case XmlPullParser.END_TAG:
eltName = xmlPullParser.getName();
if ("item".equals(eltName) && rssModel != null) {
listRssFeed.add(rssModel);
}
break;
}
eventType = xmlPullParser.next();
}
return listRssFeed;
}
}
my xml design is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="rssnewsfeed.RssNewsActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeRefresh_rssFeed"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView_rssFeed"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
This is my adapter class
public class RssFeedAdapter extends RecyclerView.Adapter<RssFeedAdapter.RssViewHolder> {
private Context mContext;
private List<RssModel> mRssFeeds;
public RssFeedAdapter(Context mContext, List<RssModel> mRssFeeds) {
this.mContext = mContext;
this.mRssFeeds = mRssFeeds;
}
#NonNull
#Override
public RssViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.rss_feed_layout, viewGroup, false);
return new RssViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull RssViewHolder rssViewHolder, int i) {
RssModel post = mRssFeeds.get(i);
rssViewHolder.textView_title.setText(post.getTitle());
rssViewHolder.textView_link.setText(post.getLink());
}
#Override
public int getItemCount() {
return mRssFeeds.size();
}
public class RssViewHolder extends RecyclerView.ViewHolder {
private TextView textView_title, textView_link;
public RssViewHolder(#NonNull View itemView) {
super(itemView);
textView_title = itemView.findViewById(R.id.textView_title);
textView_link = itemView.findViewById(R.id.textView_link);
}
}
}
And finally this is my model class:
public class RssModel {
private String title;
private String link;
public RssModel() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
I tried many ways but no success. I don't know what I am missing. I will be grateful for any guidance. Thanks.
Giving " = " will create a new instance of ArrayList apart from which is already binded to RecyclerView adapter.
So, you need to change this,
listResponseModel = parseNewsFeed(response);
to
listResponseModel.addAll(parseNewsFeed(response));
This happens because the Rss list which you're passing to recycler view adapter is null as you mentioned earlier you're successfully getting the values in log so another guaranteed workaround is to set the values into an separate arraylist.
So inside your class simply create arraylist:
private ArrayList<String> title;
private ArrayList<String> post;
This will be your initialize method:
private void initialize()
{
swipeRefreshLayout = findViewById(R.id.swipeRefresh_rssFeed);
recyclerView_rssFeed = findViewById(R.id.recyclerView_rssFeed);
title = new ArrayList<>();
post = new ArrayList<>();
}
Now simply pass your values to arraylist:
title.add(title)
post.add(post)
Now pass those arraylist to adapter:
adapter = new RssFeedAdapter(RssNewsActivity.this, title,post);
recyclerView_rssFeed.setAdapter(adapter);
After this initialize arraylist in adapter and fetch your values!
One more Important thing inside your oncreate() place your fetchNewsFeed(); method before initializing the adapter
initialize();
fetchNewsFeed();
recyclerView_rssFeed.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView_rssFeed.setLayoutManager(linearLayoutManager);
adapter = new RssFeedAdapter(RssNewsActivity.this, listResponseModel);
recyclerView_rssFeed.setAdapter(adapter);
I have create the recycerview and this recycerview display the Person image ,person name and + button when i have press + button change the button image like true.and after recycerview bottom one button this button click all data show the next activity..
My Adapter
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
public BuildCustomAdapter(List<People> buildList) {
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.isSelected());
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// public ImageView ivPeopleImage;
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
}
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
People people = peopleList.get(mPosition);
people.setSelected(!people.isSelected());
notifyDataSetChanged();
}
}
Activity
public class BulidActivity extends AppCompatActivity {
private List<People> peopleList = new ArrayList<>();
private List<People> peopleListCopy = new ArrayList<>();
private RecyclerView recyclerView;
private BuildCustomAdapter buildCustomAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bulid);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BuildData();
peopleListCopy.addAll(peopleList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
AddTxt();
BtnBuildNow();
}
private void BtnBuildNow() {
Button btnnuildnow = (Button) findViewById(R.id.btn_build_now);
btnnuildnow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BulidActivity.this, AlertList.class);
startActivity(intent);
}
});
}
private void AddTxt() {
EditText editTxt = (EditText) findViewById(R.id.etSearch);
editTxt.setTextColor(Color.WHITE);
editTxt.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.setFocusable(true);
v.setFocusableInTouchMode(true);
return false;
}
});
editTxt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() <= 0) {
peopleList.clear();
peopleList.addAll(peopleListCopy);
recyclerView.setAdapter(null);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
recyclerView.setAdapter(buildCustomAdapter);
} else {
buildCustomAdapter.getFilter().filter(s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<People> BuildData() {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
if (db.open()) {
peopleList = db.getPeople();
}
return peopleList;
}
Model class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private boolean selected;
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
DatabaseHelper.class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/databasename/databases/";
private static final String DB_NAME = "alertme.db";
private final String TABLE_PEOPLE = "people";
private final String TABLE_CATEGORY = "category";
private final String CATEGORY_NAME = "name";
private final String ID = "id";
private final String CATEGORY_ID = "category_id";
private final String PEOPLE_IMAGE = "image";
private final String PEOPLE_NAME = "name";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch (SQLException sqle) {
myDataBase = null;
return false;
}
}
public List<People> getPeople(String category_id) {
List<People> peoples = new ArrayList<>();
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery("select * from people where category_id = " + category_id, null);
while (cursor.moveToNext()) {
String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));
String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
People people = new People();
people.setPeopleName(peopleName);
people.setPeopleImage(peopleImage);
peoples.add(people);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return peoples;
}
public List<Category> getCategory() {
List<Category> categoryList = new ArrayList<>();
try {
String query = " SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int categoryID = cursor.getInt(cursor.getColumnIndex(ID));
String categoryName = cursor.getString(cursor.getColumnIndex(CATEGORY_NAME));
Category category = new Category();
category.setId(categoryID);
category.setCategoryName(categoryName);
categoryList.add(category);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return categoryList;
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
First you should implement Serializable interface in your Build model class like this :-
public class Build implements Serializable{
//Content will be as it is
}
Change your clickListener like this :-
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("build",build);
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
In the onCreate method of receiving activity write this :-
Build build = (Build) getIntent().getSerializableExtra("build");
Add Intent in below Method,
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("key","value");
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
Huge mistak that you register to the click event on your ViewHolder! you will get diffrent position from the actual because when android use notifyItemMoved the viewBindHolder will not be called and than you got the wrong position.
and in the click listener implementation you should pass Intent with your data
I want show image into RecyclerView and i should use this images from drawable folder. I write below codes, but show me this error :
java.lang.IllegalArgumentException: Unknown type class [I. You must provide a Model of a type for which there is a registered ModelLoader, if you are using a custom model, you must first call Glide#register with a ModelLoaderFactory for your custom model class
at com.bumptech.glide.RequestManager.loadGeneric(RequestManager.java:629)
at com.bumptech.glide.RequestManager.load(RequestManager.java:598)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:66)
at com.tellfa.colony.Adapters.ColoniesAdapter.onBindViewHolder(ColoniesAdapter.java:29)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5768)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5801)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5037)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4913)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3260)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3069)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3518)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1705)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1559)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1468)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15631)
at android.view.ViewGroup.layout(ViewGroup.java:4966)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2101)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1858)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5845)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at jav
Model codes:
public class MainDataModel implements Serializable {
private static final long serialVersionUID = 1L;
private String category;
private String categoryID;
private String categoryDescription;
private int[] categoryImages;
private TimeInterpolator interpolator;
public MainDataModel(String categoryID, String category, String categoryDescription, int[] categoryImages,
TimeInterpolator interpolator) {
this.categoryID = categoryID;
this.category = category;
this.categoryDescription = categoryDescription;
this.categoryImages = categoryImages;
this.interpolator = interpolator;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategoryID() {
return categoryID;
}
public void setCategoryID(String caategoryID) {
this.categoryID = caategoryID;
}
public String getCategoryDescription() {
return categoryDescription;
}
public void setCategoryDescription(String categoryDescription) {
this.categoryDescription = categoryDescription;
}
public TimeInterpolator getInterpolator() {
return interpolator;
}
public void setInterpolator(TimeInterpolator interpolator) {
this.interpolator = interpolator;
}
public int[] getCategoryImages() {
return categoryImages;
}
public void setCategoryImages(int[] categoryImages) {
this.categoryImages = categoryImages;
}
}
AsyncTask codes and set image :
public class ColoniesDataInfo {
private static Context mContext;
private String ServerAddress = ServerIP_colonies.getColoniesIP();
public void getColoniesDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress);
}
private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<MainDataModel> infoModels;
#Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress)
//.cacheControl(CacheControl.FORCE_NETWORK)
.build();
Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("categories");
infoModels = new ArrayList<>();
for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);
String colID = postObject.getString("id");
String colTitle = postObject.getString("title");
String colDescription = postObject.getString("description");
final int[] colImages = {
R.drawable.colonies_image_food,
R.drawable.colonies_image_medical,
R.drawable.colonies_image_tecgnolegy,
R.drawable.colonies_image_entertenement,
R.drawable.colonies_image_car,
R.drawable.colonies_image_model,
R.drawable.colonies_image_sport,
};
Log.d("Data", "Colonies ID: " + colID);
Log.d("Data", "Colonies title: " + colTitle);
Log.d("Data", "Colonies Desc: " + colDescription);
Log.d("Data", "---------------------------------");
//Use the title and id as per your requirement
infoModels.add(new MainDataModel(colID, colTitle, colDescription, colImages,
Utils.createInterpolator(Utils.BOUNCE_INTERPOLATOR)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ou_response;
}
#Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}
Adapter codes and set image into adapter :
public class ColoniesAdapter extends RecyclerView.Adapter<ColoniesAdapter.ViewHolder> {
private List<MainDataModel> mDateSet;
private Context mContext;
private SparseBooleanArray expandState = new SparseBooleanArray();
public ColoniesAdapter(Context context, List<MainDataModel> dataSet) {
this.mContext = context;
this.mDateSet = dataSet;
for (int i = 0; i < mDateSet.size(); i++) {
expandState.append(i, false);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.colonies_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.colonies_title.setText(mDateSet.get(position).getCategory());
holder.colonies_title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getPosition();
MainDataModel model = mDateSet.get(pos);
v.getContext().startActivity(new Intent(v.getContext(), Category_page.class)
.putExtra("categoryTitle", model.getCategory())
.putExtra("categoryID", model.getCategoryID()));
}
});
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages())
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
holder.colonies_description.setText(mDateSet.get(position).getCategoryDescription());
holder.expandableLayout.setInterpolator(mDateSet.get(position).getInterpolator());
holder.expandableLayout.setExpanded(expandState.get(position));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
createRotateAnimator(holder.buttonLayout, 0f, 180f).start();
expandState.put(position, true);
}
#Override
public void onPreClose() {
createRotateAnimator(holder.buttonLayout, 180f, 0f).start();
expandState.put(position, false);
}
});
holder.buttonLayout.setRotation(expandState.get(position) ? 180f : 0f);
holder.buttonLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
onClickButton(holder.expandableLayout);
}
});
}
private void onClickButton(final ExpandableLayout expandableLayout) {
expandableLayout.toggle();
}
#Override
public int getItemCount() {
return mDateSet.size();
}
public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}
public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}
public void add(List<MainDataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}
public void update(List<MainDataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView colonies_title, colonies_description;
private ImageView colonies_image;
private ExpandableLinearLayout expandableLayout;
private RelativeLayout buttonLayout;
public ViewHolder(View itemView) {
super(itemView);
colonies_title = (TextView) itemView.findViewById(R.id.colonies_colony_title_text);
colonies_image = (ImageView) itemView.findViewById(R.id.colonies_cover_image);
colonies_description = (TextView) itemView.findViewById(R.id.colonies_expandable_description_text);
buttonLayout = (RelativeLayout) itemView.findViewById(R.id.colonies_expandable_button);
expandableLayout = (ExpandableLinearLayout) itemView.findViewById(R.id.colonies_expandable_layout);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* v.getContext().startActivity(new Intent(v.getContext(), PostShow_page.class)
.putExtra("title", model.getTitle())
.putExtra("image", model.getThumbnail()));*/
}
});
}
}
public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
animator.setDuration(300);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
}
How can i fix it?
First of all why are you loading all the array of images into a single imageView? Your method getCategoryImages() gives you an integer array of images. retrieve one by one corresponding to the position.
If the problem still persists you can refer to the below link with the same issue
https://github.com/bumptech/glide/issues/588
Glide.with(mContext)
.load(mDateSet.get(position).getCategoryImages()[position])
.placeholder(R.drawable.post_image)
.crossFade()
.override(700, 400)
.into(holder.colonies_image);
You are trying to load a list of ints and that is why Glide isn't working.
As you gave one ImageView as destination, only one image can be loaded there.
What you need to do is extract the image you wish to load and then pass it to Glide.
I'm trying to run an application and it crashes because of this error:
FATAL EXCEPTION: main
Process: com.panaceasoft.citiesdirectory, PID: 4201
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: ""
It had some Gradle errors, but I had solved them, and now it still crashed when I tried to run the app. It looks like that problem is in the class below, at line 252. Tried everything possible to check data and to solve this error, but nothing so far. What should I do? Thanks!
CitiesListFragment:
public class CitiesListFragment extends Fragment {
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Variables
//-------------------------------------------------------------------------------------------------------------------------------------
private RecyclerView mRecyclerView;
private ProgressWheel progressWheel;
private CityAdapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private TextView display_message;
private ArrayList<PCityData> pCityDataList;
private ArrayList<PCityData> pCityDataSet;
private NestedScrollView singleLayout;
private TextView scCityName;
private TextView scCityLocation;
private TextView scCityAbout;
private TextView scCityCatCount;
private TextView scCitySubCatCount;
private TextView scCityItemCount;
private ImageView scCityPhoto;
private Button scCityExplore;
private String jsonStatusSuccessString;
private String connectionError;
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Public Variables
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
public CitiesListFragment() {
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Constructor
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cities_list, container, false);
initUI(view);
initData();
return view;
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Override Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initUI(View view){
initSingleUI(view);
initSwipeRefreshLayout(view);
initProgressWheel(view);
initRecyclerView(view);
startLoading();
}
private void initSingleUI(View view) {
singleLayout =(NestedScrollView) view.findViewById(R.id.single_city_layout);
scCityName = (TextView) view.findViewById(R.id.sc_city_name);
scCityLocation = (TextView) view.findViewById(R.id.sc_city_loc);
scCityAbout = (TextView) view.findViewById(R.id.sc_city_desc);
scCityCatCount = (TextView) view.findViewById(R.id.txt_cat_count);
scCitySubCatCount = (TextView) view.findViewById(R.id.txt_sub_cat_count);
scCityItemCount = (TextView) view.findViewById(R.id.txt_item_count);
scCityPhoto = (ImageView) view.findViewById(R.id.sc_city_photo);
scCityExplore = (Button) view.findViewById(R.id.button_explore);
int screenWidth = Utils.getScreenWidth();
int rlWidth = (screenWidth/3) - 20;
RelativeLayout r1 = (RelativeLayout) view.findViewById(R.id.rl_count1);
RelativeLayout r2 = (RelativeLayout) view.findViewById(R.id.rl_count2);
RelativeLayout r3 = (RelativeLayout) view.findViewById(R.id.rl_count3);
r1.setMinimumWidth(rlWidth);
r2.setMinimumWidth(rlWidth);
r3.setMinimumWidth(rlWidth);
scCityPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
scCityExplore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pCityDataList !=null && pCityDataList.size() > 0) {
final Intent intent;
intent = new Intent(getActivity(), SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(0);
intent.putExtra("selected_city_id", pCityDataList.get(0).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
}
});
}
private void initSwipeRefreshLayout(View view) {
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
requestData(Config.APP_API_URL + Config.GET_ALL);
}
});
}
private void initProgressWheel(View view) {
progressWheel = (ProgressWheel) view.findViewById(R.id.progress_wheel);
}
private void initRecyclerView(View view) {
mRecyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(llm);
display_message = (TextView) view.findViewById(R.id.display_message);
display_message.setVisibility(view.GONE);
pCityDataSet = new ArrayList<>();
adapter = new CityAdapter(getActivity(), pCityDataSet);
mRecyclerView.setAdapter(adapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
onItemClicked(position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init UI Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
private void initData(){
requestData(Config.APP_API_URL + Config.GET_ALL);
jsonStatusSuccessString = getResources().getString(R.string.json_status_success);
connectionError = getResources().getString(R.string.connection_error);
}
private void requestData(String uri) {
JsonObjectRequest request = new JsonObjectRequest(uri,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String status = response.getString("status");
if (status.equals(jsonStatusSuccessString)) {
progressWheel.setVisibility(View.GONE);
Gson gson = new Gson();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
Utils.psLog("City Count : " + pCityDataList.size());
if(pCityDataList.size() > 1) {
singleLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
updateDisplay();
}else{
mRecyclerView.setVisibility(View.GONE);
singleLayout.setVisibility(View.VISIBLE);
stopLoading();
updateSingleDisplay();
}
updateGlobalCityList();
} else {
stopLoading();
Utils.psLog("Error in loading CityList.");
}
} catch (JSONException e) {
Utils.psErrorLogE("Error in loading CityList.", e);
stopLoading();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ex) {
progressWheel.setVisibility(View.GONE);
stopLoading();
/* NetworkResponse response = ex.networkResponse;
if (response != null && response.data != null) {
} else {*/
try {
display_message.setVisibility(View.VISIBLE);
display_message.setText(connectionError);
}catch (Exception e){
Utils.psErrorLogE("Error in Connection Url.", e);
}
//}
}
});
request.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(request);
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Init Data Function
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void updateSingleDisplay() {
try {
if (pCityDataList.size() > 0) {
display_message.setVisibility(View.GONE);
singleLayout.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in));
scCityName.setText(pCityDataList.get(0).name);
scCityLocation.setText(pCityDataList.get(0).address);
scCityAbout.setText(pCityDataList.get(0).description);
scCityCatCount.setText(pCityDataList.get(0).category_count + " Categories");
scCitySubCatCount.setText(pCityDataList.get(0).sub_category_count + " Sub Categories");
scCityItemCount.setText(pCityDataList.get(0).item_count + " Items");
Picasso.with(getActivity()).load(Config.APP_IMAGES_URL + pCityDataList.get(0).cover_image_file).into(scCityPhoto);
}
}catch(Exception e){
Utils.psErrorLogE("Error in single display data binding.", e);
}
}
private void updateGlobalCityList() {
GlobalData.cityDatas.clear();
for (PCityData cd : pCityDataList) {
GlobalData.cityDatas.add(cd);
}
}
private void updateDisplay() {
if (swipeRefreshLayout.isRefreshing()) {
pCityDataSet.clear();
adapter.notifyDataSetChanged();
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
} else {
for (PCityData cd : pCityDataList) {
pCityDataSet.add(cd);
}
}
stopLoading();
adapter.notifyItemInserted(pCityDataSet.size());
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Bind Functions
//-------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------
//region // Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
private void onItemClicked(int position) {
Utils.psLog("Position : " + position);
Intent intent;
intent = new Intent(getActivity(),SelectedCityActivity.class);
GlobalData.citydata = pCityDataList.get(position);
intent.putExtra("selected_city_id", pCityDataList.get(position).id);
getActivity().startActivity(intent);
getActivity().overridePendingTransition(R.anim.right_to_left, R.anim.blank_anim);
}
private void startLoading(){
try{
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
}
});
}catch (Exception e){}
}
private void stopLoading(){
try {
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}catch (Exception e){}
}
//-------------------------------------------------------------------------------------------------------------------------------------
//endregion Private Functions
//-------------------------------------------------------------------------------------------------------------------------------------
Line 252:
pCityDataList = gson.fromJson(response.getString("data"), listType);
PCityData.class:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 6/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCityData implements Parcelable {
public int id;
public String name;
public String description;
public String address;
public String lat;
public String lng;
public String added;
public int status;
public int item_count;
public int category_count;
public int sub_category_count;
public int follow_count;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public String cover_image_description;
public ArrayList<PCategoryData> categories;
protected PCityData(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
address = in.readString();
lat = in.readString();
lng = in.readString();
added = in.readString();
status = in.readInt();
item_count = in.readInt();
category_count = in.readInt();
sub_category_count = in.readInt();
follow_count = in.readInt();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
cover_image_description = in.readString();
if (in.readByte() == 0x01) {
categories = new ArrayList<PCategoryData>();
in.readList(categories, PCategoryData.class.getClassLoader());
} else {
categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeString(description);
dest.writeString(address);
dest.writeString(lat);
dest.writeString(lng);
dest.writeString(added);
dest.writeInt(status);
dest.writeInt(item_count);
dest.writeInt(category_count);
dest.writeInt(sub_category_count);
dest.writeInt(follow_count);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
dest.writeString(cover_image_description);
if (categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCityData> CREATOR = new Parcelable.Creator<PCityData>() {
#Override
public PCityData createFromParcel(Parcel in) {
return new PCityData(in);
}
#Override
public PCityData[] newArray(int size) {
return new PCityData[size];
}
};
}
L.E:
data:
[{"id":"1","name":"Maramureș","description":"Maramureș is a mountainous .","address":"Maramureș, Romania","lat":"0","lng":"0","admin_id":"3","is_approved":"1","paypal_trans_id":"0","added":"2016-07-1420:45:50","status":"1","item_count":85,"category_count":49,"sub_category_count":0,"follow_count":0,"cover_image_file":"singapore.png","cover_image_width":"600","cover_image_height":"400","cover_image_description":"Singapore","categories":
L.E:
PCategoryData.java:
package com.panaceasoft.citiesdirectory.models;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by Panacea-Soft on 8/8/15.
* Contact Email : teamps.is.cool#gmail.com
*/
public class PCategoryData implements Parcelable {
public int id;
public int shop_id;
public String name;
public int is_published;
public int ordering;
public String added;
public String updated;
public String cover_image_file;
public int cover_image_width;
public int cover_image_height;
public ArrayList<PSubCategoryData> sub_categories;
public Double value;
protected PCategoryData(Parcel in) {
id = in.readInt();
shop_id = in.readInt();
name = in.readString();
is_published = in.readInt();
ordering = in.readInt();
added = in.readString();
updated = in.readString();
cover_image_file = in.readString();
cover_image_width = in.readInt();
cover_image_height = in.readInt();
if (in.readByte() == 0x01) {
sub_categories = new ArrayList<PSubCategoryData>();
in.readList(sub_categories, PSubCategoryData.class.getClassLoader());
} else {
sub_categories = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(shop_id);
dest.writeString(name);
dest.writeInt(is_published);
dest.writeInt(ordering);
dest.writeString(added);
dest.writeString(updated);
dest.writeString(cover_image_file);
dest.writeInt(cover_image_width);
dest.writeInt(cover_image_height);
if (sub_categories == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(sub_categories);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<PCategoryData> CREATOR = new Parcelable.Creator<PCategoryData>() {
#Override
public PCategoryData createFromParcel(Parcel in) {
return new PCategoryData(in);
}
#Override
public PCategoryData[] newArray(int size) {
return new PCategoryData[size];
}
};
}
I guess that PCategoryData has double field, and guess that json value of that double field is "";
UPDATE
Your code will be like this:
public class CitiesListFragment extends Fragment {
...
private void requestData(String uri) {
...
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PCategoryData.class, new PCategoryDataTypeAdapter());
final Gson gson = gsonBuilder.create();
Type listType = new TypeToken<List<PCityData>>() {
}.getType();
//String data="";
pCityDataList = gson.fromJson(response.getString("Data"), listType);
...
}
...
class PCategoryDataTypeAdapter extends TypeAdapter<PCategoryData> {
#Override
public PCategoryData read(JsonReader in) throws IOException {
final PCategoryData data = new PCategoryData();
in.beginObject();
while (in.hasNext()) {
switch (in.nextName()) {
case "value": //Please change "value" to your field name.
try {
data.value = Double.valueOf(in.nextString());
} catch (NumberFormatException e) {
data.value = 0;
}
break;
}
}
in.endObject();
return data;
}
#Override
public void write(JsonWriter out, PCategoryData data) throws IOException {
out.beginObject();
out.name("value").value(data.value); //Please change "value" to your field name.
out.endObject();
}
}
...
}
I want to show some contacts information those are stored in a file in the list view.I want each contact to be shown in a separate cell rather than all together in a same place.Now all the contacts are showing in a single cell in the list view.I used a special character to check the end of a contact information.
Thanks in advance :)
Here is my code:
public void show_contacts()
{
final ListView listview = (ListView) findViewById(R.id.listview);
final ArrayList<String> list = new ArrayList<String>();
final ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
String data_read="";
String FILENAME = "myfile.txt";
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = null;
String s1="";
try {
fis = openFileInput("myfile.txt");
byte[] buffer = new byte[1];
while (fis.read(buffer) != -1) {
if(s1.endsWith("."))
{
data_read=fileContent.toString();
list.add(data_read);
}
else
s1+=buffer.toString();
fileContent.append(new String(buffer));
}
} catch (Exception e) {
e.printStackTrace();
}
data_read=fileContent.toString();
list.add(data_read);
listview.setAdapter(adapter);
}
public void Write_to_file(String cName2,String cNumber2)
{
String string=cName2+"--"+cNumber2;
String FILENAME="myfile.txt";
FileOutputStream fos = null;
Context c=this.getBaseContext();
try {
String s=".";
fos = c.openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(string.getBytes());
fos.write(s.getBytes());
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
My wish is you don't write the contact name into text file you Just write your Contacts in the custom Class like
public class Sample {
private String listitem1;
private String listitem2;
public String getListitem1() {
return listitem1;
}
public void setListitem1(String listitem1) {
this.listitem1 = listitem1;
}
public String getListitem2() {
return listitem2;
}
public void setListitem2(String listitem2) {
this.listitem2 = listitem2;
}
}
And use this custom adapter in your program...
public class CustomAdapter extends ArrayAdapter<Sample> {
public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;
public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
super(context, resource);
this.mlist = mlist;
this.context = context;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getPosition(Sample item) {
return super.getPosition(item);
}
#Override
public Sample getItem(int position) {
return mlist.get(position);
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.listitem, null);
TextView text1 = (TextView) convertView.findViewById(R.id.item1);
TextView text2 = (TextView) convertView.findViewById(R.id.item2);
text1.setText(mlist.get(position).getListitem1());
text2.setText(mlist.get(position).getListitem2());
return convertView;
}
}
And use this code into your Activity....
private ArrayList<Sample> mListItems;
private PullToRefreshListView mPullRefreshListView;
private CustomAdapter mAdapter;
private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler", "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_list);
mListItems= new ArrayList<Sample>();
mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
Calculation();
mPullRefreshListView.setAdapter(mAdapter);
}
private void Calculation() {
for(int i=0;i<mStrings.length;i++)
{
Sample sample = new Sample();
sample.setListitem1(mStrings[i]);
sample.setListitem2(mStrings[i]);
mListItems.add(sample);
}
}
And you just replace with you Contact Name and Number in the Above sample..