my application not read if statement in postexecute method - android

my code will crash if i not comment statement else if (message.equals("holiday")) on postexecute tell me why is not go further if not euqal this line (message.equals("holiday")) why not print "School is off today. Reason: if i comment else if (message.equals("holiday")) this code app work fine check my if else stateement please
String message;
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
yourBoolean=false;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
displayData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
yourBoolean=true ;
if ((Category_ID.size() > 0) ) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
menu_nametxt.setText(mVal2);
}
else if (message.equals("holiday"))
{
menu_nametxt.setText("No menu available .");
listCategory.setVisibility(View.GONE);
}
else
menu_nametxt.setText("School is off today. Reason: "+mVal3);
listCategory.setVisibility(View.GONE);
}
private void displayData() {
Cursor mCursor3 = db.selectQuery("SELECT * FROM uss_vacation WHERE calendar_id);
if (mCursor3.moveToFirst()) {
do {
Vacation_Date.add(mCursor3.getString(mCursor3.getColumnIndex("date")));
if(mCursor3.getString(mCursor3.getColumnIndex("date")).equals(mydate))
{
message = "holiday";
String mVal ;
mVal = (mCursor3.getString(mCursor3.getColumnIndex("title")));
mVal2 = mVal.toString();
mCursor3.close();
return;
}
} while (mCursor3.moveToNext());
}
mCursor3.close();
}
if i comment this code application print "School is off today. Reason: text
else if (message.equals("holiday"))
// {
// menu_nametxt.setText("No menu available .");
// listCategory.setVisibility(View.GONE);
// }

Since message is null when the app is run for the first time, when the if-else statement reaches else if (message.equals("holiday"), it will throws NullPointerException instead of false and crashing the app.
see SO: Java null String equals result
Consider initialize the message with empty string instead. (i.e. message = "";).
OR
Change the order of checking to else if ("holiday".equals(message)).

Related

Android Calling Multiple methods 1 by 1

I have this function where it checks what are the choices of the users made.
So for example
there is a 4 choices:
InfoOfUp
InfoOfArt
InfoOfParish
InfoOfAteneo.
So when the user selects InfoOfUp and InfoOfArt then on the next activity, i will click a button that contains function : selected() it will check the items that was choosen by the user. if the user choose item InfoOfUp it will run a specific function and if the user choose item InfoOfArt it will also run a specific function
The problem is every item has it's own function and every item have progress dialog that marks if the function is already done or not.
So the user choose 2 items there's an error because there's 2 function being called up at the same time;
I want the function to be call 1by1 where the function waits to the other function to finish.
To avoid confusion, i call methods as function.
public void selected() {
if (InfoOfUp.select == 1) {
if (ayala == 0) {
ayala();
ayala = 1;
} else if (ayala == 1) {
}
}
if (InfoOfArt.select == 1) {
if (art == 0) {
ArtInIsland();
art = 1;
} else if (art == 1) {
}
}
if (InfoOfParish.select == 1) {
if (parish == 0) {
parish();
parish = 1;
} else if (parish == 1) {
}
}
if (InfoOfAteneo.select == 1) {
if (ateneo == 0) {
ateneogallery();
ateneo = 1;
} else if (ateneo == 1) {
}
}
Additionally, if the function calls, it will run an asynctask to get data.
here is my asynctask:
public class connectAsyncTask3 extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
private traffic traffic;
private boolean displayDestinationDetails;
String url;
boolean launchDestination;
connectAsyncTask3(String urlPass, traffic traffic, boolean displayDestinationDetails) {
this.url = urlPass;
this.traffic = traffic;
this.displayDestinationDetails = displayDestinationDetails;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
try {
super.onPreExecute();
progressDialog = new ProgressDialog(traffic.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if (result != null) {
Log.d("momo2", " : " + result);
traffic.drawPath(result);
speakOut();
}
if (displayDestinationDetails) {
Intent i = new Intent(traffic.this, poppers.class);
i.putExtra("currentMarker", traffic.markers.size());
traffic.startActivity(i);
}
}
}
Classic multi threading situation.
Create two threads, each one in the method related, start them and use
thread.join()
to begin second thread only after first finished.
great example here

NewtworkUtils.getResponseFromHttpUrl()

I am doing an Udacity course (https://classroom.udacity.com/courses/ud851/lessons/e5d74e43-743c-455e-9a70-7545a2da9783) and I have to implement the following code:
public class GithubQueryTask extends AsyncTask<URL, Void, String> {
// TODO (26) Override onPreExecute to set the loading indicator to visible
#Override
protected String doInBackground(URL... params) {
URL searchUrl = params[0];
String githubSearchResults = null;
try {
githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
} catch (IOException e) {
e.printStackTrace();
}
return githubSearchResults;
}
#Override
protected void onPostExecute(String githubSearchResults) {
// TODO (27) As soon as the loading is complete, hide the loading indicator
if (githubSearchResults != null && !githubSearchResults.equals("")) {
// TODO (17) Call showJsonDataView if we have valid, non-null results
mSearchResultsTextView.setText(githubSearchResults);
}
// TODO (16) Call showErrorMessage if the result is null in onPostExecute
}
}
At the line "githubSearchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);" I get an cannot resolve error for NetworkUtils. What to do?
Kindly check if NetworkUtils class is there in your project. Or if it is imported via gradle depedancy, check if the class is imported.

How to refresh a listview in android using asynctask?

There are two Activities. The first Activity is having the list view to see what is being shared and the second activity has an edit text box (to input inorder to share) and a button. On clicking the button, it returns me the string which is the json response and I need to add this in the previous activity.
Now the problem is, when I refresh the first page fully hitting the server it gets the response but this is not what I want. It should not go back to the server. It should simply add in the list view adapter.
I have commented the code in the PostExecute(). I have tried the everyway but it is not reflecting. I am also posting my code for your reference.
public class ShareAsyncTask extends AsyncTask<String, Void, ArrayList<EventsStreamBean>> {
public ProgressDialog pd = new ProgressDialog(EventStreamActivity.this);
String success_share_val;
#Override
protected ArrayList<EventsStreamBean> doInBackground(
String... result) {
// TODO Auto-generated method stub
JSONObject jsonobj = new JSONObject(result[0].toString());
success_share_val = jsonobj.getString(Constants.SUCCESS);
//checks the success value
if(success_share_val.equalsIgnoreCase("1")) {
JSONArray events_stream_share_array = jsonobj.getJSONArray("streamArray");
if(events_stream_share_array.length() > 0) {
for(int i=0; i<events_stream_share_array.length(); i++) {
EventsStreamBean events_stream_bean = new EventsStreamBean();
JSONObject events_stream_object = events_stream_share_array.getJSONObject(i);
events_stream_bean.setStreamId(events_stream_object.getString(Constants.STREAM_ID));
events_stream_bean.setStreamType(events_stream_object.getString(Constants.STREAM_TYPE));
events_stream_bean.setUserId(events_stream_object.getString(Constants.USER_ID));
events_stream_bean.setUserName(events_stream_object.getString(Constants.USER_NAME));
events_stream_bean.setUserType(events_stream_object.getString(Constants.USER_TYPE));
events_stream_bean.setUserAvatar(events_stream_object.getString(Constants.USER_AVATAR));
arraylist_events_stream.add(events_stream_bean);
}
}else {
Log.i("Test", "No Events Streams Available");
}
}
}catch(Exception e) {}
return arraylist_events_stream;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.pd.setMessage("Loading....");
pd.setCanceledOnTouchOutside(false);
pd.setCancelable(false);
this.pd.show();
}
#Override
protected void onPostExecute(final ArrayList<EventsStreamBean> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.pd.isShowing()) {
this.pd.dismiss();
}
Toast.makeText(EventStreamActivity.this, "Post shared successfully", Toast.LENGTH_SHORT).show();
new EventsStreamAsyncTask().execute(temp_val);
/*runOnUiThread(new Runnable() {
public void run() {
//EventStream_Customadapter adapter = (EventStream_Customadapter) list_view.getAdapter();
//adapter.clearData();
adapter.updateData(result);
//adapter = new EventStream_Customadapter(EventStreamActivity.this, arraylist_events_stream);
//list_view.setAdapter(adapter);
//adapter.notifyDataSetChanged();
}
});*/
}
}
Thank you

AsyncTask HttpParams

Could anyone help me on following questions.
1) onPostExecute - Toast.make while in background i am sending HttpRequest.
0nCraeteBunle - execute() ; startNewActivity
showing error. AsycTask# Runtime Exception .
While commenting Http request in background, no error is showed.
here, how can i know that http Request and reply finished , so that i can start my new Activity.
2) how to get HttpParams. Sending from TIBCO BE (As event with properties)
3) What if i am recieving JSONObject, JAVAObject, Integer other than String in onPostExecute. unable to override .
Try this,
protected class GetTask extends AsyncTask<Void, Void, Integer> {
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this,
"Loading", "Please wait");
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
//call ur HttpRequest
httpRequest();
return 0;
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
mHandler.sendEmptyMessage(0);
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message Msg) {
if (Flag) {
//Add ur stuff
}else{
}
And then in ur method set Flag value
public void httpRequest() {
// TODO Auto-generated method stub
String URL ="ADD UR URL";
try {
JSONObject ResponseObject = mAPIService.CallAPI(
YourActivity.this, URL);
String status = ResponseObject.getString("status");
Flag = true;
} catch (Exception err) {
Flag = false;
}
}

app crashes when implementing async Android

I'm trying to implement async on Android but it keeps crashing my app, the code in doInBackground works if I put it in the oncreate so that i know that It works
any help is greatly appreciated
thanks
here's my code :
public class accueilEco extends Activity
{
String[] param = new String[5];
TextView nom;
TextView prenom;
ProgressDialog mDialog;
Context ctxt;
TelephonyManager tm;
connectEco ce;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nom = (TextView) findViewById(R.id.user);
ctxt = getBaseContext();
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
new chargerParam().execute();
}
public class chargerParam extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... params) {
try
{
ce =new connectEco();
param = ce.recupereParam(tm.getDeviceId());
if(String.valueOf(param[4]) == String.valueOf(1))
{
Toast.makeText(ctxt, "Paramétres chargées" , Toast.LENGTH_LONG).show();
//setContentView(R.layout.home);
nom.setText(param[1]+" "+ param[2]+" - "+param[3]);
}
else
{
Toast.makeText(ctxt, "=> login" , Toast.LENGTH_LONG).show();
}
}
catch(Exception ex)
{
Toast.makeText(ctxt, "erreur" , Toast.LENGTH_LONG).show();
}
return null;
}
}
}
You cannot access UI objects from another thread than the UI thread. The code:
nom.setText(param[1]+" "+ param[2]+" - "+param[3]);
will throw the exception.
You can access the UI elements when you are in onPreExecute() or onPostExecute(Result). Accessing UI elements while youre in doInBackground, it'll result in exception.
To "fix" this you need to read through and understand the AsyncTask implementation. Instead of declaring your background task by AsyncTask<Void, Void, Void> you can provide an "result type" that the can be posted from the doInBackground method to the onPostExecute method (on the UI thread). AsyncTask<Void, Void, String> (the String type).
You would have to do something like this:
#Override
protected void onPostExecute(String result) {
if (result != null)
nom.setText(result);
// else show toast
}
#Override
protected String doInBackground(Void... params) {
try {
String[] param = new connectEco().recupereParam(tm.getDeviceId());
if (String.valueOf(param[4]) == String.valueOf(1))
return param[1]+" "+ param[2]+" - "+param[3];
} catch(Exception ex) {
// ignore and return null
}
return null;
}

Categories

Resources