CheckBox ListView Mysql - android

I am three days trying to solve this problem with my filter using checkbox and a ListView.
In this code I select the checkboxes the first time and they are listed correctly with the IDs of each selected category and review the IDs for another Activity called NovaActivity. OK? So far so good.
The problem is the following when I re-open the Filters Activity to make a new same unchecking checkbox with the already listed filters it keeps going to NovaAcitivty even though they are unmarked.
EX:
 1st filter selects 1 and 2;
When I send it to another it goes the 1,2;
 2nd filter I select 1 and uncheck checkbox 2;
When I send it to another it goes the 1,1,2;
How do I solve this?
NOTE: important the second time so said that I open the Filters activity the already selected checkboxes are already premarked because I write them to my remote MySQL database and I retrieve them.
If I was not very clear can ask questions at will, thank you any help already.
public class MainActivity extends AppCompatActivity {
Context context;
ArrayList<Category> array_list;
FavouriteCategoriesJsonParser categoryJsonParser;
String categoriesCsv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
new asyncTask_getCategories().execute();
}
public static class CategoryAdapter extends ArrayAdapter<Category> {
private final List<Category> list;
public CategoryAdapter(Context context, int resource, List<Category> list) {
super(context, resource, list);
this.list = list;
}
static class ViewHolder {
protected TextView categoryName;
protected CheckBox categoryCheckBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(getContext());
convertView = inflator.inflate(R.layout.row_category, null);
viewHolder = new ViewHolder();
viewHolder.categoryName = (TextView) convertView.findViewById(R.id.row_categoryname_textview);
viewHolder.categoryCheckBox = (CheckBox) convertView.findViewById(R.id.row_category_checkbox);
viewHolder.categoryCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
list.get(getPosition).setSelected(buttonView.isChecked());
if (buttonView.isChecked()) {
if (!FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.add(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"ADICONOU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
} else {
if (FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.remove(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"REMOVEU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.row_categoryname_textview, viewHolder.categoryName);
convertView.setTag(R.id.row_category_checkbox, viewHolder.categoryCheckBox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.categoryCheckBox.setTag(position);
viewHolder.categoryName.setText(list.get(position).getCategory_Name());
viewHolder.categoryCheckBox.setChecked(list.get(position).isSelected());
return convertView;
}
}
public static class FavouriteCategoriesJsonParser {
public static ArrayList<String> selectedCategories = new ArrayList<>();
public ArrayList<Category> getParsedCategories() {
String JsonFavouriteCategories = "";
ArrayList<Category> MyArraylist = new ArrayList<>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://pensoupediu.000webhostapp.com/api/filtro/getFavouriteCategories.php?id_usuario=1");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
JsonFavouriteCategories = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsonArray = new JSONArray(JsonFavouriteCategories);
for (int i = 0; i < jsonArray.length(); i++) {
Category genres = new Category();
JSONObject MyJsonObject = jsonArray.getJSONObject(i);
genres.setCateogry_id(Integer.parseInt(MyJsonObject.getString("id")));
genres.setCategory_Name(MyJsonObject.getString("nome_cat"));
genres.setSelected(Boolean.parseBoolean(MyJsonObject.getString("selected")));
MyArraylist.add(genres);
if (MyJsonObject.getString("selected").equals("true")) {
selectedCategories.add(MyJsonObject.getString("id"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return MyArraylist;
}
}
public class asyncTask_getCategories extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
#Override
protected void onPreExecute() {
dialog.setTitle("");
dialog.setMessage("Carregando...");
dialog.show();
array_list = new ArrayList<>();
categoryJsonParser = new FavouriteCategoriesJsonParser();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
array_list = categoryJsonParser.getParsedCategories();
Log.i("ISIS"," "+array_list);
return null;
}
#Override
protected void onPostExecute(Void s) {
ListView mListViewBooks = (ListView) findViewById(R.id.category_listView);
final CategoryAdapter categoryAdapter = new CategoryAdapter(context, R.layout.row_category, array_list);
mListViewBooks.setAdapter(categoryAdapter);
Button button = (Button) findViewById(R.id.selectCategoryButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
categoriesCsv = FavouriteCategoriesJsonParser.selectedCategories.toString();
categoriesCsv = categoriesCsv.substring(1, categoriesCsv.length() - 1);
if (categoriesCsv.length() > 0) {
new asyncTask_insertUpdatefavouriteCategories().execute();
} else {
Toast.makeText(context, "Por favor, selecione um filtro.", Toast.LENGTH_SHORT).show();
}
}
});
super.onPostExecute(s);
dialog.dismiss();
}
public class asyncTask_insertUpdatefavouriteCategories extends AsyncTask<Void, Void, Void> {
String response;
#Override
protected Void doInBackground(Void... params) {
response = insertUpdateCall(categoriesCsv);
return null;
}
#Override
protected void onPostExecute(Void s) {
Toast.makeText(context, categoriesCsv, Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NovaActivity.class);
intent.putExtra("filtros", response);
startActivity(intent);
super.onPostExecute(s);
}
}
}
public static String insertUpdateCall(String categoriesCsv) {
String response = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://pensoupediu.000webhostapp.com/api/filtro/insertUpdateFavouriteCategories.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id_usuario", "1"));
nameValuePairs.add(new BasicNameValuePair("favouriteCategories", categoriesCsv));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
response = EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}

Use Set instead of ArrayList:
public static Set<String> selectedCategories = new HashSet<>();
This will ensure that your selectedCategories has no duplicates.

Related

How to show only list view items which value is equal to a value in the Json

iam creating an App which should show the Sights in a Listview.
The datas are parsed from a json.
At this json there is a column which declares in which City the sight is.
Now i would like to create a kind of a filter which should check the current Cityname with the City values in my Json.
For example there is a Sight in Berlin and my current city is Berlin, the Listview should show it. If the user is in Munich and the sight is in Berlin, the listview shouldnt show this item.
I get the current cityname value from a different Activity in a TextView.
Here is my Listview Activity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity;
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
Get current city name from intent.
String currentCityName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
currentCityName = i.getExtras().getString("cityname");
...........
.................
}
Add condition to match cityName with currentCityName before adding productforloc object to ArrayList:
try {
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
String cityName = po.getString("city");
if(!cityName.equals(currentCityName)) {
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")));
}
}
} catch (JSONException e) {
e.printStackTrace();
}

ANDROID - How to use custom adapter to add jsonObject from API webservices?

is there a way to use custom adapter with jsonArray obtained from a specific link?
I getting error when I run my app with my code, what should i do??
I've tried to find a way how to do, but the examples given too scrimpy, that's why I need help here,
I've tried this code to do :
Pertanyaan.java
public class Pertanyaan {
private float ratingStar;
private String ask;
Pertanyaan(int ratingStar, String ask) {
this.ratingStar = ratingStar;
this.ask = ask;
}
float getRatingStar() {
return 0;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
}
PertanyaanAdapter.java
class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {
private AppCompatActivity activity;
private List<Pertanyaan> movieList;
PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
super(context, resource, objects);
this.activity = context;
this.movieList = objects;
}
#Override
public Pertanyaan getItem(int position) {
return movieList.get(position);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
//holder.ratingBar.getTag(position);
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(getItem(position).getRatingStar());
holder.movieName.setText(getItem(position).getAsk());
return convertView;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Pertanyaan item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
private static class ViewHolder {
private RatingBar ratingBar;
private TextView movieName;
ViewHolder(View view) {
ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
movieName = (TextView) view.findViewById(R.id.text);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Pertanyaan> listPertanyaan;
ArrayAdapter<Pertanyaan> adapter2;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
getpertanyaan get= new getpertanyaan();
get.execute();
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setOnItemClickListener(onItemClickListener());
}
private AdapterView.OnItemClickListener onItemClickListener() {
}
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list;
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();
}
#Override
protected Integer doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
}
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
result += line;
}
}
if (is != null) {
is.close();
}
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list.add(new Pertanyaan(0,jsonObject.getString("ask")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2.notifyDataSetChanged();
}
}
EDIT :
Error from logcat :
FATAL EXCEPTION: main
Process: flix.yudi.pertanyaan3, PID: 23836
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.addAll(java.util.Collection)' on a null object reference
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:156)
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Your problem is that your ArrayList is not initialized. It crashs at this point:
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list); // CRASH!
adapter2.notifyDataSetChanged();
}
To explain more, like we discussed in the comments, what you have done is to creating a new ArrayList in your asyncTask:
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list; //NEW ARRAYLIST
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();//NEW ARRAYLIST INITIALIZING
}
but still not have initialized listPertanyaan . Wether you have to use the new created arrayList like:
list.addAll(list);
in your onPostExecute(), or you have to initialize the listPertanyaan before like
listPertanyaan = new ArrayList<Pertanyaan>();
EDIT
For your second question, you should initialize your adapter and set it to listView in onPostExecute() after you get filled the arrayList. It should look like:
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setAdapter(adapter2);
}

Android - Display data from Adapter in Listview

I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}

listview is jerking on scrolling

i hv an application in which i am getting data from api,when data get loads and i tried to scroll the listview it get starts jerking,i tried to find the solution but get nothing.please help me to sort it out.
InboxActivity.java
list=(ListView)rootView.findViewById(R.id.list);
catagery = new ArrayList<ProfileInbox>();
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), fontPath);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1,
int position, long id) {
// TODO Auto-generated method stub
//arg0.getp.setBackgroundColor(Color.WHITE);
//parent.getChildAt(position).setBackgroundColor(Color.BLUE);
IsRead=true;
catagery.get(position).setRead(IsRead);
new Task().execute(url);
adapter.notifyDataSetChanged();
msg=catagery.get(position).getMessage();
dateFrom=catagery.get(position).getSentDate();
sub=catagery.get(position).getSubject();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
});
return rootView;
}
private void loadNextPageOfReviews()
{
page_no_count += 1;
new JSONAsyncTask().execute(loadMoreUrl);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please Wait, Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// ------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("inbox");
String unread_msg= jsono.getString("unread_msg");
Log.i("unreadMsg", unread_msg);
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
ProfileInbox category = new ProfileInbox();
String id = c.getString("msg_id");
String sub = c.getString("subject");
String name = c.getString("message");
String imageSetter=c.getString("sent_on");
//Log.i("id", id);
//Log.i("name", name);
//Log.i("imageSetter", imageSetter);
category.setMsgId(((JSONObject) c).getString("msg_id"));
if(unread_msg.contains(id)){
category.setRead(false);
}
else{
category.setRead(true);
}
category.setSubject(((JSONObject) c).getString("subject"));
category.setMessage(((JSONObject) c).getString("message"));
category.setSentDate(((JSONObject) c).getString("sent_on"));
//Log.i("category", category.toString());
catagery.add(category);
//Log.i("category", category.toString());
}
return true;
}
// ------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if (result == false){
Toast.makeText(getActivity(),
"Unable to fetch data from server", Toast.LENGTH_LONG)
.show();
}
else if(Blank.notice.equals("true")){
msg=catagery.get(0).getMessage();
dateFrom=catagery.get(0).getSentDate();
sub=catagery.get(0).getSubject();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
Intent i= new Intent(getActivity(),InboxDetail.class);
startActivity(i);
}
else if(Blank.notice.equals("false"))
{
//adapter.notifyDataSetChanged();
adapter = new InboxAdaptor(getActivity(),
catagery);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
InboxAdapter
public class InboxAdaptor extends BaseAdapter {
private List<ProfileInbox> originalData;
private List<ProfileInbox> filteredData;
private Context context;
public static String url;
public static String bussinessId;
public InboxAdaptor(Context context, ArrayList<ProfileInbox> Data) {
this.context = context;
this.originalData = Data;
//Log.i("originalData", Data.toString());
filteredData = new ArrayList<ProfileInbox>();
filteredData.addAll(this.originalData);
//Log.i("filterData", filteredData.toString());
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.inboxlist, null,false);
holder.coloredlay=(RelativeLayout)convertView.findViewById(R.id.coloredlay);
holder.txtWelcom = (TextView) convertView.findViewById(R.id.txtWelcom);
holder.dateTime = (TextView) convertView.findViewById(R.id.dateTime);
holder.txtdetails = (TextView) convertView.findViewById(R.id.txtdetails);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
if(filteredData.get(position).getRead()==true)
{
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}else{
holder.coloredlay.setBackgroundColor(Color.parseColor("#E5E4E2"));
}
// holder.img.setTag(position);
String fontPath = "font/Roboto-Regular.ttf";
// Loading Font Face
Typeface tf = Typeface.createFromAsset(convertView.getContext().getAssets(), fontPath);
holder.txtWelcom.setText(filteredData.get(position).getSubject());
holder.txtWelcom.setTypeface(tf);
holder.dateTime.setText(filteredData.get(position).getSentDate());
holder.dateTime.setTypeface(tf);
holder.txtdetails.setText(filteredData.get(position).getMessage());
holder.txtdetails.setTypeface(tf);
/* if(Blank.notice.equals("true")){
holder.coloredlay.setBackgroundColor(Color.WHITE);
notifyDataSetChanged();
}
*/
notifyDataSetChanged();
return convertView;
}
public static class ViewHolder {
public RelativeLayout coloredlay;
public TextView txtdetails;
public TextView dateTime;
public TextView txtWelcom;
}
Remove notifyDataSetChanged() from getView() , notifyDataSetChanged() will update adapter when the data which you provided for your adapter has been changed , but you are using that wrong when a View of your list has been changed.
Remove notifyDataSetChanged() from getView().
You dot need that here. Rather have Remove notifyDataSetChanged() in onPostExecute() call back of JSONAsyncTask
Use cachecolorHint for come out of your solution:
<ListView
android:id="#+id/listNewsMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent" >
</ListView>

Android Pull-to-Refresh doubles size of ListView on each Refresh()

Every time I pull to refresh (using chrisbanes library), my ListView gets all the "new" data appended to the end of the old data, instead of replacing it. I already checked my Json parser, which returns my ArrayList, and it's definitely NOT that I'm accidentally doubling up in the list itself.
I've tried all sorts of "notifyDataSetChanged()"'s and ".invalidate()"'s and I just cannot seem to convince my ListView to fully repopulate itself. It works correctly on orientation-shift, which I realize is a clue, but I can't seem to figure out what is different in that case.
Code below, thanks for any tips!
public class VoicemailsPME extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.voicemails_pme);
listView = (PullToRefreshListView) findViewById(R.id.pulllist);
final String username = getIntent().getExtras().getString("username");
final String password = getIntent().getExtras().getString("password");
mailboxId = getIntent().getExtras().getString("mailboxId");
m_voicemails = new ArrayList<Voicemail>();
mHandlerFirst.post(new Runnable() {
#Override
public void run() {
CheckConnectionTask CCT = new CheckConnectionTask(VoicemailsPME.this);
CCT.execute(username, password);
firstTime = false;
}
});
listView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> lv) {
lv.invalidate();
mHandler.post(new Runnable() {
#Override
public void run() {
CheckConnectionTask CCT = new CheckConnectionTask(VoicemailsPME.this);
CCT.execute(username, password);
}
});
}
});
this.m_adapter = new OrderAdapter(this, R.layout.voicemails_pme_row, m_voicemails);
listView.setAdapter(m_adapter);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_voicemails != null && m_voicemails.size() > 0){
for(int i=0;i<m_voicemails.size();i++)
m_adapter.add(m_voicemails.get(i));
}
}
};
private void getVoicemails(){
try{
//Log.d("Data right before Json Parse", data);
Json jsonParser = new Json(data);
m_voicemails = jsonParser.getVoicemailsPME();
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Voicemail> {
private ArrayList<Voicemail> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Voicemail> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Voicemail vm = items.get(position);
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.voicemails_pme_row, null);
}
if (vm != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView nm = (TextView) v.findViewById(R.id.length);
if (tt != null)
{
tt.setText(vm.getPhoneNumber());
if(vm.getNewStatus())
tt.setTypeface(null, Typeface.BOLD);
}
if(bt != null)
{
bt.setText(vm.getDate());
}
if(nm != null)
{
nm.setText(vm.getLength());
}
}
return v;
}
}
class CheckConnectionTask extends AsyncTask<String, Void, String> {
private VoicemailsPME activity;
private ProgressDialog dialog;
private Context context;
public CheckConnectionTask(VoicemailsPME activity)
{
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
String username, password, str;
#Override
protected void onPreExecute() {
if(firstTime)
{
this.dialog.setMessage("Loading...");
this.dialog.show();
}
}
#Override
protected String doInBackground(String...arg0)
{
username = arg0[0];
password = arg0[1];
DefaultHttpClient httpclient = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials(username, password);
httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
try{
HttpPost post = new HttpPost("https://www.my.patlive.com/api/v1.0/Mailbox/" + mailboxId + "/messages?format=json");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(post);
str = inputStreamToString(response.getEntity().getContent()).toString();
if(str.contains("\"ErrorCode\":0"))
{
//data = str;
return str;
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();}
return str;
}
#Override
protected void onPostExecute(String newData)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
data = newData;
getVoicemails();
m_adapter.notifyDataSetChanged();
listView.onRefreshComplete();
}
}
}
I think that your getVoicemail() method is the culprit.
Because of the way that the adapter works, it's using the backing array you provided originally (m_voicemails), and when you refresh it you create a new list but the original one is not cleared and then you just add on top of that.
public void run() {
//Try adding m_adapter.clear() here
if(m_voicemails != null && m_voicemails.size() > 0){
for(int i=0;i<m_voicemails.size();i++)
m_adapter.add(m_voicemails.get(i));
}
}
I've found that it's clearer to keep a list of the data separate from your adapter and then just feed that data into the adapter (using a set instead of an add).

Categories

Resources