Loading spinner not showing correctly - spinner

I am trying to put a spinner while my data is loaded and UI updated so for this task I do this:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_details);
setTitle("Details");
startButt = (Button)findViewById(R.id.BeginJourney);
Map = (Button)findViewById(R.id.map_btn1);
boolean GreenButtState = getIntent().getBooleanExtra("GreenButtState", false);
boolean FastButtonState = getIntent().getBooleanExtra("FastButtonState", false);
AsyncTask<Void, Void, Void> LoadingTask = new AsyncTask<Void, Void, Void>()
{
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
#Override
protected void onPreExecute()
{
this.dialog.setMessage("Message");
this.dialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
final HashMap<String, Object> trip1;
Intent intent = getIntent();
mXmlRpcUrl = intent.getStringExtra("XmlRpcUrl");
mSessionID = intent.getStringExtra("SessionID");
mGetSavedTripFunc = intent.getStringExtra("GetSavedTripFunc");
newTripID = intent.getIntExtra("newTripID", 0);
variantID = intent.getIntExtra("VariantID", 0);
Week = intent.getIntExtra("WeekState", 0);
CityName = intent.getStringExtra("NameOfCity");
Flag = intent.getIntExtra("Flag", 0);
startLatitude = intent.getDoubleExtra("startLatitude", 0.0);
startLongitude = intent.getDoubleExtra("startLongitude", 0.0);
endLatitude = intent.getDoubleExtra("endLatitude", 0.0);
endLongitude = intent.getDoubleExtra("endLongitude", 0.0);
trip1 = (HashMap<String, Object>) intent.getSerializableExtra("Variant");
variant = new Variant();
variant.Read(trip1);
startButt.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(RoadDetails.this, Localisation.class);
intent.putExtra("SessionID", mSessionID);
intent.putExtra("XmlRpcUrl", mXmlRpcUrl);
intent.putExtra("NewTripID", newTripID);
intent.putExtra("VariantID", variantID);
intent.putExtra("WeekState", Week);
intent.putExtra("NameOfCity", CityName);
intent.putExtra("Variant", (Serializable)trip1);
intent.putExtra("Flag", Flag);
intent.putExtra("startLatitude", startLatitude);
intent.putExtra("startLongitude", startLongitude);
intent.putExtra("endLatitude", endLatitude);
intent.putExtra("endLongitude",endLongitude);
startActivity(intent);
}
});
Map.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//Intent intent1 = new Intent (RoadDetails.this, MapDraw.class);
Intent intent1 = new Intent (RoadDetails.this, OSMActivity.class);
intent1.putExtra("SessionID",mSessionID);
intent1.putExtra("endLatitude", endLatitude);
intent1.putExtra("endLongitude",endLongitude);
intent1.putExtra("startLatitude", startLatitude);
intent1.putExtra("startLongitude", startLongitude);
intent1.putExtra("Variant", (Serializable)trip1);
startActivity(intent1);
}
});
return null;
}
#Override
protected void onPostExecute(Void result)
{
GettingData();
this.dialog.dismiss();
}
};
LoadingTask.execute((Void[])null);
}
However when I do this there is a delay before opening the the activity that contains this code (I want the spinner to be there while the data is loaded) the spinner is not showing. There is just a delay (for the data to be loaded - lets also call it screen freeze for a 1 - 3 seconds) and thats it. What am I doing wrong? I want the spinner to show while the data is loaded and after that to be dismissed. I also what to mention that in the method GettingData(); I am changing the UI - adding Layouts dynamically, adding images etc.

try this...this will work
ProgressDialog dialog = new ProgressDialog(RoadDetails.this);
this.dialog.setMessage("Message");
this.dialog.show();
//start your asynchronous task here
load your data here
//end asynchronous task
this.dialog.dismiss();

write ProgressDialog dialog; outside AsyncTask then
call
dialog = new ProgressDialog(RoadDetails.this);
dialog.setMessage("Message");
dialog.show();
inside onPreExecute().
Hope it will help you..

Related

NotifyDataSetChanged() not updating listview after closing alert dialog

In my adapter class I have created a alert dialog and added a update button to it which allows me to update the items on my list view, it updates my listview but only when I leave the page and return back to it, I have used notifydatasetchanged but it doesn't seem to work, I want it to update on the list view immediately after the dialog closing.
update button
viewHolder.btnDisplayUpdate.setText("Update");
viewHolder.btnDisplayUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateCrime(crimes);
}
});
Update method
private void updateCrime(CrimesDelete crimes){
AlertDialog.Builder popupWindow = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
View root = inflater.inflate(R.layout.dialog_update, null);
popupWindow.setView(root);
AlertDialog alertDialog = popupWindow.create();
alertDialog.show();
editLocation = (EditText)root.findViewById(R.id.editText_location);
editType = (EditText)root.findViewById(R.id.editText_type);
editDescription = (EditText)root.findViewById(R.id.editText_description);
editDate = (EditText)root.findViewById(R.id.textViewDate);
editTime = (EditText)root.findViewById(R.id.textViewTime);
Spinner spinner = (Spinner) root.findViewById(R.id.editText_rating);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
getContext(), R.array.rating, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
editRating = parent.getItemAtPosition(pos).toString();
if (pos==0){
editRating = null;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
editLocation.setText(crimes.getLOCATION());
editType.setText(crimes.getTYPE());
editDescription.setText(crimes.getDESCRIPTION());
editDate.setText(crimes.getDATE());
editTime.setText(crimes.getTIME());
root.findViewById(R.id.btnAdd).setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String location = editLocation.getText().toString().trim();
String type = editType.getText().toString().trim();
String description = editDescription.getText().toString().trim();
String date = editDate.getText().toString().trim();
String time = editTime.getText().toString().trim();
String rating = spinner.getSelectedItem().toString().trim();
DB_CRIME.updateDate(crimes.getID(), location, type, description, date, time, rating);
loadUpdatedCrimes();
alertDialog.dismiss();
}
});
}
private void loadUpdatedCrimes() {
notifyDataSetChanged();
Toast.makeText(getContext(), "Crime has been Updated" , Toast.LENGTH_SHORT).show();
}

Problem with custom layout into another layout, layout doesn't show in app and design mode

So, when i click on button called calendar on main activity it should open new activity (Second screen) with part of calendar which i made (custom_calendar layout). However, it open to me only empty activity. I already tried to make changes in style.xml, clean and rebuild project, but it doesn't change anything.
Link to my app on BitBucket is down below.
https://bitbucket.org/Nike50/app/src/master/
Please change CustomCalendarView Class as per below
public class CustomCalendarView extends LinearLayout {
private static final int MAX_CALENDAR_DAYS = 42;
ImageView backBtn, nextBtn;
TextView CurrentDate;
GridView gridViewCalendar;
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
Context myContext;
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM", Locale.ENGLISH);
SimpleDateFormat yearFormat = new SimpleDateFormat("MMMM YYYY", Locale.ENGLISH);
List<Date> dates = new ArrayList<>();
List<Events> eventsList = new ArrayList<>();
public CustomCalendarView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
this.myContext = context;
InitializeLayout();
SetUpCalendar();
backBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, -1);
SetUpCalendar();
}
});
nextBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, 1);
SetUpCalendar();
}
});
}
private void SetUpCalendar() {
String currentDate = dateFormat.format(calendar.getTime());
CurrentDate.setText(currentDate);
}
public void InitializeLayout() {
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_calendar, this);
nextBtn = view.findViewById(R.id.forwardButton);
backBtn = view.findViewById(R.id.previousButton);
CurrentDate = view.findViewById(R.id.currentDate);
gridViewCalendar = view.findViewById(R.id.gridview);
}
}
It's Running well
I hope this can help you!
Thank You.

How to Display Custom AlertDailog Box inside Broadcast Receiver?

I create custom layout which i want to use inside broadcast receiver, but getLayoutInflater() not work inside receiver
inside onreceiver method i call startAlaram(context,intent)
private void startAlaram(final Context context, Intent intent) {
LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.custom_layout_notification, null);
AlertDialog.Builder builder=new AlertDialog.Builder(context,);
builder.setTitle("Get Reminder");
builder.setMessage("Alert ALert");
builder.setIcon(R.mipmap.ic_launcher_round);
builder.setView(view);
final AlertDialog dialog=builder.create();
TextView not_txt_title,not_txt_desc,not_txt_callfor,not_txt_name;
ImageView img1;
not_txt_title = view.findViewById( R.id.not_txt_title );
not_txt_desc = view.findViewById( R.id.not_txt_desc );
not_txt_callfor = view.findViewById( R.id.not_txt_callfor );
not_txt_name = view.findViewById( R.id.not_txt_name );
img1 = view.findViewById( R.id.img1);
not_txt_title.setText(rTitle);
not_txt_desc.setText(rDesc);
not_txt_callfor.setText(rCallFor);
not_txt_name.setText(rName);
dialog.show();
}
You can implement a transparent activity with AlertDialog.
Create a void for your AlertDialog.
private void alert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//... your alert stuff
}
Show your AlertDialog in your Receiver
#Override
public void onReceive(Context context, Intent intent) {
alert();
}
This is very Simple.
private void showDialog(){
LayoutInflater factory = LayoutInflater.from(this);
final View deleteDialogView = factory.inflate(R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(this).create();
deleteDialog.setView(deleteDialogView);
deleteDialogView.findViewById(R.id.yes).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//your business logic
deleteDialog.dismiss();
}
});
deleteDialogView.findViewById(R.id.no).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
* you have to register/unregister your broadcast.
registerReceiver(mReceiver, new IntentFilter("com.mybroadcast"));
unregisterReceiver(mReceiver);
Your Broadcast code is like this.
Broadcast mReceiver = new Broadcast(){
#Override
public void onReceive(Context context, Intent intent) {
showDialog()
}
}

How to destroy activity without crashing the app

I`v been trying for a while to destroy activity when the home button is pressed or when the app is in background and I manage to do something with this code
#Override
protected void onPause() {
this.finish();
super.onPause();
}
and when the app runs it does not crash but after a while playing in the activity the app just goes background and crashes.
This is the activity that I`m talking about:
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL=1154;//1 second
final static long TIMEOUT=7000;
int progressValue = 0;
CountDownTimer mcountDown;
List<Question> questionPlay = new ArrayList<>();
DbHelper db;
int index=0 , score =0,thisQuestion=0,totalQuestion,CorrectAnswer;
String mode = "";
ProgressBar progressBar;
ImageView imageView;
Button btnA, btnB, btnC,btnD;
TextView txtScore,txtQuestion;
#Override
protected void onPause() {
this.finish();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
Bundle extra = getIntent().getExtras();
if(extra!=null)
mode =extra.getString("MODE");
db = new DbHelper(this);
txtScore = (TextView)findViewById(R.id.txtScore);
txtQuestion =(TextView)findViewById(R.id.txtQuestion);
progressBar=(ProgressBar) findViewById(R.id.progreessBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB =(Button)findViewById(R.id.btnAnswerB);
btnC = (Button)findViewById(R.id.btnAnswerC);
btnD = (Button)findViewById(R.id.btnAnswerD);
imageView = (ImageView)findViewById(R.id.question_bike);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionPlay = db.getQuestionMode(mode);
totalQuestion = questionPlay.size();
mcountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mcountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion){
thisQuestion++;
txtQuestion.setText(String.format("%d %d",thisQuestion,totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int ImageID = this.getResources().getIdentifier(questionPlay.get(index).getImage().toLowerCase(),"drawable",getPackageName());
imageView.setBackgroundResource(ImageID);
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mcountDown.start();
}
else {
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL",totalQuestion);
dataSend.putInt("CORRECT",CorrectAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mcountDown.cancel();
if (index < totalQuestion){
Button clickedButton = (Button)v;
if(clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())){
score+=1;
CorrectAnswer++;
showQuestion(++index);
}
else showQuestion(++index);
txtScore.setText(String.format("S:%d",score));
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Playing.this ,MainActivity.class) ;
startActivity(intent) ;
finish() ;
}
}
I`v tried and with this code
#Override
protected void onDestroy(){
super.onDestroy;
finish();
}
but then the second activity does not start and the app crashes again.
So what to do?

Creating a very custom list

I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>
filled by data from database.
Thank you
Here it is:
public class Avancee extends Activity {
// Log tag
private static final String TAG = MainActivity2.class.getSimpleName();
// Movies json url
private static final String url = "http://blabla.com/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
hidePDialog();
String result = getIntent().getStringExtra("ITEM_EXTRAA");
System.out.println(result);
try{
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
try {
JSONObject obj = ja.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setLocation(obj.getString("location_search_text"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
It's the "id" that I want to get in the OnClick event.
use this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Movie movie= movieList.get(position);
}
});
//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object

Resources