How to display items in custom adapter android - android

Hi I need to store items in custom adapter but I got issue while creating custom adapter. Please help me to resolve.
private class Cast extends AsyncTask<Object, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(Detailed_View.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
private final String KeY = "";
private static final String DEBUG_TAG = "TM";
#Override
protected ArrayList<String> doInBackground(Object... params) {
try {
return getCast();
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(ArrayList<String> results_Cast) {
updateListOfCast(results_Cast);
dialog.cancel();
};
public ArrayList<String> getCast() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("https://themovie/3/movie/" + id
+ "/credit");
stringBuilder.append("?key=" + key);
URL url = new URL(stringBuilder.toString());
// Log.d("urlstring",stringBuilder.toString() );
InputStream stream = null;
try {
// Establish a connection
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.addRequestProperty("Accept", "application/json"); // Required
// to
// get
// TMDB
// to
// play
// nicely.
conn.setDoInput(true);
conn.connect();
int responseCode = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response code is: " + responseCode + " "
+ conn.getResponseMessage());
stream = conn.getInputStream();
return parseCast(stringify(stream));
} finally {
if (stream != null) {
stream.close();
}
}
}
private ArrayList<String> parseCast(String result) {
String streamAsString = result;
ArrayList<String> results_Cast = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("cast");
Log.d("array view", array.toString());
for (int i = 0; i < array.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonMovieObject = array.getJSONObject(i);
results_Cast.add(jsonMovieObject.getString("name"));
ids=jsonMovieObject.getString("id");
results_Cast.add(jsonMovieObject.getString("character"));
}
} catch (JSONException e) {
Log.d("e", e.toString());
Log.d(DEBUG_TAG, "Error parsing JSON. String was: "
+ streamAsString);
}
// Log.d("resulted", results_Cast.toString());
return results_Cast;
}
public String stringify(InputStream stream) throws IOException,
UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
return bufferedReader.readLine();
}
}
// displays cast
public void updateListOfCast(ArrayList<String> result) {
ListView listView = (ListView) findViewById(R.id.cast_details);
//Log.d("updateViewWithResults", result.toString());
// Add results to listView.
listView.setAdapter(adapter);
Helper.getListViewSize(listView);
gridAdapter = new GridAdapter(this, R.layout.test_row, result); // here I have issue.
listView.setAdapter(gridAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long idss) {
// TODO Auto-generated method stub
String name = (String) parent.getItemAtPosition(position);
Toast.makeText(Detailed_View.this, name+"Id"+ids, Toast.LENGTH_SHORT)
.show();
}
});
public class GridAdapter extends BaseAdapter {
public GridAdapter(Activity a, int resource, ArrayList<String> result) { // here it displays error as The blank final field itemLists may not have been initialized
layoutInflater = (LayoutInflater) a
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
results=result;
activity=a;
loader=new ImageLoader(a.getApplicationContext());
}
}
How to get items of name, id and character to display in custom adapter?

You have to overide all methods..
Example
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}

Related

how to update Expandable Listview with new items?(notifyDataSetChanged()not works)

I have expandable Lisview and i load the data to listview from server.
And there are some rows with edittext. so whenever i pressed right button for edit,
edittext is focusable and edit that value and again pressed on that button value will goes to sever.
But from this it did not save it,Its again restore original value.
But when i am refreshing same activity value got changed.
How to load the Expandable listview with new editable values?
Here is my Code:-This is my activity
public class EditSwitch1Activity extends AppCompatActivity {
ExpandableListAdapter1 listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
SharedPreferences pref;
SharedPreferences.Editor editor;
private TextView edit_text;
HashMap<String, List<String>> listDataChild;
private TextView back;
private String roomId;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editswitch1);
pref = PreferenceManager.getDefaultSharedPreferences(EditSwitch1Activity.this);
editor = pref.edit();
expListView = (ExpandableListView) findViewById(R.id.lvExp);
back = (TextView) findViewById(R.id.back);
expListView.setItemsCanFocus(true);
// preparing list data
Window window = EditSwitch1Activity.this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(EditSwitch1Activity.this.getResources().getColor(R.color.color_statusbar));
roomId = getIntent().getStringExtra("roomId");
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + roomId;
// Use AsyncTask execute Method To Prevent ANR11 Problem
new LongOperation1().execute(serverURL);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private class LongOperation1 extends AsyncTask<String, Void, Void> {
// Required initialization
// private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(
EditSwitch1Activity.this);
String data = "";
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Dialog.setMessage("Please wait..");
//Dialog.show();
// data += "Authorization:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA";
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
// String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setDoOutput(true);
String auth_token = pref.getString("auth_token", "");
conn.setRequestProperty("Authorization", auth_token);
//conn.setRequestMethod("GET");
//byte[] encodedPassword = ( "Authorization" + ":" + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA" ).getBytes();
//BASE64Encoder encoder = new BASE64Encoder();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
// Content=Content.replaceAll("<string>","");
// Content=Content.replaceAll("</string>", "");
Dialog.dismiss();
if (Error != null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Bad request", Toast.LENGTH_LONG);
toast.show();
// uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
// uiUpdate.setText(Content);
/****************** Start Parse Response JSON Data *************/
// String OutputData = "";
// JSONObject jsonResponse;
Gson gson = new Gson();
// Map messageObjMap = new Gson().fromJson(Content, Map.class);
// String type = messageObjMap.get("messageType").toString();
// Song song = gson.fromJson(message, Song.class);
final SearchResponse response = gson.fromJson(Content,
SearchResponse.class);
if (response.getStatus() == true) {
List<String> newlist = new ArrayList<String>();
for (int i = 0; i < response.getModule().length; i++) {
listDataHeader.add(response.getModule()[i].getModule_name());
newlist = new ArrayList<String>();
for (int j = 0; j < response.getModule()[i].getNo_of_switches(); j++) {
if (response.getModule()[i].getModuleId().getModuleid().equals(response.getModule()[i].getSwitches()[j].getModuleId().getModuleid())) {
newlist.add(response.getModule()[i].getSwitches()[j].getSwitch_name());
}
listDataChild.put(response.getModule()[i].getModule_name(), newlist);
}
}
listAdapter = new ExpandableListAdapter1(EditSwitch1Activity.this, listDataHeader, listDataChild, response);
// setting list adapter
expListView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "status:-" + response.getStatus(), Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onResume() {
super.onResume();
}
}
Also Attched the Expandable Listview Adapater:-
public class ExpandableListAdapter1 extends BaseExpandableListAdapter {
private String childText;
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private ArrayList<String> newlist;
private ArrayList<String> newlist1;
ArrayList<String>list1;
private SearchResponse response;
private Boolean onclick = true;
public ExpandableListAdapter1(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData, SearchResponse response) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.response = response;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
childText = (String) getChild(groupPosition, childPosition);
final ViewHolder holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtListChild.setText(childText); // Here whatever you will type in edittext will be overwritten by the value of 'childText.getTotal'. So after you are done writing in edit text make sore you change that in "_listDataChild" list.
newlist = new ArrayList<String>();
newlist1 = new ArrayList<String>();
list1=new ArrayList<>();
list1.add(childText);
final TextView txtListChild1 = (TextView) convertView
.findViewById(R.id.flash1);
txtListChild1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onclick) {
txtListChild1.setText("Save");
holder.txtListChild.setEnabled(true);
onclick = false;
} else {
// ArrayList<String> itemList=new ArrayList<String>();
//itemList.add();
onclick = true;
txtListChild1.setText("Edit");
holder.txtListChild.setEnabled(false);
newlist.add(response.getModule()[groupPosition].getSwitches()[childPosition].getSwitchId().getId());
newlist1.add(holder.txtListChild.getText().toString());
String url = "http://dashboard.droidhomes.in/api/switch";
RequestQueue requestQueue = Volley.newRequestQueue(_context);
JSONObject dataObj = new JSONObject();
try {
JSONArray cartItemsArray = new JSONArray();
JSONObject cartItemsObjedct;
for(int i=0;i<newlist.size();i++){
cartItemsObjedct = new JSONObject();
cartItemsObjedct.putOpt("switch_id", newlist.get(i));
cartItemsObjedct.putOpt("switch_name",newlist1.get(i));
cartItemsArray.put(cartItemsObjedct);
}
dataObj.put("update_list", cartItemsArray);
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.PUT, url, dataObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(_context, response.getString("status"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//mTextView.setText(error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA");
headers.put("Content-Type", "application/json");
return headers;
}
};
requestQueue.add(jsonArrayRequest);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
notifyDataSetChanged();
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
class ViewHolder {
EditText txtListChild;
public ViewHolder(View v) {
txtListChild = (EditText) v.findViewById(R.id.lblListItem);
}
}
public HashMap<String,List<String>> gethashmap() {
return _listDataChild;
}
}
Here ,In this adapter i used gethashmap() method which call from activity so it load with fresh data but don't know how to do this.
Replace your code with following modified code :
public class EditSwitch1Activity extends AppCompatActivity {
ExpandableListAdapter1 listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
SharedPreferences pref;
SharedPreferences.Editor editor;
private TextView edit_text;
HashMap<String, List<String>> listDataChild;
private TextView back;
private String roomId;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editswitch1);
pref = PreferenceManager.getDefaultSharedPreferences(EditSwitch1Activity.this);
editor = pref.edit();
expListView = (ExpandableListView) findViewById(R.id.lvExp);
back = (TextView) findViewById(R.id.back);
expListView.setItemsCanFocus(true);
// preparing list data
Window window = EditSwitch1Activity.this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(EditSwitch1Activity.this.getResources().getColor(R.color.color_statusbar));
roomId = getIntent().getStringExtra("roomId");
String serverURL = "http://dashboard.droidhomes.in/api/module?room_id=" + roomId;
// Use AsyncTask execute Method To Prevent ANR11 Problem
new LongOperation1().execute(serverURL);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
listAdapter = new ExpandableListAdapter1(EditSwitch1Activity.this, listDataHeader, listDataChild, response);
// setting list adapter
expListView.setAdapter(listAdapter);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private class LongOperation1 extends AsyncTask<String, Void, Void> {
// Required initialization
// private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(
EditSwitch1Activity.this);
String data = "";
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Dialog.setMessage("Please wait..");
//Dialog.show();
// data += "Authorization:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA";
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader = null;
// final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
// String urlEncoded = Uri.encode(path, ALLOWED_URI_CHARS);
// Send data
try {
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setDoOutput(true);
String auth_token = pref.getString("auth_token", "");
conn.setRequestProperty("Authorization", auth_token);
//conn.setRequestMethod("GET");
//byte[] encodedPassword = ( "Authorization" + ":" + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA" ).getBytes();
//BASE64Encoder encoder = new BASE64Encoder();
// Get the server response
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
// Content=Content.replaceAll("<string>","");
// Content=Content.replaceAll("</string>", "");
Dialog.dismiss();
if (Error != null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Bad request", Toast.LENGTH_LONG);
toast.show();
// uiUpdate.setText("Output : " + Error);
} else {
// Show Response Json On Screen (activity)
// uiUpdate.setText(Content);
/****************** Start Parse Response JSON Data *************/
// String OutputData = "";
// JSONObject jsonResponse;
Gson gson = new Gson();
// Map messageObjMap = new Gson().fromJson(Content, Map.class);
// String type = messageObjMap.get("messageType").toString();
// Song song = gson.fromJson(message, Song.class);
final SearchResponse response = gson.fromJson(Content,
SearchResponse.class);
if (response.getStatus() == true) {
List<String> newlist = new ArrayList<String>();
listDataHeader.clear() ;
listDataChild.clear();
for (int i = 0; i < response.getModule().length; i++) {
listDataHeader.add(response.getModule()[i].getModule_name());
newlist = new ArrayList<String>();
for (int j = 0; j < response.getModule()[i].getNo_of_switches(); j++) {
if (response.getModule()[i].getModuleId().getModuleid().equals(response.getModule()[i].getSwitches()[j].getModuleId().getModuleid())) {
newlist.add(response.getModule()[i].getSwitches()[j].getSwitch_name());
}
listDataChild.put(response.getModule()[i].getModule_name(), newlist);
}
}
//listAdapter = new ExpandableListAdapter1(EditSwitch1Activity.this, listDataHeader, listDataChild, response);
listAdapter.setListDataHeader(listDataHeader) ;
listAdapter.setListDataChild(listDataChild) ;
listAdapter.setSearchResponse(response) ;
listAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getApplicationContext(), "status:-" + response.getStatus(), Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onResume() {
super.onResume();
}
Adapter class
public class ExpandableListAdapter1 extends BaseExpandableListAdapter {
private String childText;
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private ArrayList<String> newlist;
private ArrayList<String> newlist1;
ArrayList<String>list1;
private SearchResponse response;
private Boolean onclick = true;
public ExpandableListAdapter1(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData, SearchResponse response) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
this.response = response;
}
public void setListDataHeader(List<String> list){
this._listDataHeader = list;
}
public void setListDataChild(List<String> list){
this._listDataChild = list;
}
public void setSearchResponse(SearchResponse response){
this.response = response;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
childText = (String) getChild(groupPosition, childPosition);
final ViewHolder holder;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtListChild.setText(childText); // Here whatever you will type in edittext will be overwritten by the value of 'childText.getTotal'. So after you are done writing in edit text make sore you change that in "_listDataChild" list.
newlist = new ArrayList<String>();
newlist1 = new ArrayList<String>();
list1=new ArrayList<>();
list1.add(childText);
final TextView txtListChild1 = (TextView) convertView
.findViewById(R.id.flash1);
txtListChild1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onclick) {
txtListChild1.setText("Save");
holder.txtListChild.setEnabled(true);
onclick = false;
} else {
// ArrayList<String> itemList=new ArrayList<String>();
//itemList.add();
onclick = true;
txtListChild1.setText("Edit");
holder.txtListChild.setEnabled(false);
newlist.add(response.getModule()[groupPosition].getSwitches()[childPosition].getSwitchId().getId());
newlist1.add(holder.txtListChild.getText().toString());
String url = "http://dashboard.droidhomes.in/api/switch";
RequestQueue requestQueue = Volley.newRequestQueue(_context);
JSONObject dataObj = new JSONObject();
try {
JSONArray cartItemsArray = new JSONArray();
JSONObject cartItemsObjedct;
for(int i=0;i<newlist.size();i++){
cartItemsObjedct = new JSONObject();
cartItemsObjedct.putOpt("switch_id", newlist.get(i));
cartItemsObjedct.putOpt("switch_name",newlist1.get(i));
cartItemsArray.put(cartItemsObjedct);
}
dataObj.put("update_list", cartItemsArray);
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.PUT, url, dataObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(_context, response.getString("status"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//mTextView.setText(error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Ijk5MjEyMzQ4MTMiLCJyb2xlIjoiY3VzdG9tZXIiLCJpZCI6IjU4M2VhZjI0OWM1ZDM5MTgyMzk0MTkzNyIsIm5hbWUiOiJWaWpheSBNYWxob3RyYSJ9.aF-vgNvOSSk_mbi_cTGufG2JZRrmP38zPFGn9UK9iMA");
headers.put("Content-Type", "application/json");
return headers;
}
};
requestQueue.add(jsonArrayRequest);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
class ViewHolder {
EditText txtListChild;
public ViewHolder(View v) {
txtListChild = (EditText) v.findViewById(R.id.lblListItem);
}
}
public HashMap<String,List<String>> gethashmap() {
return _listDataChild;
}

OnPost Execute method how can I pass image from one Fragment to other activity. Able to pass the image from drawable folder using Bundle

OnPost Execute method how can I pass image from one Fragment to other activity. Able to pass the image from drawable folder using Bundle. Loding product details from server and able to other information except Image to other Activity.
package sanjay.apackage.torcente.com.torcentemotors;
public class HomeFragment extends Fragment {
FragmentTransaction fragmentTransaction;
//private TextView tvData;
private ListView lvMovies;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
//Image loader
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()) //getApplicationContext()
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView)view.findViewById(R.id.lvMovies);
new JSONTask().execute("http://torcentemotors.com/app_001/productsInfoNew.php");
return view;
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel> > {
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null ) {
buffer.append(line);
}
//return buffer.toString();
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for(int i = 0; i< parentArray.length() ;i++ ) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setProduct_name(finalObject.getString("product_name"));
movieModel.setProduct_price(finalObject.getInt("product_price"));
movieModel.setProduct_image(finalObject.getString("product_image"));
movieModel.setProduct_color(finalObject.getString("product_color"));
movieModel.setCover_image(finalObject.getString("cover_image"));
movieModel.setOriginal_price(finalObject.getInt("original_price"));
movieModel.setApp_desc(finalObject.getString("app_desc"));
//adding the final object to the list
movieModelList.add(movieModel);
}
//return finalBufferedData.toString();
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if( connection != null){
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
final MovieAdapter adapter = new MovieAdapter( getActivity().getApplicationContext(), R.layout.rownew, result );
//// getApplicationContext() // getActivity is added by me
lvMovies.setAdapter(adapter);
//set data to list
lvMovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getActivity().getBaseContext(),parent.getItemIdAtPosition(position)+" is selected",Toast.LENGTH_LONG).show();
MovieModel movieModel = (MovieModel) adapter.getItem(position);
Intent intent = new Intent("sanjay.apackage.torcente.com.torcentemotors.product_details");
//intent.putExtra("product_image", movieModel.getProduct_image());
//sanjay //
intent.putExtra("id",position);
intent.putExtra("product_name",movieModel.getProduct_name());
intent.putExtra("product_price", movieModel.getProduct_price());
intent.putExtra("product_color", movieModel.getProduct_color());
intent.putExtra("original_price", movieModel.getOriginal_price());
intent.putExtra("app_desc", movieModel.getApp_desc());
Bundle bundle=new Bundle();
bundle.putInt("image",R.drawable.ban);
bundle.putInt("image2",R.drawable.fz25);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
public class MovieAdapter extends ArrayAdapter{
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater ;
public MovieAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource ;
inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE); // context is added by me.
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
viewHolder holder = null;
if (convertView == null ) {
holder = new viewHolder();
convertView = inflater.inflate(resource, null);
holder.tvIcon = (ImageView)convertView.findViewById(R.id.tvIcon);
holder.tvcover = (ImageView)convertView.findViewById(R.id.tvcover);
holder.tvproduct_name = (TextView)convertView.findViewById((R.id.tvproduct_name));
holder.tvproduct_price = (TextView)convertView.findViewById((R.id.tvproduct_price));
holder.tvproduct_color = (TextView)convertView.findViewById((R.id.tvproduct_color));
holder.tvoriginal_price = (TextView)convertView.findViewById((R.id.tvoriginal_price));
holder.tvapp_desc = (TextView)convertView.findViewById((R.id.tvapp_desc));
convertView.setTag(holder);
} else{
holder = (viewHolder)convertView.getTag();
}
ImageLoader.getInstance().displayImage(movieModelList.get(position).getProduct_image(), holder.tvIcon);
ImageLoader.getInstance().displayImage(movieModelList.get(position).getCover_image(), holder.tvcover);
//holder.tvproduct_id.setText(" Product ID : " +movieModelList.get( position ).getProduct_id());
//holder.tvcategory_id.setText("Category ID : " +movieModelList.get(position).getCategory_id());
//holder.tvsub_category_id.setText("Sub Category ID : " +movieModelList.get(position).getSub_category_id());
holder.tvproduct_name.setText(movieModelList.get(position).getProduct_name());
//holder.tvproduct_code.setText(movieModelList.get(position).getProduct_code());
holder.tvproduct_price.setText("BookingPrice : "+movieModelList.get(position).getProduct_price());
holder.tvproduct_color.setText(movieModelList.get(position).getProduct_color());
holder.tvoriginal_price.setText("Price : "+movieModelList.get(position).getOriginal_price());
//holder.tvapp_desc.setText(movieModelList.get(position).getApp_desc());
return convertView;
}
class viewHolder{
private ImageView tvIcon ;
private ImageView tvcover ;
private TextView tvproduct_id;
private TextView tvcategory_id;
private TextView tvsub_category_id;
private TextView tvproduct_name;
private TextView tvproduct_code;
private TextView tvproduct_color;
private TextView tvproduct_price;
private TextView tvoriginal_price;
private TextView tvapp_desc;
}
}
}

Call BaseAdapter In Fragment Close Application

Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");

Custom Listview Loops through all images in first listItem

i have a list view that is populated from a database with a customlistview...everything works fine except when i first start activity, the first item on the list view, loops through all images and then sets each image to corresponding item. I cannot figure out what i am doing wrong. pls help. I have gone through al the answers on stackoverflow but nothing works for me. Here is my custom list view:
***Edit:This code is working fine now. I fixed it.
public class FriendsListView extends ArrayAdapter<FriendsRowItem> {
Context context;
ArrayList<FriendsRowItem> infoList;
private LayoutInflater inflater = null;
int Resource;
ViewHolder holder;
public FriendsListView(Context context, int resourceId,
ArrayList<FriendsRowItem> items) {
super(context, resourceId, items);
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resourceId;
infoList = items;
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
}
public int getCount() {
return infoList.size();
}
public RowItem getItem(RowItem position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) {
vi = inflater.inflate(R.layout.list_item_3, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) vi.findViewById(R.id.title3);
holder.imageView = (ImageView) vi.findViewById(R.id.icon3);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txtTitle.setText(infoList.get(position).getTitle());
holder.imageView.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageView).execute(infoList.get(position)
.getImage());
return vi;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
int position;
public DownloadImageTask(ImageView bmImage, int position) {
this.bmImage = bmImage;
this.position = position;
bmImage.setTag(position);
bmImage.setImageBitmap(null);
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = (InputStream) new java.net.URL(urldisplay)
.getContent();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
// Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
if (result != null && (bmImage.getTag()).equals(this.position))
bmImage.setImageBitmap(result);
bmImage.setImageBitmap(result);
}
}
And how i populate my list view using JSON:
class RetrieveFriendsTask extends AsyncTask<Void, Void, Void> {
ArrayList<FriendsRowItem> FriendList = new ArrayList<FriendsRowItem>();
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pDialog != null) {
pDialog.dismiss();
}
// Showing progress dialog
else {
pDialog = new ProgressDialog(Friends.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("eposta", email));
pairs.add(new BasicNameValuePair("sifre", pass));
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET, pairs);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONObject obj = jsonObj.getJSONObject("data");
friends = obj.getJSONArray(TAG_EVENTS);
for (int i = 0; i < friends.length(); i++) {
friend = new FriendsRowItem();
JSONObject c = friends.getJSONObject(i);
nick = c.optString("nick");
// friend.setTitle(c.optString("nick"));
img = c.optString("url_resim");
// friend.setImage(c.optString("url_resim"));
friend.setTitle(nick);
friend.setImage(img);
FriendList.add(friend);
}
}
catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(Void result) {
if (pDialog.isShowing())
pDialog.dismiss();
adapter = new FriendsListView(Friends.this, R.layout.list_item_3,
FriendList);
lvfriends.setAdapter(adapter);
OnItemClickListener myListViewClicked = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
FriendsRowItem name = (FriendsRowItem) parent
.getItemAtPosition(position);
Intent i = new Intent(Friends.this, FriendsDisplay.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("FriendName", name.toString());
startActivity(i);
}
};
lvfriends.setOnItemClickListener(myListViewClicked);
}
}
I would really appreciate the help.

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>

Categories

Resources