Async call adapter show nothing - android

I have a problem.
I´m set an adapter when a asyctask end.
All code rules but when the code is inflated the screen keep white. The code dont throw any exception and i put some log to control execution flow. All is ok but the screen keep white.
I´m doing that:
protected class ObtenerCursos extends AsyncTask<Void, Void, Boolean> {
private JSONArray resultado;
private ProgressDialog dialog;
private Activity_Mis_Curso activity;
List <Curso> lista;
public ObtenerCursos(Activity_Mis_Curso misCursos){
this.activity=misCursos;
}
#Override
protected Boolean doInBackground(Void... params) {
resultado = getCursos(url,usuario);
if (resultado != null) {
lista=parseJSONDocumentos(resultado);
return true;
} else {
return false;
}
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Activity_Mis_Curso.this,
"Obteniendo cursos", "Espere por favor...", true);
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if (result) {
gridView = (GridView) findViewById(R.id.miscursos_Grid);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
gridView.setNumColumns(3);
numColumns = 3;
} else {
numColumns = 2;
gridView.setNumColumns(2);
}
gridView.setAdapter(new MisCursosAdapter(Activity_Mis_Curso.this, listaCursos, numColumns));
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (listaCursos.get(position).getSoloReproduccion() == 0) {
Intent i = new Intent(Activity_Mis_Curso.this,
Activity_Main_Tradicional.class);
i.putExtra("Curso", listaCursos.get(position));
finish();
startActivity(i);
} else {
Intent i = new Intent(Activity_Mis_Curso.this,
Activity_Curso_SoloReproductor.class);
i.putExtra("Curso", listaCursos.get(position));
finish();
startActivity(i);
}
}
});
Log.e("ando", "por aqui \n\n");
} else {
Toast.makeText(getBaseContext(), "No se han encontrado cursos",
Toast.LENGTH_LONG).show();
Intent in = new Intent(Activity_Mis_Curso.this,
Activity_Index.class);
finish();
startActivity(in);
}
}
}
I can´t find where is my problem, i don´t know what i´m doing bad.

Related

How to use backbutton to unselect all item in gridview?

i'm using backbutton as interface from activity but it's not working properly for me because on backpress showing 0 size of arraylist
// here is the activity class from where i'm getting backbutton interface..
public class Multiple_Images extends AppCompatActivity {
#Override
public void onBackPressed() {
if(twice ==true){
Intent intent =new Intent(this,MainActivity.class);
startActivity(intent);
}ImageAdapter imageAdapter =new ImageAdapter(this);
imageAdapter.onBackPress();
Toast.makeText(this, "Press twice", Toast.LENGTH_SHORT).show();
twice =true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice =false; } }, 2000); }}
//here is the adapter class here i'm using backbutton
public class ImageAdapter extends BaseAdapter implements onBackPressListener {
ArrayList<String> selectedArraylist ;
#Override
public boolean onBackPress() {
selectedArraylist.clear();
Toast.makeText(context, "All values unselected", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
urimodel=new ArrayList<>();
final ImageView imageGrid ;
Activity activity = (Activity) context;
actionMode = activity.startActionMode(new Actionmode());
final GridModel gridModel=(GridModel) this.getItem(i);
if(view==null) {
view = LayoutInflater.from(context).inflate(R.layout.model, null);
selectedArraylist =new ArrayList<>();
}
final CardView cardView= (CardView)view.findViewById(R.id.cardview_image);
imageGrid = (ImageView) view.findViewById(R.id.grid_image);
// gridText = (TextView) view.findViewById(R.id.grid_text);
imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.get().load(gridModel.getImage()).resize(200,200).into(imageGrid);
if (selectedArraylist.contains(gridModel.getImage_text())) {
cardView.setCardBackgroundColor(CARD_SELECTED_COLOR);
}else {
cardView.setCardBackgroundColor(Color.WHITE);
}
return view;
}
}
Simply you can do this inside onBackPressed
#Override
public void onBackPressed() {
if (twice == true) {
super.onBackPressed(); //this backs to the previous activity, if you want to stay with Intent, add finish() after startActivity()
return;
} else {
for (int i = 0; i < list.size(); i++) {
if (gridView.isItemChecked(i)) {
gridView.setItemChecked(i, false);
}
}
//selectedArraylist.clear(); this is clearing your array of selected items
}
twice = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
}
}, 2000);
}
I don't know, why did you put selectedArraylist =new ArrayList<>(); in adapter getView() method. getView() is fired every time, when a new list item is inflated, that mean every time, when you are changing adapters source, scrolling list this method is called, and every time you are initialize you array, and all data inside lost. You should treat an adapter class just like a tool for displaying items, and all actions like above make outside adapter.
pretty much easy,
I give you my own project code, hope it help you.
StudentFragment.java:
private void MultiSelected_Student(int position) {
Student data = adapter_class.getItem(position);
if (data != null) {
if (selectedIds.contains(data)) selectedIds.remove(data);
else selectedIds.add(data);
}
}
private void Remove_MultiSelected() {
try {
selectedIds.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void Group_UnSelect() {
Remove_MultiSelected();
MultiSelected = false;
fab.setVisibility(View.GONE);
homeeActivity.studentsMultiSelect = false;
notifyy();
}
private void notifyy() {
adapter_class.notifyDataSetChanged();
}
HomeActivity.java:
public boolean studentsMultiSelect = false;
#Override
public void onBackPressed() {
if (studentsMultiSelect) {
studentFragment.Group_UnSelect();
} else {
super.onBackPressed();
}
}

Display black blank screen while showing folderwisw all photo from gallery

Hi I developed one app where I want to display folder wise all photos from storage. I implemented the code for it but the problem is that when activity is created it display black blank screen for 5 sec and then display all folder.
Here is my code:
public class ImageWithFolder extends AppCompatActivity implements AdapterView.OnItemClickListener {
List<GridViewItem> gridItems = new ArrayList<GridViewItem>();
String redirect;
GridView gridView;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imagefolder);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
Intent ii = getIntent();
redirect = ii.getStringExtra("next_activity");
gridView = (GridView) findViewById(R.id.gridView);
setGridAdapter();
}
private void setGridAdapter() {
createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
private void createGridItems(String directoryPath) {
File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
for (File file : files) {
if (file.isDirectory()) {
if (file.listFiles((new DirFilter())).length > 0) {
createGridItems(file.getAbsolutePath());
}
if (file.listFiles((new ImageFilter())).length > 0) {
gridItems.add(new GridViewItem(file.getAbsolutePath(), true, null));
}
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isImageFile(String filePath) {
if (filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".jpeg")) {
return true;
}
return false;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (redirect.equalsIgnoreCase("1")) {
Intent ii = new Intent(ImageWithFolder.this, SelectPhotos.class);
ii.putExtra("path", gridItems.get(i).getPath());
startActivity(ii);
} else if (redirect.equalsIgnoreCase("2")) {
Intent ii = new Intent(ImageWithFolder.this, AlbumSelectPhotos.class);
ii.putExtra("path", gridItems.get(i).getPath());
startActivity(ii);
}
}
private class ImageFileFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
private class ImageFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
private class DirFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
return false;
}
}
}
I am not getting what is going wrong with the code.
Can anyone give solution regarding black screen appear at the first time.
Thanks in advance.
Put your read file method in async..
Call Aysnc:
new LoadData().execute()
public class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
}
If you are comfortable with RxJava then use Observal, This is the best soluton.

How to display the loading progress bar on top of the dialog popup which is listview?

I'm a having a listview, of type dialog pop-up. When i click on the item of the listview, i want loading progress bar to be displayed. Below is the listview code.
public AdapterView.OnItemClickListener getOnItemClickListener() {
return new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// ProgressDialog dialog;
// dialog = ProgressDialog.show(view.getContext(), "Please wait..", "Loading data", true);
// dialog.setCancelable(false);
// dialog.show();
HashSet sometable= new HashSet();
sometable.add(i);
if (getContext() == null) return;
Intent output = new Intent();
final IData data = (IData) adapterView.getItemAtPosition(i);
//check if its myself
if((data.get("FIRST_NAME")==null)&&(data.get("LAST_NAME")==null))
output.putExtra("User","");
else{
output.putExtra("User", (String) data.get("ASSIGNEE_GUID"));
output.putExtra("userName", (String) data.get("FIRST_NAME") + " " + (String) data.get("LAST_NAME"));
//new cancelPending((Activity) getContext(),data).execute();
AssigneABO.SyncSubordinateCalendar((String) data.get("ASSIGNEE_GUID"), view.getContext());
//new MyTask(MainActivity.this).execute((Void) null);
}
Activity activity = (Activity) getContext() ;
activity.setResult(Activity.RESULT_OK,output);
activity.finish();
}
};
}
When i click on the items of the listview, starts the async task to get the data. In that async task's onprexcute method i'm calling the progress dialog as below.
public static class SyncApplicationTask extends AsyncTask<String, Context, Boolean> {
Context context;
ProgressDialog progress;// = new ProgressDialog(context);
public SyncApplicationTask(Context mcontext) {
super();
context = mcontext;
progress = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
progress.setMessage(context.getString(R.string.Sync));
progress.setTitle(R.string.sync_msg);
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.setIndeterminate(true);
progress.show();
if (!Util.hasActiveNetworkConnection(context)) {
Util.alertMessageDialog(context, R.string.network_connection_unavailable_message);
return;
}
if (SynchronizationManager.getInstance().isSyncAllCategoryGroupActive()) {
Util.alertMessageDialog(context, R.string.synchronization_still_active);
return;
}
if (!ConnectionManager.getInstance().isServerConnected()) {
ConnectionManager.getInstance().stopServerConnection(60);
boolean isStarted = ConnectionManager.getInstance()
.startServerConnection(60); // 2 mins time out
Log.v("Connection started : ", Boolean.valueOf(isStarted)
.toString());
if (!isStarted) {
Util.alertMessageDialog(context, R.string.connection_server_lost_message);
return;
}
}
}
#Override
protected Boolean doInBackground(String... syncGroups) {
try {
SAPReXDB.synchronize(syncGroups[0]);
return true;
}catch (Exception Ex)
{ Log.v("Erron on sync: ", Ex.toString());
return false;
}
}
#Override
protected void onPostExecute(final Boolean c) {
progress.dismiss();
if(!c)
Util.alertMessageDialog(context, R.string.sync_progress_failed);
}
}
But it is displaying behind the dialog listview. I want it to display above the dialog listview. What am'i doing wrong. Can you please suggest me on this. Thank you.
With which Context do you create ProgressDialog?
GUI position & order issues can happen when you do not use normal Activity Context, but using your specific View's context or Application Context.

Load more data dynamically in a listview in android

i'm doing an android application. I retrive data with GSON and display 10 elements each time i do a request. My problem is that i don't know how to add the new elements, to the elements before, in the bottom of the list. I use onScroll,so when i reach at the end of the list with 10 elements ,i make a request on the server.
I'm trying to integrate some libraries from github ,but it doesn't work.
Here is my code:
First is my method that populate the main list:
public void popullateMainList(final String url,final long expirationTime) {
//requestData(MAIN_LIST_URL);
new AsyncTask<Void, Void, Void>() {
ProgressBar pb = (ProgressBar)findViewById(R.id.progressBar);
#Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... voids) {
try {
elements = new Elements(url, expirationTime);
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Void result) {
pb.setVisibility(View.GONE);
updateDisplay();
mainElementAdapter.notifyDataSetChanged();
}
}.execute();
}
And the method updateDisplay has the following code:
protected void updateDisplay() {
eList = (ListView) findViewById(R.id.mainView);
mainElementAdapter = new ElementListAdapter(this, elements.getElements());
// mainElementAdapter.add(elements.getElements());
footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_footer, null, false);
eList.addFooterView(footerView);
eList.setAdapter(mainElementAdapter);
eList.removeFooterView(footerView);
eList.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (eList.getLastVisiblePosition() >= eList.getCount() - visibleThreshold) {
currentPage++;
actualUrl = Constants.MAIN_LIST_URL + "?pageNumber=" + currentPage;
popullateMainList(actualUrl,1);
}
}}
public boolean canChildScrollUp() {
//your condition to check scrollview reached at top while scrolling
if (swipeLayout.getScrollY() == 0.0)
return true;
else
return false;
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
if (firstVisibleItem == 0)
swipeLayout.setEnabled(true);
else
swipeLayout.setEnabled(false);
}
});
}
I hope that anybody help me. Thank you in advance!
Try save old.
when you use
elements = new Elements(url, expirationTime);
you override your Elements object and when you use
mainElementAdapter = new ElementListAdapter(this, elements.getElements());
you override your old data in adapter
added new method in your class Elemets
something like that
if(elements == null) {
elements = new Elements(url, expirationTime);
} else {
elements.add(new Elements(url, expirationTime).getElements());
}

Finish an activity from Fragment

In my application I have 2 fragment, Fragment A and Fragment B.On both these fragments Iam doing some XML parsing and populating listviews.I want to implement a splash screen for my app.So that it display during parsing and population of listviews and finishes when its done. For this, I have created an activity SplashActivity.I have Implemented asyntask on FragmentA and called the SplashActivity on preexecute section.Now, when the app launches SplashActivity get started.But I cant finish this acitivity on postexecute of FragmentA. getActivity().finishActivity() is not working.Please some one help me to solve this issue or suggest me another method to implement Splash screen on Fragment Activity. Thanks in advance....
here is my FragmentA=>
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating layout
View v = inflater
.inflate(R.layout.headlines_fragment, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("Tag", "onCreateView");
// We set clear listener
loading = (ProgressBar) getActivity().findViewById(R.id.progressBar1);
if (Headlines.headflag == "malayalam") {
urls = "http://www.abc.com/rssfeeds/19_18_17_25/1/rss.xml";
}
if (Headlines.headflag == "english") {
urls = "http://www.abc.com/en/rssfeeds/1_2_3_5/latest/rss.xml";
}
new ProgressAsyncTask().execute();
MainActivity.refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ProgressAsyncTask().execute();
}
});
}
public void populate_listview() {
newsList = new ArrayList<HashMap<String, String>>();
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
newsList.add(map);
MarqueeStr = MarqueeStr + " *** " + Title[i];
}
}
public void StartProgress() {
new ProgressAsyncTask().execute();
}
public class ProgressAsyncTask extends AsyncTask<Void, Integer, Void> {
int myProgress;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
myProgress = 0;
Intent intent = new Intent(getActivity(), Splash.class);
startActivityForResult(intent, 5); //Here I called Splash Activity
loading.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
getActivity().finishActivity(5);// Here I tried to finish flash activity
if (Title == null) {
final AlertDialog.Builder alertbox = new AlertDialog.Builder(
getActivity());
alertbox.setMessage("Error in connection.Do you want to retry");
alertbox.setPositiveButton("retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// getActivity().finish();
// Intent intent = new Intent(getActivity(),
// MainActivity.class);
// startActivityForResult(intent,1);
}
});
alertbox.setNegativeButton("exit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// getActivity().finish();
}
});
alertbox.show();
}
list = (GridView) getActivity().findViewById(R.id.grid);
// Getting adapter by passing xml data ArrayList
adapter = new HeadlinesAdapter(getActivity(), newsList);
list.setAdapter(adapter);
loading.setVisibility(View.INVISIBLE);
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/karthika.TTF");
MainActivity.flashnews.setText(MarqueeStr);
if (Headlines.headflag == "malayalam") {
MainActivity.flashnews.setTypeface(tf);
}
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myintent = new Intent(
"com.abc.malayalam2headlinespodcast.PODCAST");
Bundle mybundle = new Bundle();
mybundle.putInt("number", position);
myintent.putExtras(mybundle);
startActivity(myintent);
}
});
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parse();
if (Title != null) {
populate_listview();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
}
}
public static void parse() {
//parsing done here
}
}
You should not implement your Splash as an Activity but rather as a DialogFragment. Simply style that dialog fragment so that it appears fullscreen.
Concerning showing:
SplashDialogFragment splashDlg = new SplashDialogFragment();
splashDlg.show(getSupportFragmentManager(), "SplashScreen");
Then closing:
SplashDialogFragment splashDlg = (SplashDialogFragment) getSupportFragmentManager().findByTag("SplashScreen");
splashDlg.dismiss();
just to answer the question which is your title actually "To finish an activity from Fragment", it's always a good way to use interface to interact from Fragment to Activity as per the docs: Communicating with Activity from Fragment. So one must always declare an interface in Fragment which is to be implemented in your activity something like below:
public class SplashActivity extends Activity implements FragmentA.FragmentListenerCallback {
public void onFragmentInteraction() {
//finish your activity or do whatever you like
finish();
}
}
public class FragmentA extends Fragment {
private FragmentListenerCallback fragmentListenerCallback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentListenerCallback = (FragmentListenerCallback) activity;
}
public interface FragmentListenerCallback {
void onFragmentInteraction();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(fragmentListenerCallback != null){
fragmentListenerCallback.onFragmentInteraction();
}
}
}

Categories

Resources