How to add adapter2 with asynctask inside adapter1 - android

I've this adapter class :
public class NoteFeedListAdapter extends RecyclerView.Adapter<feedItemsHolder>{
private Activity activity;
private LayoutInflater inflater;
private List<NoteFeedItem> feedItems;
private List<CommentModel> commentItems;
private NoteCommentListAdapter adapter;
private RecyclerView mRecyclerView;
ImageLoader imageLoader = NoteAppController.getInstance().getImageLoader();
private static final String URL_LIST_VIEW_COMMENT = "http://url.com";
private int level = 0;
private Context mContext;
public NoteFeedListAdapter(Context context, List<NoteFeedItem> feedItems) {
this.feedItems = feedItems;
this.mContext = context;
}
public feedItemsHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.feed_item, null);
feedItemsHolder mh = new feedItemsHolder(v);
return mh;
}
public void onBindViewHolder(final feedItemsHolder fItemsHolder, final int i) {
final NoteFeedItem item = feedItems.get(i);
fItemsHolder.setLevel(item.getLevel());
if (item.getName2() != null) {
fItemsHolder.mHiddenComment.setText(item.getName2()+": "+item.getComment2());
fItemsHolder.feedImageView.setVisibility(View.VISIBLE);
and Inside onBindViewHolder :
int jComment = Integer.parseInt(item.getJumlahComment().toString());
if( jComment > 0){
fItemsHolder.mHiddenComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//this code is what I used to call asyntask but result from asynctask cannot be shown in this adapter
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView = new RecyclerView(mContext);
getListViewComments(item.getUserid(), item.getId(),fItemsHolder,i, commentItems, adapter, mRecyclerView);
commentItems = new ArrayList<CommentModel>();
adapter = new NoteCommentListAdapter(mContext, commentItems);
mRecyclerView.setAdapter(adapter);
}
});
}
...
} else {
fItemsHolder.mHiddenComment.setVisibility(View.GONE);
fItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
}
if(item.getLevel() == Level.LEVEL_ONE){
level = Level.LEVEL_TWO;
}else if(item.getLevel() == Level.LEVEL_TWO){
level = Level.LEVEL_THREE;
}
}
public int getItemCount() {
return (null != feedItems ? feedItems.size() : 0);
}
private void getListViewComments(final String userid, String id_note,final feedItemsHolder feedItemsHolder, int i, final List<CommentModel> commentItems, final NoteCommentListAdapter adapter, final RecyclerView mRecyclerView) {
class ambilComment extends AsyncTask<String, Void, String> {
ProgressDialog loading;
com.android.personal.asynctask.profileSaveDescription profileSaveDescription = new profileSaveDescription();
String result = "";
InputStream inputStream = null;
#Override
protected void onPreExecute() {
feedItemsHolder.mLoading.setVisibility(View.GONE);
feedItemsHolder.mHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLinearHiddenComment.setVisibility(View.GONE);
feedItemsHolder.mLoading.setVisibility(View.VISIBLE);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("userid", params[0]);
data.put("id_note", params[1]);
String result = profileSaveDescription.sendPostRequest(URL_LIST_VIEW_COMMENT,data);
return result;
}
protected void onPostExecute(String s) {
JSONArray dataJsonArr = null;
if(s.equals(null)){
Toast.makeText(mContext, "Internet Problem.", Toast.LENGTH_SHORT).show();
}else{
try{
JSONObject json = new JSONObject(s);
String id_note = json.getString("id_note");
Toast.makeText(mContext, id_note, Toast.LENGTH_SHORT).show();
dataJsonArr = json.getJSONArray("data");
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
String id_comment = c.getString("id_comment");
String uid = c.getString("userid");
String profile_name = c.getString("profile_name");
String profile_photo = c.getString("profile_photo");
String amount_of_like = c.getString("amount_of_like");
String amount_of_dislike = c.getString("amount_of_dislike");
String amount_of_comment = c.getString("amount_of_comment");
String content_comment = c.getString("content_comment");
String tgl_comment = c.getString("tgl_comment");
String parent_id = c.getString("parent_id");
CommentModel citem = new CommentModel();
citem.setId_note(id_note);
citem.setId_comment(id_comment);
citem.setUserid(uid);
citem.setProfileName(profile_name);
String pPhoto = c.isNull("profile_photo") ? null : c.getString("profile_photo");
citem.setProfile_photo(pPhoto);
citem.setJumlahLove(amount_of_like);
citem.setJumlahNix(amount_of_dislike);
citem.setJumlahComment(amount_of_comment);
citem.setContent_comment(content_comment);
citem.setTimeStamp(tgl_comment);
String prntID = c.isNull("parent_id") ? null : c.getString("parent_id");
citem.setParent_id(prntID);
citem.setLevel(level);
commentItems.add(citem);
}
adapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
Log.w("getListNotesComment", "exception");
}
}
/* iH.mHiddenComment.setText("");*/
}
}
ambilComment ru = new ambilComment();
ru.execute(userid, id_note);
}
The problem is that I wanna add data from Asynctask and shown on another adapter. But how can i do that? please help. view from another adapter couldn't show with this code.

Related

Return button to previous activity with BaseAdapter

I currently have two activities doing HTTP requests.
The first activity contains a CustomList class extends BaseAdapter.
On the second, there is a previous button allowing me to return to the first activity.
Returning to the first activity, I would like to be able to recover the state in which I left it. That is to say to be able to find the information which also come from an HTTP request. I would like to find the data "infos_user" which is in the first activity and all the data in the BaseAdapter.
My architecture is as follows: Activity 0 (HTTP request) -> Activity 1 (with BaseAdapter and HTTP request) -> Activity 2 (HTTP request)
I put all the code because I really don't know how can I do this :/
First activity:
public class GetChildrenList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Child> childrenImeList = new ArrayList<Child>();
private Button btn_previous;
private ListView itemsListView;
private TextView tv_signin_success;
int id = 0;
String infos_user;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_children_list);
infos_user = (String) getIntent().getSerializableExtra("infos_user");
Intent intent = new Intent(GetChildrenList.this , GetLearningGoalsList.class);
intent.putExtra("username", infos_user);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
tv_signin_success = (TextView) findViewById(R.id.tv_signin_success);
tv_signin_success.setText("Bonjour " + infos_user + "!");
itemsListView = (ListView)findViewById(R.id.list_view_children);
new GetChildrenAsync().execute();
}
class GetChildrenAsync extends AsyncTask<String, Void, ArrayList<Child>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetChildrenList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<Child> doInBackground(String... params) {
int age = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
String first_name = null;
String last_name = null;
try {
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/childrenime/list", "GET", true, email, password);
String jsonResult = "{ \"children\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray childrenArray = jsonObject.getJSONArray("children");
for (int i = 0; i < childrenArray.length(); ++i) {
JSONObject child = childrenArray.getJSONObject(i);
id = child.getInt("id");
first_name = child.getString("first_name");
last_name = child.getString("last_name");
age = child.getInt("age");
String name = first_name + " " + last_name;
childrenImeList.add(new Child(id,name,age));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenImeList;
}
#Override
protected void onPostExecute(final ArrayList<Child> childrenListInformation) {
loadingDialog.dismiss();
if(childrenListInformation.size() > 0) {
CustomListChildrenAdapter adapter = new CustomListChildrenAdapter(GetChildrenList.this, childrenListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des enfants", Toast.LENGTH_LONG).show();
}
}
}
}
BaseAdapter:
public class CustomListChildrenAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private ArrayList<Child> children;
private Button btnChoose;
private TextView childrenName;
private TextView childrenAge;
public CustomListChildrenAdapter(Context context, ArrayList<Child> children) {
this.context = context;
this.children = children;
}
#Override
public int getCount() {
return children.size(); //returns total item in the list
}
#Override
public Object getItem(int position) {
return children.get(position); //returns the item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_list_view_children,null);
childrenName = (TextView)view.findViewById(R.id.tv_childrenName);
childrenAge = (TextView) view.findViewById(R.id.tv_childrenAge);
btnChoose = (Button) view.findViewById(R.id.btn_choose);
btnChoose.setOnClickListener(this);
} else {
view = convertView;
}
btnChoose.setTag(position);
Child currentItem = (Child) getItem(position);
childrenName.setText(currentItem.getChildName());
childrenAge.setText(currentItem.getChildAge() + "");
return view;
}
#Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
Child item = (Child) getItem(position);
String email = (String) ((Activity) context).getIntent().getSerializableExtra("email");
String password = (String) ((Activity) context).getIntent().getSerializableExtra("password");
Intent intent = new Intent(context, GetLearningGoalsList.class);
intent.putExtra("idChild",item.getId());
intent.putExtra("email",email);
intent.putExtra("password",password);
context.startActivity(intent);
}
}
Second Activity:
public class GetLearningGoalsList extends AppCompatActivity implements View.OnClickListener {
private ArrayList<LearningGoal> childrenLearningList = new ArrayList<LearningGoal>();
private Button btn_previous;
private ListView itemsListView;
String email;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_learning_goals_list);
btn_previous = (Button) findViewById(R.id.btn_previous);
btn_previous.setOnClickListener(this);
itemsListView = (ListView)findViewById(R.id.list_view_learning_goals);
new GetLearningGoalsAsync().execute();
}
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
class GetLearningGoalsAsync extends AsyncTask<String, Void, ArrayList<LearningGoal>> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(GetLearningGoalsList.this, "Please wait", "Loading...");
}
#Override
protected ArrayList<LearningGoal> doInBackground(String... params) {
int id = 0;
email = (String) getIntent().getSerializableExtra("email");
password = (String) getIntent().getSerializableExtra("password");
int idChild = (int) getIntent().getSerializableExtra("idChild");
String name = null;
String start_date = null;
String end_date = null;
try {
List<BasicNameValuePair> parameters = new LinkedList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("idchild", Integer.toString(idChild)));
SendRequest sr = new SendRequest();
String result = sr.sendHttpRequest("http://" + sr.getIP_ADDRESS() + "/learningchild/list"+ "?"+ URLEncodedUtils.format(parameters, "utf-8"), "POST", true, email, password);
String jsonResult = "{ \"learningGoals\":" + result + "}";
Log.d("result1", jsonResult);
//Manage JSON result
JSONObject jsonObject = new JSONObject(jsonResult);
JSONArray learningGoalsArray = jsonObject.getJSONArray("learningGoals");
for (int i = 0; i < learningGoalsArray.length(); ++i) {
JSONObject learningGoal = learningGoalsArray.getJSONObject(i);
id = learningGoal.getInt("id");
name = learningGoal.getString("name");
start_date = learningGoal.getString("start_date");
end_date = learningGoal.getString("end_date");
childrenLearningList.add(new LearningGoal(id,name,start_date,end_date));
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenLearningList;
}
#Override
protected void onPostExecute(final ArrayList<LearningGoal> learningListInformation) {
loadingDialog.dismiss();
if(learningListInformation.size() > 0) {
CustomListLearningGoalAdapter adapter = new CustomListLearningGoalAdapter(GetLearningGoalsList.this, learningListInformation);
itemsListView.setAdapter(adapter);
}
else{
Toast.makeText(getApplicationContext(), "Impossible de récupérer la liste des scénarios de cet enfant", Toast.LENGTH_LONG).show();
}
}
}
}
Thanks for your help.
if you want to maintain GetChildrenList state as it is then just call finish() rather than new intent on previous button click as follow
replace in GetLearningGoalsList
#Override
public void onClick(View v) {
Intent myIntent = new Intent(GetLearningGoalsList.this, GetChildrenList.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
return;
}
with
#Override
public void onClick(View v) {
finish();
}

How to get Arraylist<HashMap<String, String>> from AsyncTask through onPostExecute

I am trying to put storelist into StoreList variable. But it is not working.
doInBackground method is working perfectly but onPostexecute is not working.
Here is my code,
public class guest_main extends Fragment implements View.OnClickListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Location mCurrentLocation, mDestination;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
String currentLon, currentLat;
private ListView mListView = null;
private ListViewAdapter mAdapter = null;
public ArrayList<HashMap<String, String>> StoreList;
class BackgroundWorker3 extends AsyncTask<String, Void,ArrayList<HashMap<String, String>>> {
Context context;
AlertDialog alertDialog;
BackgroundWorker3(Context ctx) {
context = ctx;
}
JSONArray store = null;
ArrayList<HashMap<String, String>> storeList;
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
String type = params[0];
storeList = new ArrayList<HashMap<String, String>>();
if (type.equals("Select2")) {
try {
String link = "...";
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String json;
while ((json = reader.readLine()) != null) {
sb.append(json);
}
String s = sb.toString().trim();
JSONObject jsonObject = new JSONObject(s);
store = jsonObject.getJSONArray("result");
for (int i = 0; i < store.length(); i++) {
JSONObject c = store.getJSONObject(i);
String name = c.getString("name");
String tel = c.getString("tel");
String latitude = c.getString("latitude");
String longitude = c.getString("longitude");
HashMap<String, String> stores = new HashMap<String, String>();
stores.put("name", name);
stores.put("tel", tel);
stores.put("latitude", latitude);
stores.put("longitude", longitude);
storeList.add(stores);
}
return storeList;
} catch (Exception e) {
return null;
}
}
return storeList;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.guest_main, container, false);
StoreList = new ArrayList<HashMap<String, String>>();
getData();
buildGoogleApiClient();
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
Button btn = (Button) v.findViewById(R.id.button1);
btn.setOnClickListener(this);
return v;
}
public void getData(){
BackgroundWorker3 bk2 = new BackgroundWorker3(getActivity());
bk2.execute("Select2");
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
Intent intent = new Intent(getActivity().getApplicationContext(), gmenu_list.class);
startActivity(intent);
}
}
private class ViewHolder {
public ImageView mIcon;
public TextView mText;
public TextView mDate;
public TextView mDistance;
}
private class ListViewAdapter extends BaseAdapter {
private Context mContext = null;
private ArrayList<g_ListData> mListData = new ArrayList<g_ListData>();
public ListViewAdapter(Context mContext) {
super();
this.mContext = mContext;
}
#Override
public int getCount() {
return mListData.size();
}
#Override
public Object getItem(int position) {
return mListData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void addItem(Drawable icon, String mTitle, String mDate, String mDistance){
g_ListData addInfo = null;
addInfo = new g_ListData();
addInfo.mIcon = icon;
addInfo.mTitle = mTitle;
addInfo.mDate = mDate;
addInfo.mDistance = mDistance;
mListData.add(addInfo);
}
public void remove(int position){
mListData.remove(position);
dataChange();
}
public void sort(){
Collections.sort(mListData, g_ListData.ALPHA_COMPARATOR);
dataChange();
}
public void dataChange(){
mAdapter.notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.gmenu_list_item, null);
holder.mIcon = (ImageView) convertView.findViewById(R.id.mImage);
holder.mText = (TextView) convertView.findViewById(R.id.mText);
holder.mDate = (TextView) convertView.findViewById(R.id.mDate);
holder.mDistance = (TextView)convertView.findViewById(R.id.mDistance);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
g_ListData mData = mListData.get(position);
if (mData.mIcon != null) {
holder.mIcon.setVisibility(View.VISIBLE);
holder.mIcon.setImageDrawable(mData.mIcon);
}else{
holder.mIcon.setVisibility(View.GONE);
}
holder.mText.setText(mData.mTitle);
holder.mDate.setText(mData.mDate);
holder.mDate.setText(mData.mDistance);
return convertView;
}
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(100000); // Update location every second
try{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);}catch (SecurityException e){
}
if (mCurrentLocation != null) {
currentLat = String.valueOf(mCurrentLocation.getLatitude());
currentLon = String.valueOf(mCurrentLocation.getLongitude());
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
currentLat = String.valueOf(location.getLatitude());
currentLon = String.valueOf(location.getLongitude());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.disconnect();
}
}
Ok..The problem is in your case that the Async task runs on separate thread from UI thread So when you call BackgroundWorker3 in getData method then UI thread doesn't wait for Async task response(separte thread) and StoreList have null value. So you see StoreList doesn't have any value and in listView nothing will show.
Write this code in onPostExecute method not in onCreate..
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {
StoreList = arrayList;
mListView = (ListView)v.findViewById(R.id.mList);
mAdapter = new ListViewAdapter(getActivity());
for(int i=0; i<StoreList.size(); i++){
HashMap<String, String> each = StoreList.get(i);
String name = each.get("name");
String tel = each.get("tel");
String lat = each.get("latitude");
String lon = each.get("longitude");
mDestination.setLatitude(Double.valueOf(lat).doubleValue());
mDestination.setLongitude(Double.valueOf(lon).doubleValue());
float distance = mCurrentLocation.distanceTo(mDestination);
mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
}
mListView.setAdapter(mAdapter);
}
Hope this will help you.

Search hashmap for string and remove

So I'm showing images in a gridview from a json response.
Each image comes in a json response like:
{poster_path=/u1LHo5ObRZA1r8pzSq0OqQ2qlaU.jpg, vote_average=0.0, title=The Beauty Inside, vote_count=0, overview=Woo-Jin changes into a different person when he wakes up. He falls in love with Yi-Soo., id=338729, release_date=2015-08-20}
poster_path contains the image url.
When the poster_path is null like:
{poster_path=null, vote_average=0.0, title=The Bad Education Movie, vote_count=0, overview=Mr Wickers and his class go on one final school trip after they finish their GCSEs., id=348296, release_date=2015-08-21}
I want to remove this item in my Hashmap if it contains poster_path=null so it doesn't load that data into my gridView.
How can this be done?
Here is my activity which downloads and parses the json response:
public class Upcoming extends android.support.v4.app.Fragment {
private static final String KEY_POSITION = "position";
private static final String TAGG = "TMDB Pop Movies";
private static final String apiKey = "MYKEY";
private static final String tmdbURL = "MYURL";
private static final String TAG_MOVIES = "results";
static final String TAG_ID = "id";
static final String TAG_RELEASE = "release_date";
static final String TAG_TITLE = "title";
static final String TAG_POSTER = "poster_path";
static final String TAG_VOTE_AVG = "vote_average";
static final String TAG_VOTE_COUNT = "vote_count";
static final String TAG_OVERVIEW = "overview";
String NumberOfPage = "&page=1";
ArrayList<HashMap<String, String>> mylist;
JSONObject json = null;
JSONArray results = null;
UpcomingGridViewAdapter adapter;
GridView Gridv;
int numberofpagesshown = 0;
private String position;
private OnFragmentInteractionListener mListener;
public static Upcoming newInstance(int position) {
Upcoming fragment = new Upcoming();
Bundle args = new Bundle();
args.putInt(KEY_POSITION, position);
fragment.setArguments(args);
return fragment;
}
public Upcoming() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
position = getArguments().getString(KEY_POSITION);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View newview = inflater.inflate(R.layout.fragment_upcoming, container, false);
//Initialize with empty data
mylist = new ArrayList<HashMap<String, String>>();
// Start download void
new DownloadJSON().execute();
return newview;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
// Downloading data asynchronously
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... url) {
json = JSONfunctions.getJSONfromURL(tmdbURL + "/3/movie/upcoming"
+ apiKey + NumberOfPage);
try {
// Get the array of movies
results = json.getJSONArray(TAG_MOVIES);
// loop through all the movies
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String poster = r.getString(TAG_POSTER);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
numberofpagesshown = numberofpagesshown + 1;
if(numberofpagesshown == 1 ) {
Gridv = (GridView) getActivity().findViewById(R.id.upcoming_gridlayout);
adapter = new UpcomingGridViewAdapter(getActivity(), mylist);
Gridv.setAdapter(adapter);
}
else {
adapter.notifyDataSetChanged();
}
// Attach the listener to the AdapterView onCreate
Gridv.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Append new items to AdapterView
if (numberofpagesshown == 1) {
NumberOfPage = "&page=2";
new DownloadJSON().execute();
} else if (numberofpagesshown == 2) {
NumberOfPage = "&page=3";
new DownloadJSON().execute();
} else if (numberofpagesshown == 3) {
NumberOfPage = "&page=4";
new DownloadJSON().execute();
} else if (numberofpagesshown == 4) {
NumberOfPage = "&page=5";
new DownloadJSON().execute();
} else if (numberofpagesshown == 5) {
NumberOfPage = "&page=6";
new DownloadJSON().execute();
}
}
});
}
}
}
And finally the gridView Adapter:
public class UpcomingGridViewAdapter extends BaseAdapter {
public boolean pressedMovieItem;
Context context;
ArrayList<HashMap<String, String>> data;
// Will store json data
HashMap<String, String>mylist = new HashMap<>();
public UpcomingGridViewAdapter(Context a, ArrayList<HashMap<String, String>> d) {
context = a;
data = d;
}
public int getCount() {
return data.size();
}
public HashMap<String, String> getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.upcoming_grid_item, parent, false);
}
final ImageView poster = (ImageView) convertView.findViewById(R.id.upcoming_image);
mylist = data.get(position);
final String posterPath = mylist.get("poster_path");
// set image url correctly
// sizes for image 45, 92, 154, 185, 300, 500
final String url = "http://image.tmdb.org/t/p/w185" + posterPath;
if(mylist.get("poster_path") != "null") {
// load image url into poster
Picasso.with(context).load(url).into(poster);
}
else{
// load image url into poster
// Picasso.with(context).load(R.drawable.ic_local_movies_black_24dp).into(poster);
poster.setBackgroundColor(Color.parseColor("#F5F5F5"));
// poster.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
}
Just change you for loop inside doInBackground() like this. It would simply won't add that node in ArrayList
for (int i = 0; i < results.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String poster = r.getString(TAG_POSTER);
if(poster == null || poster.equals(""))
continue;
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}
Made a little modification:
// loop through all the movies
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject r = results.getJSONObject(i);
String poster = r.getString(TAG_POSTER);
if(poster == null || poster.equals("")|| poster.equals("null"))
continue;
else {
String id = r.getString(TAG_ID);
String title = r.getString(TAG_TITLE);
String release = r.getString(TAG_RELEASE);
String vote = r.getString(TAG_VOTE_AVG);
String voteCount = r.getString(TAG_VOTE_COUNT);
String overview = r.getString(TAG_OVERVIEW);
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_POSTER, poster);
map.put(TAG_RELEASE, release);
map.put(TAG_VOTE_AVG, vote);
map.put(TAG_VOTE_COUNT, voteCount);
map.put(TAG_OVERVIEW, overview);
mylist.add(map);
}

Android update adapter doesn't work correctly

In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.

Setting AppWidget's title using data encoded as JSON

I'm working with json. I parsed the JSON and I can show my JSON (images and text) on ListView. Now I want to show JSON's first item's title in my widget.
I successfully created the widget but I have a problem with the JSON's first item's title.
This is a my code:
public class AppWidget extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "CLOCK_WIDGET_UPDATE";
RemoteViews views;
int appWidgetId;
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
views = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
String aa = (MainActivity.itemList.get(0)
.get(MainActivity.KEY_title)).toString();
views.setOnClickPendingIntent(R.id.widgetPic, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetTitle, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetDesc, pendingIntent);
views.setTextViewText(R.id.widgetDesc, aa);
views.setImageViewBitmap(
R.id.widgetPic,
((BitmapDrawable) context.getResources().getDrawable(
R.drawable.background)).getBitmap());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public void updateAppWidget(Context context,
AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
try {
} catch (Exception e) {
}
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
}
BaseAdapter.java code:
public class MyAdapter extends BaseAdapter {
Context mContext;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private int screenSize;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> d,
int screenSize) {
this.mContext = context;
this.data = d;
this.screenSize = screenSize;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(context.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView journal = (TextView) vi.findViewById(R.id.smalljournal);
TextView title = (TextView) vi.findViewById(R.id.smalltitle);
TextView description = (TextView) vi
.findViewById(R.id.smallDescription);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.smallthumb);
TextView statId = (TextView) vi.findViewById(R.id.smallstatID);
TextView DateTime = (TextView) vi.findViewById(R.id.smallDateTime);
HashMap<String, String> itemList = new HashMap<String, String>();
itemList = data.get(position);
journal.setText(itemList.get(MainActivity.KEY_journal));
statId.setText(itemList.get(MainActivity.KEY_statID));
journal.setTypeface(MainActivity.tf2);
String titleString = itemList.get(MainActivity.KEY_title);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// coming date : 2014-02-03T18:45:00
String DateTimeTxt = itemList.get(MainActivity.KEY_pubDate).replace(
"T", " ");
// DateTimeTxt = date;
try {
Date _d = df.parse(DateTimeTxt);
SimpleDateFormat new_df = new SimpleDateFormat("dd.MM.yyyy");
String _s = new_df.format(_d);
DateTime.setText(_s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (screenSize == Configuration.SCREENLAYOUT_SIZE_NORMAL)
description.setVisibility(View.INVISIBLE);
else
description.setVisibility(View.VISIBLE);
title.setText(titleString);
title.setTypeface(MainActivity.tf2);
description.setText(itemList.get(MainActivity.KEY_description));
description.setTypeface(MainActivity.tf2);
String url = itemList.get(MainActivity.KEY_image);
// url = url.replace("-c.jpg", ".jpg");
imageLoader.DisplayImage(url, thumb_image);
return vi;
}
}
MainActivity.java code
public class MainActivity extends Activity {
public String URL = "********************";
public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;
public JSONParser jsonparser;
static MyAdapter adapter;
ProgressDialog pDialog, pDialog1;
static String fontPath2 = "font.ttf";
public static Typeface tf2;
public static ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();
public ImageLoader imageLoader;
static final int DIALOG_ERROR_CONNECTION = 1;
public static String dateTime;
private ArrayList<Content> contents = new ArrayList<Content>();
public ImageView image;
public EditText searchInput;
public LinearLayout mainLayout, SlideLayout;
public TransparentProgressDialog pd;
public Tools tools;
public static boolean CheckListview = true;
private int screenSize;
int windowWidth;
public LoadDataAllChanelsToServer loadData;
public TextView journal, tittle, description, smalllink, DateTime,
smallstatID;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
Writer writer;
public File yourFile;
View menu_Slide;
#SuppressLint("CutPasteId")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
SlideLayout = (LinearLayout) findViewById(R.id.SlideLayout);
list = (ListView) findViewById(R.id.listView1);
cd = new ConnectionDetector(getApplicationContext());
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this,
this));
loadData = new LoadDataAllChanelsToServer();
menu_Slide = (findViewById(R.id.menu_button));
image = (ImageView) findViewById(R.id.imageView1);
searchInput = (EditText) findViewById(R.id.input_search_query);
tf2 = Typeface.createFromAsset(getAssets(), fontPath2);
pd = new TransparentProgressDialog(this, R.drawable.loader);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
journal = (TextView) view.findViewById(R.id.smalljournal);
tittle = (TextView) view.findViewById(R.id.smalltitle);
description = (TextView) view
.findViewById(R.id.smallDescription);
smalllink = (TextView) view.findViewById(R.id.smalllink);
DateTime = (TextView) view.findViewById(R.id.smallDateTime);
smallstatID = (TextView) view.findViewById(R.id.smallstatID);
String Stringjournal = journal.getText().toString();
String Stringtittle = tittle.getText().toString();
String Stringdescription = description.getText().toString();
String Stringlink = smalllink.getText().toString();
String StringdateTime = DateTime.getText().toString();
String StringstatID = smallstatID.getText().toString();
HideKeyBoadr();
Intent in = new Intent(MainActivity.this, Result.class);
in.putExtra("KEY_journal", Stringjournal);
in.putExtra("KEY_title", Stringtittle);
in.putExtra("KEY_description", Stringdescription);
in.putExtra("KEY_link", Stringlink);
in.putExtra("KEY_pubDate", StringdateTime);
in.putExtra("KEY_statID", StringstatID);
String url = itemList.get(position).get(MainActivity.KEY_image);
if (!cd.isConnectingToInternet()) {
in.putExtra("Bitmap", url);
}
else {
if (url.endsWith("-c.jpg"))
url = url.replace("-c.jpg", ".jpg");
in.putExtra("Bitmap", url);
}
in.putExtra("Bitmap", url);
startActivity(in);
overridePendingTransition(R.anim.trans_left_in,
R.anim.trans_left_out);
}
});
if (!cd.isConnectingToInternet()) {
return;
} else {
loadData.execute();
}
}
public void HideKeyBoadr() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
}
private class LoadDataAllChanelsToServer extends
AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected String doInBackground(String... urls) {
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
itemList.add(map);
dateTime = itemList.get(itemList.size() - 1).get(
KEY_pubDate);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return itemList.toString();
}
#Override
protected void onPostExecute(String result) {
try {
if (pd != null) {
pd.dismiss();
}
} catch (Exception e) {
}
try {
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
list.setAdapter(adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
createDialog();
}
private void createDialog() {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Are you sure you want to exit?");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
}
);
alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDlg.create().show();
}
}
My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?
My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?
That is too much code to look at. Please narrow your issue down and show the exact point the issue is occurring at.
Use your debugger to step through your code. 1st, identify the exact line at which the issue is occurring. Next, use your debugger to inspect the variables at that point. The error is an index out of bounds, so you're accessing a point in a list that is bigger than the size of the list.

Categories

Resources