Android Parse.com error with ArrayAdapter[App crash] - java

I am having a problem using the ParseObject, first tried ListActivity but the app was crashing, then saw few posts on stack overflow didnt work either, few details about the Parse Class are
Class Name : Events
Fields: String event_name;
String date;
String time;
String event_venue;
String speaker;
int fee;
String event_description;
The error in the program persists when the i am trying to initialize Adapter.
My code is as Follows
Events.java
public class Events extends ParseObject {
private String event_name;
private String date;
private String time;
private String event_venue;
private String speaker;
private int fee;
private String event_description;
public Events(String event_name, String date, String time, String event_venue, String speaker, int fee, String event_description) {
this.event_name = event_name;
this.date = date;
this.time = time;
this.event_venue = event_venue;
this.speaker = speaker;
this.fee = fee;
this.event_description = event_description;
}
public String getEvent_name() {
return event_name;
}
public void setEvent_name(String event_name) {
this.event_name = event_name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getEvent_venue() {
return event_venue;
}
public void setEvent_venue(String event_venue) {
this.event_venue = event_venue;
}
public String getSpeaker() {
return speaker;
}
public void setSpeaker(String speaker) {
this.speaker = speaker;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
public String getEvent_description() {
return event_description;
}
public void setEvent_description(String event_description) {
this.event_description = event_description;
}
}
Events_Activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class Event_Activity extends AppCompatActivity {
private List<Events> mEvents= new ArrayList<Events>();
private String e_name;
private String e_date;
private String e_time;
private String e_venue;
private String e_speaker;
private int e_fee;
private String e_description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_);
ParseQuery<Events> event_query = new ParseQuery<Events>("Events");
event_query.findInBackground(new FindCallback<Events>() {
#Override
public void done(List<Events> list, ParseException e) {
if(e != null){
Toast.makeText(Event_Activity.this,"Exception : "+e,Toast.LENGTH_LONG).show();
}
for (Events event : list){
e_name = event.getEvent_name();
e_date = event.getDate();
e_time = event.getTime();
e_venue = event.getEvent_venue();
e_speaker = event.getSpeaker();
e_fee = event.getFee();
e_description = event.getEvent_description();
Events new_event = new Events(e_name,e_date,e_time,e_venue,e_speaker,e_fee,e_description);
mEvents.add(new_event);
}
}
});
ArrayAdapter<Events> value = new ArrayAdapter<Events>(Event_Activity.this,android.R.layout.simple_list_item_1, android.R.id.text1, mEvents);
ListView v = (ListView)findViewById(R.id.eventlistView);
v.setAdapter(value);
activity_event_.xml
<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="com.example.cse.Event_Activity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/eventlistView">
</ListView>
</RelativeLayout>

Related

Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference RecyclerView Adapter Error

Api (Interface)
package com.example.openweathermap;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface Api {
String BASE_URL="https://samples.openweathermap.org/data/2.5/";
#GET("weather/")
Call<WeatherResponse> getWeatherDetails(#Query("api_key")String api_key);
}
My Model Class
Here is my model class which consists of getters and setters
package com.example.openweathermap;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Weather {
#SerializedName("coord")
private String coord;
#SerializedName("lon")
private String lon;
#SerializedName("lat")
private String lat;
#SerializedName("weather")
private List<Integer> weather = new ArrayList<Integer>();
#SerializedName("description")
private String description;
#SerializedName("base")
private String base;
#SerializedName("main")
private String main;
#SerializedName("temp")
private String temp;
#SerializedName("pressure")
private String pressure;
#SerializedName("humidity")
private Integer humidity;
#SerializedName("temp_min")
private String temp_min;
#SerializedName("temp_max")
private String temp_max;
#SerializedName("visibility")
private String visibility;
#SerializedName("wind")
private String wind;
#SerializedName("speed")
private String speed;
#SerializedName("deg")
private String deg;
#SerializedName("clouds")
private String clouds;
#SerializedName("all")
private String all;
#SerializedName("dt")
private String dt;
#SerializedName("sys")
private String sys;
#SerializedName("type")
private String type;
#SerializedName("id")
private String id;
#SerializedName("message")
private String message;
#SerializedName("country")
private String country;
#SerializedName("sunrise")
private String sunrise;
#SerializedName("sunset")
private String sunset;
public Weather(String description) {
this.description = description;
}
public Weather(String coord, String lon, String lat, List<Integer> weather, String base, String main, String temp, String pressure, Integer humidity, String temp_min, String temp_max, String visibility, String wind, String speed, String deg, String clouds, String all, String dt, String sys, String type, String id, String message, String country, String sunrise, String sunset) {
this.coord = coord;
this.lon = lon;
this.lat = lat;
this.weather = weather;
this.base = base;
this.main = main;
this.temp = temp;
this.pressure = pressure;
this.humidity = humidity;
this.temp_min = temp_min;
this.temp_max = temp_max;
this.visibility = visibility;
this.wind = wind;
this.speed = speed;
this.deg = deg;
this.clouds = clouds;
this.all = all;
this.dt = dt;
this.sys = sys;
this.type = type;
this.id = id;
this.message = message;
this.country = country;
this.sunrise = sunrise;
this.sunset = sunset;
}
public String getCoord() {
return coord;
}
public void setCoord(String coord) {
this.coord = coord;
}
public String getLon() {
return lon;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public List<Integer> getWeather() {
return weather;
}
public void setWeather(List<Integer> weather) {
this.weather = weather;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getPressure() {
return pressure;
}
public void setPressure(String pressure) {
this.pressure = pressure;
}
public Integer getHumidity() {
return humidity;
}
public void setHumidity(Integer humidity) {
this.humidity = humidity;
}
public String getTemp_min() {
return temp_min;
}
public void setTemp_min(String temp_min) {
this.temp_min = temp_min;
}
public String getTemp_max() {
return temp_max;
}
public void setTemp_max(String temp_max) {
this.temp_max = temp_max;
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getDeg() {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
public String getClouds() {
return clouds;
}
public void setClouds(String clouds) {
this.clouds = clouds;
}
public String getAll() {
return all;
}
public void setAll(String all) {
this.all = all;
}
public String getDt() {
return dt;
}
public void setDt(String dt) {
this.dt = dt;
}
public String getSys() {
return sys;
}
public void setSys(String sys) {
this.sys = sys;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getSunrise() {
return sunrise;
}
public void setSunrise(String sunrise) {
this.sunrise = sunrise;
}
public String getSunset() {
return sunset;
}
public void setSunset(String sunset) {
this.sunset = sunset;
}
}
MyJSONResponse
I am trying to get this data in adapter which is a RecyclerView Adapter
package com.example.openweathermap;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class WeatherResponse {
#SerializedName("weather")
private List<Weather> weather;
#SerializedName("id")
private String id;
#SerializedName("main")
private String main;
#SerializedName("description")
private String description;
#SerializedName("temp")
private String temp;
public WeatherResponse(List<Weather> weather) {
this.weather = weather;
}
public WeatherResponse(String weather, String id, String main, String description, String temp) {
this.id = id;
this.main = main;
this.description = description;
this.temp = temp;
}
public List<Weather> getWeather() {
return weather;
}
public void setWeather(List<Weather> weather) {
this.weather = weather;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
}
----------
**MyAdapter
This is the recyclerview adapter**
----------
package com.example.openweathermap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<Weather> weathers;
public Context context;
public MyAdapter(ArrayList<Weather> weathers, Context context) {
this.weathers = weathers;
this.context = context;
}
public MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.ViewHolder holder, int position) {
Weather weather=weathers.get(position);
holder.temp.setText(weather.getTemp());
/*holder.name.setText(weather.getCountry());*/
holder.description.setText(weather.getDescription());
weathers=new ArrayList<>();
}
#Override
public int getItemCount() {
return weathers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView temp;
public TextView name;
public TextView description;
public ViewHolder(#NonNull View itemView) {
super(itemView);
temp=(TextView)itemView.findViewById(R.id.temp);
name=(TextView)itemView.findViewById(R.id.name);
description=(TextView)itemView.findViewById(R.id.description);
}
}
}
Main Activity
package com.example.openweathermap;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<Weather> weathersList;
// TODO - insert your themoviedb.org API KEY here
private final static String API_KEY = "ae47e0f7eb5fbbce0c9cfbdf1373a1b3";
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
weathersList=new ArrayList<>();
if (API_KEY.isEmpty()) {
Toast.makeText(getApplicationContext(), "Please obtain your API KEY first ", Toast.LENGTH_LONG).show();
return;
}
getWeather();
}
private void getWeather() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api api=retrofit.create(Api.class);
Call<WeatherResponse> call=api.getWeatherDetails(API_KEY);
call.enqueue(new Callback<WeatherResponse>() {
#Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
ArrayList<Weather> weathersList = (ArrayList<Weather>) response.body().getWeather();
adapter=new MyAdapter(weathersList,getApplicationContext());
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
I am getting an error as " Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference RecyclerView Adapter Error" in MyAdapter

How to fix 'No properties to serialize found on class' error in a Java class?

This question is not a duplicate. I have tried other methods shown in answers, but they don't seem to work. I am trying to iterate through all the documents in my "users" collection to get everyone's user name, store it into an ArrayList, and display it in my listview.
My ERROR Shown Is
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.example, PID: 17169
java.lang.RuntimeException: No properties to serialize found on class com.example.example.Model
at com.google.firebase.firestore.util.CustomClassMapper$BeanMapper.<init>(com.google.firebase:firebase-firestore##21.3.1:714)
at com.google.firebase.firestore.util.CustomClassMapper.loadOrCreateBeanMapperForClass(com.google.firebase:firebase-firestore##21.3.1:377)
at com.google.firebase.firestore.util.CustomClassMapper.convertBean(com.google.firebase:firebase-firestore##21.3.1:540)
at com.google.firebase.firestore.util.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-firestore##21.3.1:253)
at com.google.firebase.firestore.util.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-firestore##21.3.1:100)
at com.google.firebase.firestore.DocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:210)
at com.google.firebase.firestore.QueryDocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:116)
at com.google.firebase.firestore.DocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:188)
at com.google.firebase.firestore.QueryDocumentSnapshot.toObject(com.google.firebase:firebase-firestore##21.3.1:97)
at com.example.example.LeaderboardActivity$1.onSuccess(LeaderboardActivity.java:46)
at com.example.example.LeaderboardActivity$1.onSuccess(LeaderboardActivity.java:42)
at com.google.android.gms.tasks.zzn.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
My Leaderboard Class
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
public class LeaderboardActivity extends AppCompatActivity {
ArrayList<String> usersInfo = new ArrayList<>();
FirebaseFirestore fStore = FirebaseFirestore.getInstance();
FirebaseAuth fAuth= FirebaseAuth.getInstance();
String userID= fAuth.getCurrentUser().getUid();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
lv = findViewById(R.id.leaderboardlist);
CollectionReference cr = fStore.collection("users");
cr.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots){ //Line 42
Model mod = documentSnapshot.toObject(Model.class);
String Name = mod.getName();
usersInfo.add(Name);
System.out.println(usersInfo); //Line 46
}
}
});
usersInfo.add("aggg");
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,usersInfo);
lv.setAdapter(adapter);
System.out.println(usersInfo);
final Context context = this;
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_arcade:
Intent intentSettings = new Intent(context, MenuActivity.class);
startActivity(intentSettings);
finish();
break;
case R.id.action_home:
Intent intentHome = new Intent(context, Menu2.class);
startActivity(intentHome);
finish();
break;
case R.id.action_account:
Intent intentAccount = new Intent(context, AccountActivity.class);
startActivity(intentAccount);
finish();
break;
}
return false;
}
});
}
}
My Model Class
import androidx.annotation.Keep;
import java.io.Serializable;#Keep
public class Model implements Serializable {
public static String Name;
public static String Email;
public static int Coin_Toss_High_Score;
public static int Rps_High_Score;
public static int TicTacToe_High_Score;
public Model() {}
public Model(String name, String email, int ticTacToe_High_Score, int coin_Toss_High_Score, int rps_High_Score){
this.Name = name;
this.Email = email;
this.TicTacToe_High_Score = ticTacToe_High_Score;
this.Coin_Toss_High_Score = coin_Toss_High_Score;
this.Rps_High_Score = rps_High_Score;
}
public static String getName() {
return Name;
}
public static String getEmail() {
return Email;
}
public static int getCoin_Toss_High_Score() {
return Coin_Toss_High_Score;
}
public static int getRps_High_Score() {
return Rps_High_Score;
}
public static int getTicTacToe_High_Score() {
return TicTacToe_High_Score;
}
public static void setName(String name) {
Name = name;
}
public static void setEmail(String email) {
Email = email;
}
public static void setCoin_Toss_High_Score(int coin_Toss_High_Score) {
Coin_Toss_High_Score = coin_Toss_High_Score;
}
public static void setRps_High_Score(int rps_High_Score) {
Rps_High_Score = rps_High_Score;
}
public static void setTicTacToe_High_Score(int ticTacToe_High_Score) {
TicTacToe_High_Score = ticTacToe_High_Score;
}
}
You need to Add this Gson library
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
then import java.io.Serializable;#Keep remove this and import this in your class
import com.google.gson.annotations.SerializedName
change this :
public static String Name;
public static String Email;
public static int Coin_Toss_High_Score;
public static int Rps_High_Score;
public static int TicTacToe_High_Score;
To this :
public String Name;
public String Email;
public int Coin_Toss_High_Score;
public int Rps_High_Score;
public int TicTacToe_High_Score;
Even i thing if you already have getter() setter() method this way even you are making it public you can access all this property through getter() and setter() method.
This should be like this:
public class Model implements Serializable {
private String Name;
private String Email;
private int Coin_Toss_High_Score;
private int Rps_High_Score;
private int TicTacToe_High_Score;
public Model(String name, String email, int coin_Toss_High_Score, int rps_High_Score, int ticTacToe_High_Score) {
Name = name;
Email = email;
Coin_Toss_High_Score = coin_Toss_High_Score;
Rps_High_Score = rps_High_Score;
TicTacToe_High_Score = ticTacToe_High_Score;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public int getCoin_Toss_High_Score() {
return Coin_Toss_High_Score;
}
public void setCoin_Toss_High_Score(int coin_Toss_High_Score) {
Coin_Toss_High_Score = coin_Toss_High_Score;
}
public int getRps_High_Score() {
return Rps_High_Score;
}
public void setRps_High_Score(int rps_High_Score) {
Rps_High_Score = rps_High_Score;
}
public int getTicTacToe_High_Score() {
return TicTacToe_High_Score;
}
public void setTicTacToe_High_Score(int ticTacToe_High_Score) {
TicTacToe_High_Score = ticTacToe_High_Score;
}
}

How to pass data collected in arraylist from json asset file in one activity having recyclerview to another activity again having recycler view?

I have an activity named Cardview Activity which has a recycler view associated with it and i am fetching data from a JSON asset file in that. But now when i click on an item of Cardview Activity, I want to send data related to that item only to another activity i.e. People_List_Activity which is again having a recyclerView.
CardViewActivity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class CardViewActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
private RecyclerView mainRecyclerView;
private RecyclerView.Adapter mainAdapter;
private RecyclerView.LayoutManager mainLayoutManager;
private static String LOG_TAG = "CardViewActivity";
EditText inputSearchMain;
private ArrayList<CategoryModel.CategoryList> categoryLists;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_view);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Telephone Directory");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
categoryLists=new ArrayList<CategoryModel.CategoryList>();
categoryLists.addAll(getmcategoryset());
mainRecyclerView=(RecyclerView)findViewById(R.id.recyclerView_Main);
mainRecyclerView.setHasFixedSize(true);
mainLayoutManager=new LinearLayoutManager(this);
mainRecyclerView.setLayoutManager(mainLayoutManager);
mainAdapter=new RecyclerViewAdapterMain(getmcategoryset());
mainRecyclerView.setAdapter(mainAdapter);
inputSearchMain = (EditText) findViewById(R.id.inputSearchMain);
addTextListener();
}
public void addTextListener(){
inputSearchMain.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final ArrayList<CategoryModel.CategoryList> filteredList = new ArrayList<CategoryModel.CategoryList>();
for (int i = 0; i < categoryLists.size(); i++) {
final String text = categoryLists.get(i).getCategory_name().toLowerCase();
if (text.contains(query)) {
filteredList.add(categoryLists.get(i));
}
}
mainRecyclerView.setLayoutManager(new LinearLayoutManager(CardViewActivity.this));
mainAdapter = new RecyclerViewAdapterMain(filteredList);
mainRecyclerView.setAdapter(mainAdapter);
mainAdapter.notifyDataSetChanged(); // data set changed
}
});
}
private ArrayList<CategoryModel.CategoryList> getmcategoryset() {
try {
ArrayList<CategoryModel.CategoryList>categoryList = new ArrayList<CategoryModel.CategoryList>();
JSONObject jsonObject = new JSONObject(readJSONFromAsset());
JSONArray categoryArray = jsonObject.getJSONArray("Category");
Log.d("getmcategoryset", "category count: "+categoryArray.length());
for (int i = 0; i < categoryArray.length(); i++)
{
JSONObject job = categoryArray.getJSONObject(i);
int categoryId = job.getInt("Category_id");
String categoryName = job.getString("Category_name");
//this is for email array
ArrayList<String> emails = new ArrayList<>();
JSONArray emailArray = job.getJSONArray("Emails");
for (int j = 0; j< emailArray.length(); j++){
emails.add(emailArray.getString(j));
}
//This i for Epabx array
ArrayList<String> epabx = new ArrayList<>();
JSONArray epabxArray = job.getJSONArray("Epabx");
for (int j = 0; j < epabxArray.length(); j++){
epabx.add(epabxArray.getString(j));
}
//This i for Category_Fax array
ArrayList<String> category_Fax = new ArrayList<>();
JSONArray category_FaxJson = job.getJSONArray("Category_Fax");
for (int j = 0; j < category_FaxJson.length(); j++){
category_Fax.add(category_FaxJson.getString(j));
}
//This i for Persons array
ArrayList<CategoryModel.Persons> personsList = new ArrayList<>();
JSONArray personsArray = job.getJSONArray("Persons");
for (int j = 0; j < personsArray.length(); j++){
JSONObject jobIn = personsArray.getJSONObject(j);
int Person_ID = jobIn.getInt("Person_ID");
String Name = jobIn.getString("Name");
String Designation = jobIn.getString("Designation");
String Office_Phone = jobIn.getString("Office_Phone");
String Residence_Phone = jobIn.getString("Residence_Phone");
String VOIP = jobIn.getString("VOIP");
String Address = jobIn.getString("Address");
//this is for Fax array
ArrayList<String>Fax = new ArrayList<>();
JSONArray fax = jobIn.getJSONArray("Fax");
for (int k=0; k < fax.length(); k++)
{
// JSONObject jobI = fax.getString(k);
Fax.add(fax.getString(k));
}
String Ext = jobIn.getString("Ext");
personsList.add(new CategoryModel.Persons(Person_ID, Name, Designation, Office_Phone, Residence_Phone,
VOIP, Address, Fax, Ext));
}
//here your Category[] value store in categoryArrayList
categoryList.add(new CategoryModel.CategoryList(categoryId, categoryName, emails, epabx, category_Fax, personsList));
Log.i("categoryList size = ", ""+categoryArray.length());
}
if (categoryList != null)
{
Log.i("categoryList size = ", ""+categoryArray.length());
}
return categoryList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onResume() {
super.onResume();
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("DirectoryData.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
RecyclerViewAdapterMain
package com.example.android.directory;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Android on 3/17/2017.
*/
public class RecyclerViewAdapterMain extends RecyclerView.Adapter<RecyclerViewAdapterMain.CategoryObjectHolder> {
private static String LOG_TAG = "categoryRecyclrVwAdptr";
private ArrayList<CategoryModel.CategoryList> mcategoryset;
private static CategoryClickListener categoryClickListener;
public static class CategoryObjectHolder extends RecyclerView.ViewHolder {
TextView category_name;
public CategoryObjectHolder(View itemView){
super(itemView);
category_name=(TextView)itemView.findViewById(R.id.category_name);
/*category_emails=(TextView)itemView.findViewById(R.id.category_emails);
category_epabx=(TextView)itemView.findViewById(R.id.category_epabx);
category_fax=(TextView)itemView.findViewById(R.id.category_fax);*/
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
}
});
}
public RecyclerViewAdapterMain(ArrayList<CategoryModel.CategoryList> myDataset) {
mcategoryset = myDataset;
}
public CategoryObjectHolder onCreateViewHolder(ViewGroup parent,int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_row_main_activity,parent,false);
CategoryObjectHolder categoryObjectHolder=new CategoryObjectHolder(view);
return categoryObjectHolder;
}
#Override
public void onBindViewHolder(CategoryObjectHolder holder, int position) {
holder.category_name.setText(mcategoryset.get(position).getCategory_name());
}
public void addItem(CategoryModel.CategoryList dataObj, int index) {
mcategoryset.add(index, dataObj);
notifyItemInserted(index);
}
public void deleteItem(int index) {
mcategoryset.remove(index);
notifyItemRemoved(index);
}
#Override
public int getItemCount() {
return mcategoryset.size();
}
public interface CategoryClickListener {
public void onItemClick(int position, View v);
}
}
People_List_Activity.java
package com.example.android.directory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class PeopleListActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_people_list);
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar);
mActionBarToolbar.setTitle("Staff List");
mActionBarToolbar.setLogo(R.drawable.toolbar_logo);
mActionBarToolbar.setTitleMargin(5,2,2,2);
setSupportActionBar(mActionBarToolbar);
}
}
RecyclerViewAdapter_People.java
package com.example.android.directory;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Android on 3/20/2017.
*/
public class RecyclerViewAdapter_People extends RecyclerView.Adapter<RecyclerViewAdapter_People.PeopleObjectHolder> {
private static String TAG = "peopleRecyclrVwAdptr";
public static class PeopleObjectHolder extends RecyclerView.ViewHolder{
TextView peopleName,peopleDesignation;
public PeopleObjectHolder(View itemView) {
super(itemView);
peopleName=(TextView)itemView.findViewById(R.id.people_name);
peopleDesignation=(TextView)itemView.findViewById(R.id.people_designation);
Log.d(TAG, "PeopleObjectHolder: ");
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public PeopleObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_people_list_row,parent,false);
PeopleObjectHolder peopleObjectHolder=new PeopleObjectHolder(view);
return peopleObjectHolder;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter_People.PeopleObjectHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
CategoryModel.java:
package com.example.android.directory;
import java.util.ArrayList;
/**
* Created by Android on 3/17/2017.
*/
public class CategoryModel {
private ArrayList<CategoryList>categoryList;
public ArrayList<CategoryList> getCategoryList() {
return categoryList;
}
public void setCategoryList(ArrayList<CategoryList> categoryList) {
this.categoryList = categoryList;
}
public static class CategoryList{
private int Category_id;
private String Category_name;
private ArrayList<String>Emails;
private ArrayList<String>Epabx;
private ArrayList<String>Category_Fax;
private ArrayList<Persons> persons;
public CategoryList(int category_id, String category_name,
ArrayList<String> emails, ArrayList<String> epabx, ArrayList<String> category_Fax,
ArrayList<Persons> persons) {
Category_id = category_id;
Category_name = category_name;
Emails = emails;
Epabx = epabx;
Category_Fax = category_Fax;
this.persons = persons;
}
public int getCategory_id() {
return Category_id;
}
public void setCategory_id(int category_id) {
Category_id = category_id;
}
public String getCategory_name() {
return Category_name;
}
public void setCategory_name(String category_name) {
Category_name = category_name;
}
public ArrayList<String> getEmails() {
return Emails;
}
public void setEmails(ArrayList<String> emails) {
Emails = emails;
}
public ArrayList<String> getEpabx() {
return Epabx;
}
public void setEpabx(ArrayList<String> epabx) {
Epabx = epabx;
}
public ArrayList<String> getCategory_Fax() {
return Category_Fax;
}
public void setCategory_Fax(ArrayList<String> category_Fax) {
Category_Fax = category_Fax;
}
public ArrayList<Persons> getPersons() {
return persons;
}
public void setPersons(ArrayList<Persons> persons) {
this.persons = persons;
}
}
public static class Persons{
private int Person_ID;
private String Name;
private String Designation;
private String Office_Phone;
private String Residence_Phone;
private String VOIP;
private String Address;
private ArrayList<String>Fax;
private String Ext;
public Persons(int person_ID, String name, String designation, String office_Phone,
String residence_Phone, String VOIP, String address, ArrayList<String> fax, String ext) {
Person_ID = person_ID;
Name = name;
Designation = designation;
Office_Phone = office_Phone;
Residence_Phone = residence_Phone;
this.VOIP = VOIP;
Address = address;
Fax = fax;
Ext = ext;
}
public int getPerson_ID() {
return Person_ID;
}
public void setPerson_ID(int person_ID) {
Person_ID = person_ID;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
Designation = designation;
}
public String getOffice_Phone() {
return Office_Phone;
}
public void setOffice_Phone(String office_Phone) {
Office_Phone = office_Phone;
}
public String getResidence_Phone() {
return Residence_Phone;
}
public void setResidence_Phone(String residence_Phone) {
Residence_Phone = residence_Phone;
}
public String getVOIP() {
return VOIP;
}
public void setVOIP(String VOIP) {
this.VOIP = VOIP;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public ArrayList<String> getFax() {
return Fax;
}
public void setFax(ArrayList<String> fax) {
Fax = fax;
}
public String getExt() {
return Ext;
}
public void setExt(String ext) {
Ext = ext;
}
}
}
how can i send the Person_Id, Name and Designation to the People_List_Activity ? Please help as i am stuck in the code.
You can send using Intent , by passing your data in Bundle and then pass Bundle into Intent Extras.When you go form one Activity to another .
Intent intent=new Intent(CardViewActivity.this,PeopleListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key1",value1);
bundle.putString("key2",value2);
bundle.putString("key3",value3);
intent.putExtras(bundle)
startActvity(intent);
And You can retrieve Data in next Activity OnCreate():
Bundle bundle = getIntent().getExtras();
String value1 = bundle.getString("key1");
String value2 = bundle.getString("key2");
String value3 = bundle.getString("key3");

Getting data from JSON in android mobile gives fatalexception main

Please i need help , i am new to android so i need help . i need to receive data from JSON and i watched a loot of tutorials and i cant find my answer . I need to receive data from JSON link . once i do it i get a loot of errors and also the compilator gives me a lot of errors . Here is my code :
my custom adapter called CustomItemAdapter.java
package com.example.madrit.okhttp_gson_view;
import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class CustomItemAdapter extends ArrayAdapter <model_item> {
public CustomItemAdapter(Context context , List<model_item> mymodel)
{
super(context , 0 , mymodel);
}
#Nullable
#Override
public model_item getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
model_item model = getItem(position);
if (convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_shop_list, parent, false);
}
TextView title = (TextView) convertView.findViewById(R.id.item_onthelist_title);
TextView price = (TextView) convertView.findViewById(R.id.item_onthelist_price);
TextView description = (TextView) convertView.findViewById(R.id.item_onthelist_description);
title.setText(model.getName());
price.setText(Double.toString(model.getPrice()));
description.setText(model.getMeta_description());
return convertView;
}
}
my model item model_item.java
package com.example.madrit.okhttp_gson_view;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class model_item {
private String id_product;
private String id_supplier;
private String id_manufacturer;
private String id_category_default;
private String id_shop_default;
private String id_tax_rules_group;
private String on_sale;
private String online_only;
private String ean13;
private String upc;
private String ecotax;
private int quantity;
private String minimal_quantity;
private double price;
private String wholesale_price;
private String unity;
private String unit_price_ratio;
private String additional_shipping_cost;
private String reference;
private String supplier_reference;
private String location;
private String width;
private String height;
private String depth;
private String weight;
private String out_of_stock;
private String quantity_discount;
private String customizable;
private String uploadable_files;
private String text_fields;
private String active;
private String redirect_type;
private String id_product_redirected;
private String available_for_order;
private String available_date;
private String condition;
private String show_price;
private String indexed;
private String visibility;
private String cache_is_pack;
private String cache_has_attachments;
private String is_virtual;
private String cache_default_attribute;
private String date_add;
private String date_upd;
private String advanced_stock_management;
private String pack_stock_type;
private String id_shop;
private int id_product_attribute;
private String product_attribute_minimal_quantity;
private String description;
private String description_short;
private String available_now;
private String available_later;
private String link_rewrite;
private String meta_description;
private String meta_keywords;
private String meta_title;
private String name;
private String id_image;
private String legend;
private String manufacturer_name;
private String category_default;
#SerializedName("new")
private String newX;
private String orderprice;
private int allow_oosp;
private String category;
private String link;
private int attribute_price;
private double price_tax_exc;
private double price_without_reduction;
private int reduction;
private boolean specific_prices;
private int quantity_all_versions;
private int virtual;
private int pack;
private int nopackprice;
private boolean customization_required;
private int rate;
private String tax_name;
private String image_url;
private List<?> features;
private List<?> attachments;
private List<?> packItems;
public String getId_product() {
return id_product;
}
public void setId_product(String id_product) {
this.id_product = id_product;
}
public String getId_supplier() {
return id_supplier;
}
public void setId_supplier(String id_supplier) {
this.id_supplier = id_supplier;
}
public String getId_manufacturer() {
return id_manufacturer;
}
public void setId_manufacturer(String id_manufacturer) {
this.id_manufacturer = id_manufacturer;
}
public String getId_category_default() {
return id_category_default;
}
public void setId_category_default(String id_category_default) {
this.id_category_default = id_category_default;
}
public String getId_shop_default() {
return id_shop_default;
}
public void setId_shop_default(String id_shop_default) {
this.id_shop_default = id_shop_default;
}
public String getId_tax_rules_group() {
return id_tax_rules_group;
}
public void setId_tax_rules_group(String id_tax_rules_group) {
this.id_tax_rules_group = id_tax_rules_group;
}
public String getOn_sale() {
return on_sale;
}
public void setOn_sale(String on_sale) {
this.on_sale = on_sale;
}
public String getOnline_only() {
return online_only;
}
public void setOnline_only(String online_only) {
this.online_only = online_only;
}
public String getEan13() {
return ean13;
}
public void setEan13(String ean13) {
this.ean13 = ean13;
}
public String getUpc() {
return upc;
}
public void setUpc(String upc) {
this.upc = upc;
}
public String getEcotax() {
return ecotax;
}
public void setEcotax(String ecotax) {
this.ecotax = ecotax;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getMinimal_quantity() {
return minimal_quantity;
}
public void setMinimal_quantity(String minimal_quantity) {
this.minimal_quantity = minimal_quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getWholesale_price() {
return wholesale_price;
}
public void setWholesale_price(String wholesale_price) {
this.wholesale_price = wholesale_price;
}
public String getUnity() {
return unity;
}
public void setUnity(String unity) {
this.unity = unity;
}
public String getUnit_price_ratio() {
return unit_price_ratio;
}
public void setUnit_price_ratio(String unit_price_ratio) {
this.unit_price_ratio = unit_price_ratio;
}
public String getAdditional_shipping_cost() {
return additional_shipping_cost;
}
public void setAdditional_shipping_cost(String additional_shipping_cost) {
this.additional_shipping_cost = additional_shipping_cost;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getSupplier_reference() {
return supplier_reference;
}
public void setSupplier_reference(String supplier_reference) {
this.supplier_reference = supplier_reference;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getDepth() {
return depth;
}
public void setDepth(String depth) {
this.depth = depth;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getOut_of_stock() {
return out_of_stock;
}
public void setOut_of_stock(String out_of_stock) {
this.out_of_stock = out_of_stock;
}
public String getQuantity_discount() {
return quantity_discount;
}
public void setQuantity_discount(String quantity_discount) {
this.quantity_discount = quantity_discount;
}
public String getCustomizable() {
return customizable;
}
public void setCustomizable(String customizable) {
this.customizable = customizable;
}
public String getUploadable_files() {
return uploadable_files;
}
public void setUploadable_files(String uploadable_files) {
this.uploadable_files = uploadable_files;
}
public String getText_fields() {
return text_fields;
}
public void setText_fields(String text_fields) {
this.text_fields = text_fields;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getRedirect_type() {
return redirect_type;
}
public void setRedirect_type(String redirect_type) {
this.redirect_type = redirect_type;
}
public String getId_product_redirected() {
return id_product_redirected;
}
public void setId_product_redirected(String id_product_redirected) {
this.id_product_redirected = id_product_redirected;
}
public String getAvailable_for_order() {
return available_for_order;
}
public void setAvailable_for_order(String available_for_order) {
this.available_for_order = available_for_order;
}
public String getAvailable_date() {
return available_date;
}
public void setAvailable_date(String available_date) {
this.available_date = available_date;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getShow_price() {
return show_price;
}
public void setShow_price(String show_price) {
this.show_price = show_price;
}
public String getIndexed() {
return indexed;
}
public void setIndexed(String indexed) {
this.indexed = indexed;
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public String getCache_is_pack() {
return cache_is_pack;
}
public void setCache_is_pack(String cache_is_pack) {
this.cache_is_pack = cache_is_pack;
}
public String getCache_has_attachments() {
return cache_has_attachments;
}
public void setCache_has_attachments(String cache_has_attachments) {
this.cache_has_attachments = cache_has_attachments;
}
public String getIs_virtual() {
return is_virtual;
}
public void setIs_virtual(String is_virtual) {
this.is_virtual = is_virtual;
}
public String getCache_default_attribute() {
return cache_default_attribute;
}
public void setCache_default_attribute(String cache_default_attribute) {
this.cache_default_attribute = cache_default_attribute;
}
public String getDate_add() {
return date_add;
}
public void setDate_add(String date_add) {
this.date_add = date_add;
}
public String getDate_upd() {
return date_upd;
}
public void setDate_upd(String date_upd) {
this.date_upd = date_upd;
}
public String getAdvanced_stock_management() {
return advanced_stock_management;
}
public void setAdvanced_stock_management(String advanced_stock_management) {
this.advanced_stock_management = advanced_stock_management;
}
public String getPack_stock_type() {
return pack_stock_type;
}
public void setPack_stock_type(String pack_stock_type) {
this.pack_stock_type = pack_stock_type;
}
public String getId_shop() {
return id_shop;
}
public void setId_shop(String id_shop) {
this.id_shop = id_shop;
}
public int getId_product_attribute() {
return id_product_attribute;
}
public void setId_product_attribute(int id_product_attribute) {
this.id_product_attribute = id_product_attribute;
}
public String getProduct_attribute_minimal_quantity() {
return product_attribute_minimal_quantity;
}
public void setProduct_attribute_minimal_quantity(String product_attribute_minimal_quantity) {
this.product_attribute_minimal_quantity = product_attribute_minimal_quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription_short() {
return description_short;
}
public void setDescription_short(String description_short) {
this.description_short = description_short;
}
public String getAvailable_now() {
return available_now;
}
public void setAvailable_now(String available_now) {
this.available_now = available_now;
}
public String getAvailable_later() {
return available_later;
}
public void setAvailable_later(String available_later) {
this.available_later = available_later;
}
public String getLink_rewrite() {
return link_rewrite;
}
public void setLink_rewrite(String link_rewrite) {
this.link_rewrite = link_rewrite;
}
public String getMeta_description() {
return meta_description;
}
public void setMeta_description(String meta_description) {
this.meta_description = meta_description;
}
public String getMeta_keywords() {
return meta_keywords;
}
public void setMeta_keywords(String meta_keywords) {
this.meta_keywords = meta_keywords;
}
public String getMeta_title() {
return meta_title;
}
public void setMeta_title(String meta_title) {
this.meta_title = meta_title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId_image() {
return id_image;
}
public void setId_image(String id_image) {
this.id_image = id_image;
}
public String getLegend() {
return legend;
}
public void setLegend(String legend) {
this.legend = legend;
}
public String getManufacturer_name() {
return manufacturer_name;
}
public void setManufacturer_name(String manufacturer_name) {
this.manufacturer_name = manufacturer_name;
}
public String getCategory_default() {
return category_default;
}
public void setCategory_default(String category_default) {
this.category_default = category_default;
}
public String getNewX() {
return newX;
}
public void setNewX(String newX) {
this.newX = newX;
}
public String getOrderprice() {
return orderprice;
}
public void setOrderprice(String orderprice) {
this.orderprice = orderprice;
}
public int getAllow_oosp() {
return allow_oosp;
}
public void setAllow_oosp(int allow_oosp) {
this.allow_oosp = allow_oosp;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public int getAttribute_price() {
return attribute_price;
}
public void setAttribute_price(int attribute_price) {
this.attribute_price = attribute_price;
}
public double getPrice_tax_exc() {
return price_tax_exc;
}
public void setPrice_tax_exc(double price_tax_exc) {
this.price_tax_exc = price_tax_exc;
}
public double getPrice_without_reduction() {
return price_without_reduction;
}
public void setPrice_without_reduction(double price_without_reduction) {
this.price_without_reduction = price_without_reduction;
}
public int getReduction() {
return reduction;
}
public void setReduction(int reduction) {
this.reduction = reduction;
}
public boolean isSpecific_prices() {
return specific_prices;
}
public void setSpecific_prices(boolean specific_prices) {
this.specific_prices = specific_prices;
}
public int getQuantity_all_versions() {
return quantity_all_versions;
}
public void setQuantity_all_versions(int quantity_all_versions) {
this.quantity_all_versions = quantity_all_versions;
}
public int getVirtual() {
return virtual;
}
public void setVirtual(int virtual) {
this.virtual = virtual;
}
public int getPack() {
return pack;
}
public void setPack(int pack) {
this.pack = pack;
}
public int getNopackprice() {
return nopackprice;
}
public void setNopackprice(int nopackprice) {
this.nopackprice = nopackprice;
}
public boolean isCustomization_required() {
return customization_required;
}
public void setCustomization_required(boolean customization_required) {
this.customization_required = customization_required;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public String getTax_name() {
return tax_name;
}
public void setTax_name(String tax_name) {
this.tax_name = tax_name;
}
public String getImage_url() {
return image_url;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public List<?> getFeatures() {
return features;
}
public void setFeatures(List<?> features) {
this.features = features;
}
public List<?> getAttachments() {
return attachments;
}
public void setAttachments(List<?> attachments) {
this.attachments = attachments;
}
public List<?> getPackItems() {
return packItems;
}
public void setPackItems(List<?> packItems) {
this.packItems = packItems;
}
}
list_main_item.java ( the main activity ) :
package com.example.madrit.okhttp_gson_view;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class list_main_item extends AppCompatActivity {
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.item_shop_list_view);
String url = "http://77.242.25.43:8080/girogama/modules/api/mApi/v1/categories.php?action=get_products&id_category=6&page=1&products_per_page=15";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
String json = response.body().string();
Gson gson = new Gson();
model_item[] model = gson.fromJson(json , model_item[].class);
List<model_item> list = Arrays.asList(model);
final ListAdapter myadapter = new CustomItemAdapter(list_main_item.this,list);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
listview.setAdapter(myadapter);
Log.i("Item_shop_activity"," te dhenat e response");
}
});
}
});
setContentView(R.layout.activity_list__main_item);
}
}
my main xml file activity_list_main_item.xml
<?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:id="#+id/activity_item_shop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.madrit.okhttp_gson_view.list_main_item">
<ListView
android:id="#+id/item_shop_list_view"
android:layout_width="wrap_content"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
the error
the error it gaved me
Please i need help , even if i have done any other stupid error with data parsing !!
Call setContentView(R.layout.activity_list__main_item); right after super.onCreate(savedInstanceState); or before assigning/accessing any views.

Arraylist keeps overwriting the last entry i added

sorry for troubling you, i am new at android, and i need a little help. I am doing a simple ampplication in which you sign up some people to a club. What it keeps happening is that the last person i add to the arraylist overwries the old one. I really donĀ“t know what it could be. If you can help i would be grateful.
AltaSocio.java
package com.example.polideportivo1;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class AltaSocio extends Activity {
Socios nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
VariablesGlobales vb = new VariablesGlobales();
private EditText editDocumento;
private EditText editApellido;
private EditText editNombre;
private CheckBox checkBoxM;
private CheckBox checkBoxF;
private EditText editCivil;
private Spinner Nacionalidad;
private EditText Nacimiento;
private EditText Domicilio;
private Spinner Localidad;
private EditText Celular;
private EditText TelFijo;
private EditText Correo;
String miNacionalidad;
String miLocalidad;
ArrayList<Socios> socios = vb.getSocios();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alta_socio2);
editDocumento = (EditText)findViewById(R.id.editDocumento);
editApellido = (EditText)findViewById(R.id.editApellido);
editNombre = (EditText)findViewById(R.id.editNombre);
editCivil = (EditText)findViewById(R.id.editCivil);
Nacimiento = (EditText)findViewById(R.id.editNacimiento);
Domicilio = (EditText)findViewById(R.id.editDomicilio);
Celular = (EditText)findViewById(R.id.editCelular);
TelFijo = (EditText)findViewById(R.id.editFijo);
Correo = (EditText)findViewById(R.id.editCorreo);
checkBoxM = (CheckBox)findViewById(R.id.checkM);
checkBoxF = (CheckBox)findViewById(R.id.checkF);
Nacionalidad = (Spinner)findViewById(R.id.spinnerNacionalidad);
Localidad = (Spinner)findViewById(R.id.spinnerLocalidad);
final Button BtnCrear = (Button)findViewById(R.id.botonCrear);
final Button BtnCerrar = (Button)findViewById(R.id.buttonAtras);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.Nacionalidad, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
Nacionalidad.setAdapter(adapter);
Nacionalidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miNacionalidad = Nacionalidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this, R.array.Localidad, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_item);
Localidad.setAdapter(adapter2);
Localidad.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
parent.getItemAtPosition(pos);
miLocalidad = Localidad.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//another call
}
});
}
public void grabar(View v) {
nuevosSocio.setCI(Integer.parseInt(editDocumento.getText().toString()));
nuevosSocio.setApellido(editApellido.getText().toString());
nuevosSocio.setNombre(editNombre.getText().toString());
nuevosSocio.setEstadoCivil(editCivil.getText().toString());
DateFormat formateador = new SimpleDateFormat("dd/MM/yyyy");
DateFormat DataSocio;
try {
String Fecha =(Nacimiento.getText().toString());
formateador.parse(Fecha);
nuevosSocio.setFechaNacimiento(Fecha);
}
catch (ParseException e)
{
Toast g = Toast.makeText(this, "Formato Fecha no valido", Toast.LENGTH_LONG);
}
//nuevosSocio.setFechaNacimiento(Fecha);
nuevosSocio.setDomicilio(Domicilio.getText().toString());
nuevosSocio.setTelefonoCelular(Integer.parseInt(Celular.getText().toString()));
nuevosSocio.setTelefonoFijo(Integer.parseInt(TelFijo.getText().toString()));
nuevosSocio.setCorreo(Correo.getText().toString());
if (checkBoxM.isChecked()) {
nuevosSocio.setSexo("Masculino");
} else {
nuevosSocio.setSexo("Femenino");
}
nuevosSocio.setNacionalidad(miNacionalidad);
nuevosSocio.setLocalidad(miLocalidad);
socios.add(nuevosSocio);
nuevosSocio = new Socios(0,"","","","","","","","",0,0,"");
Toast t = Toast.makeText(this, "Los datos fueron grabados",
Toast.LENGTH_SHORT);
t.show();
finish();
}
}
Socio.java
package com.example.polideportivo1;
import java.sql.Date;
import android.graphics.Bitmap;
import android.widget.CheckBox;
import android.widget.ImageView;
public class Socios {
private int CI;
private String Nombre;
private String Apellido;
private String Sexo;
private String EstadoCivil;
private String Nacionalidad;
private String FechaNacimiento;
private String Domicilio;
private String Localidad;
private int TelefonoCelular;
private int TelefonoFijo;
private String DireccionCorreo;
public Socios(int CI, String Nombre, String Apellido, String Sexo, String EstadoCivil,
String Nacionalidad, String FechaNacimiento, String Domicilio, String Localidad, int TelefonoCelular, int TelefonoFijo, String DireccionCorreo) {
this.CI = CI;
this.Nombre = Nombre;
this.Apellido = Apellido;
this.Sexo = Sexo;
this.EstadoCivil = EstadoCivil;
this.Nacionalidad = Nacionalidad;
this.FechaNacimiento = FechaNacimiento;
this.Domicilio = Domicilio;
this.Localidad = Localidad;
this.TelefonoCelular = TelefonoCelular;
this.TelefonoFijo = TelefonoFijo;
this.DireccionCorreo = DireccionCorreo;
}
public int obtenerCI() {
return CI;
}
public String obtenerNombre() {
return Nombre;
}
public String obtenerApellido() {
return Apellido;
}
public String obtenerSexo() {
return Sexo;
}
public void setSexo() {
this.Sexo = Sexo;
}
public String obtenerNacionalidad() {
return Nacionalidad;
}
public String obtenerEstadoCivil() {
return EstadoCivil;
}
public String obtenerFechaNacimiento() {
return FechaNacimiento;
}
public String obtenerDomicilio() {
return Domicilio;
}
public String obtenerLocalidad() {
return Localidad;
}
public int obtenerCelular() {
return TelefonoCelular;
}
public int obtenerTelefonoFijo() {
return TelefonoFijo;
}
public String obtenerCorreo() {
return DireccionCorreo;
}
public void setCI(int parseInt) {
this.CI = parseInt;
}
public void setApellido(String string) {
this.Apellido = string;
}
public void setNombre(String string) {
this.Nombre = string;
}
public void setEstadoCivil(String string) {
this.EstadoCivil = string;
}
public void setDomicilio(String string) {
this.Domicilio = string;
}
public void setTelefonoCelular(int parseInt) {
this.TelefonoCelular = parseInt;
}
public void setTelefonoFijo(int parseInt) {
this.TelefonoFijo = parseInt;
}
public void setCorreo(String string) {
this.DireccionCorreo = string;
}
public void setSexo(String string) {
this.Sexo = string;
}
public void setNacionalidad(String miNacionalidad) {
this.Nacionalidad = miNacionalidad;
}
public void setLocalidad(String miLocalidad) {
this.Localidad = miLocalidad;
}
public void setFechaNacimiento(String string) {
this.FechaNacimiento = string;
}
}
Every time you called the grabar to add the user you have to create a new Socio object. Using the same references will only change object's content

Categories