ProgressBar is not stopping - android

My app contained a login button and whenever that button is pressed, I want some Progress Bar to show up so that the user knows there is something happening. I've Progress Bar in XML but now i don't know how to set it in code. Please guide me where to put lines as when I press login button a Progress Bar shown up, here is my code
<ProgressBar
android:id="#+id/loading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/layout_password"
android:layout_marginTop="30dp"
android:visibility="gone"/>
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="login"
android:layout_below="#id/layout_password"
android:layout_marginTop="30dp"/>
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText email,password;
Button login;
String url="http://192.168.1.5/Register/login.php" ;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.register);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,Register.class);
startActivity(intent);
}
});
email=findViewById(R.id.email);
password=findViewById(R.id.password);
login=findViewById(R.id.login);
builder=new AlertDialog.Builder(MainActivity.this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String user_email=email.getText().toString();
final String user_password=password.getText().toString();
if (user_email.equals("")||user_password.equals("")){
builder.setTitle("Something Went Wrong...");
dispalyAlert("Enter a valid Email and Password");
}
else {
StringRequest stringRequest=new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String code=jsonObject.getString("code");
if (code.equals("login_failed")){
builder.setTitle("Login Error...");
dispalyAlert(jsonObject.getString("message"));
}
else {
Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
Bundle bundle=new Bundle();
bundle.putString("name",jsonObject.getString("name"));
// bundle.putString("email",jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("email",user_email);
params.put("password",user_password);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
}
}
});
}
private void dispalyAlert(String message){
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
email.setText("");
password.setText("");
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
}

You can achieve this as following. you don't have to add the progressBar in xml.
public class MainActivity extends AppCompatActivity {
TextView textView;
EditText email,password;
Button login;
String url="http://192.168.1.5/Register/login.php" ;
//To show the progressBar
private ProgressDialog progress;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Prepare progressBar
progress = new ProgressDialog(this);
progress.setTitle("Please Wait!!");
progress.setMessage("Wait!!");
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
textView=findViewById(R.id.register);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,Register.class);
startActivity(intent);
}
});
email=findViewById(R.id.email);
password=findViewById(R.id.password);
login=findViewById(R.id.login);
builder=new AlertDialog.Builder(MainActivity.this);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String user_email=email.getText().toString();
final String user_password=password.getText().toString();
if (user_email.equals("")||user_password.equals("")){
builder.setTitle("Something Went Wrong...");
dispalyAlert("Enter a valid Email and Password");
}
else {
//Show the progressBar
progress.show();
StringRequest stringRequest=new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Hide the progressBar
progress.dismiss();
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String code=jsonObject.getString("code");
if (code.equals("login_failed")){
builder.setTitle("Login Error...");
dispalyAlert(jsonObject.getString("message"));
}
else {
Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
Bundle bundle=new Bundle();
bundle.putString("name",jsonObject.getString("name"));
// bundle.putString("email",jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Hide the progressBar
progress.dismiss();
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("email",user_email);
params.put("password",user_password);
return params;
}
};
MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
}
}
});
}
private void dispalyAlert(String message){
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
email.setText("");
password.setText("");
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
}
}

You should be set progress bar visible when user click on button:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String user_email=email.getText().toString();
final String user_password=password.getText().toString();
if (user_email.equals("")||user_password.equals("")){
builder.setTitle("Something Went Wrong...");
dispalyAlert("Enter a valid Email and Password");
}else{ //Right here
findViewById(R.id.loading).setVisible(View.VISIBLE);
You have to set visibility to gone when stop to load :
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
String code=jsonObject.getString("code");
if (code.equals("login_failed")){
builder.setTitle("Login Error...");
dispalyAlert(jsonObject.getString("message"));
}
else {
Intent intent=new Intent(MainActivity.this,LoginSuccess.class);
Bundle bundle=new Bundle();
bundle.putString("name",jsonObject.getString("name"));
// bundle.putString("email",jsonObject.getString("email"));
intent.putExtras(bundle);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
findViewById(R.id.loading).setVisible(View.GONE); ////Here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
findViewById(R.id.loading).setVisible(View.GONE); //Here
Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_LONG).show();
error.printStackTrace();
}

Related

How could fix "Volley client NetworkError in Android?

I turn off my firewall, but persist the problem, com.android.volley.NetworkError
Also I implemented in the manifest, but nothing
public class MainActivity extends AppCompatActivity implements
Response.Listener<JSONObject>, Response.ErrorListener {
//declare variables
Button btnlogin;
TextView tvcreateuser;
private ViewPager screenPager;
RequestQueue rq;
JsonRequest jrq;
EditText cajaUser,cajaPwd;
Button btnConsultar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//start variables
btnlogin = (Button)findViewById(R.id.btnlogin);
tvcreateuser = (TextView)findViewById(R.id.tvcreateuser);
cajaUser = (EditText)findViewById(R.id.txtUser);
cajaPwd =(EditText)findViewById(R.id.txtPwd);
btnConsultar = (Button)findViewById(R.id.btnSesion);
rq = Volley.newRequestQueue(this);
btnConsultar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
iniciarSesion();
}
});
//functions
login();
createuser();
}
private void createuser() {
tvcreateuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,CreateUserActivity.class);
startActivity(intent);
}
});
}
private void login() {
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,PrincipalActivity.class);
startActivity(intent);
}
});
}
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, "Nada perrito"+error.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(JSONObject response) {
Toast.makeText(this, "Se encontro el usuario", Toast.LENGTH_SHORT).show();
User usuario = new User();
JSONArray jsonArray = response.optJSONArray("datos");
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(0);
usuario.setUser(jsonObject.optString("user"));
usuario.setPwd(jsonObject.optString("pwd"));
usuario.setNames(jsonObject.optString("names"));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void iniciarSesion(){
String url = "http://10.62.2.71/login/sesion.php?user="+cajaUser.getText().toString()+
"&pwd="+cajaPwd.getText().toString();
jrq = new JsonObjectRequest(Request.Method.GET,url,null,this,this);
rq.add(jrq);
}
}
I turn off my firewall, but persist the problem, com.android.volley.NetworkError
Add this line to AndroidManifest.xml
<manifest ....>
<uses-permission android:name="android.permission.INTERNET" />
<application>
....
</manifest>

how to get Key Hash for facebook login using android?

am developing an app where user can login by clicking login button with facebook.For facebook login i added library etc for facebook.
i have tried everything to get keyhash but still i am unable to get key hash for development of facebook login for my app.
i have added this C:\Program Files\Java\jdk1.8.0_112\jre\bin and
this C:\OpenSSL\bin .
i tried with the method given in different sites but still some problem ..kindly help
here is my Login.java
public class Login extends AppCompatActivity {
private String eml;
private String pswrd;
private ProgressDialog pDialog;
String status="";
Button login;
// private int serverResponseCode = 0;
TextView tac1;
EditText email,pass;
private static String url_create_book = "http://cloud....com/broccoli/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
email=(EditText)findViewById(R.id.email);
pass=(EditText)findViewById(R.id.password);
tac1 = (TextView) findViewById(R.id.cAcc);
tac1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, RegistrationForm.class));
}
});
login=(Button)findViewById(R.id.lbtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
eml = email.getText().toString();
pswrd = pass.getText().toString();
// new CreateNewProduct().execute();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
if (response.trim().equals("success")) {
Toast.makeText(Login.this,"Login Success",Toast.LENGTH_SHORT).show();
//your intent code here
} else {
Toast.makeText(Login.this,"username/password incorrect",Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", eml);
params.put("password",pswrd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Login.this);
requestQueue.add(stringRequest);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

Refresh Listview of another fragment

I'm Using viewpager with 2 swiping tab layouts. In the first tablayout I post data to the server and when I switch the tab the Listview in not update. Only when I click on Listview Item and close it the Listview gets refreshed and the posted data is visible...
Question Is : How to automatically refresh Listview when data is posted to server can some one help please.
public class PagerAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PagerAdapter(FragmentManager fm,int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
RaiseComplaintFragment RFragment=new RaiseComplaintFragment();
return RFragment;
case 1:
ComplaintListFragment CFragment=new ComplaintListFragment();
return CFragment;
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
This is the method which posts data to the server
public void postDataToServer(String complaintdata) throws JSONException {
String url = URLMap.getPostComplaintUrl();
String roleId = LoggedInUserStore.getLoggedInRoleId(getContext());
String branchId = LoggedInUserStore.getLoggedInBranchId(getContext());
String compid = LoggedInUserStore.getLoggedInCompanyId(getContext());
HashMap<String, String> params = new HashMap<>();
params.put("CallRecordID", "0"); //pass 0 if we are inserting a new record always
params.put("CompanyID", compid);
params.put("BranchID", branchId);
params.put("ServiceID", sId);
params.put("CallLocationID", lId);
params.put("RaisedByID", roleId);
params.put("ComplaintDetails", complaintdata);
params.put("CallStatusID", "1");
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait..");
pDialog.setProgressStyle(pDialog.STYLE_SPINNER);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Complaint has been registered successfully");
builder.setMessage("").setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
_complaintText.setText("");
serviceSpinner.setSelection(0);
locationSpinner.setSelection(0);
pDialog.dismiss();
/*((HomeActivity)getActivity()).getViewPager().setCurrentItem(1); //onCLick of Submit it just switches the tab
String tagName="android:switcher:"+R.id.pager+":"+1;
ComplaintListFragment f2=(ComplaintListFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
f2.fetchComplaintData();*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Unable to register your request.\nPlease try later.");
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
pDialog.dismiss();
}
});
req.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue requestQueue = ((VolleyRequestQueue) getActivity().getApplication()).getRequestQueue();
requestQueue.add(req);
}
My HomeActivity class which handles two tab layouts
viewPager = (ViewPager) findViewById(R.id.view_Pager);
tabLayout = (TabLayout) findViewById(R.id.tab_Layout);
String roleID = LoggedInUserStore.getLoggedInRoleId(getApplicationContext());
if (roleID.equals("4")) {
//RAISE COMPLAINT UI. IF ROLE ID == 4 MANAGER DASHBOARD
tabLayout.addTab(tabLayout.newTab().setText("Raise Complaint"));
tabLayout.addTab(tabLayout.newTab().setText("Complaint List"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final PagerAdapter adapter =
new com.six30labs.cms.adapters.PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Second fragment which contains my listview
public class ComplaintListFragment extends Fragment {
private ListView complaintListView;
EditText _inputSearch;
ComplaintAdapter compadapter;
private static Parcelable mListViewScrollPos = null;
private RequestQueue mQueue;
ProgressBar progressBar;
String URL;
private View v;
String TAG="Second Fragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_complaint_list, container, false);
complaintListView = (ListView) v.findViewById(R.id.complaintListView);
_inputSearch = (EditText) v.findViewById(R.id.inputSearchforComplaintListFragment);
progressBar = (ProgressBar) v.findViewById(R.id.complaintListProgressBar);
fetchComplaintData();
_inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
compadapter.getFilter().filter(s.toString());
compadapter.notifyDataSetChanged();
}catch (NullPointerException e){
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (mListViewScrollPos != null) {
complaintListView.onRestoreInstanceState(mListViewScrollPos);
}
return v;
}
public void fetchComplaintData() {
progressBar.setVisibility(View.VISIBLE);
URL = URLMap.getComplaintUrl("complaint_url");
URL = URL.replace("{id}", LoggedInUserStore.getLoggedInCompanyId(getContext()));
StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
getCompliantList(response);
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue queue=((VolleyRequestQueue)getActivity().getApplication()).getRequestQueue();
queue.add(request);
/* RequestQueue requestQueue
= Volley.newRequestQueue(getContext());
requestQueue.add(request);*/
}
public void getCompliantList(String response) {
try {
List complaint = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
// complaint.add(Complaint.fromJson(jArray.getJSONObject(i)));
complaint.add(0,Complaint.fromJson(jArray.getJSONObject(i))); //To push the data to the top of the listview.
}
compadapter = new ComplaintAdapter(getContext(), complaint);
complaintListView.setAdapter(compadapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Method that will save the position the user when they scroll
//return it when the user comes back to the listView instead of it refreshing the data.
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mListViewScrollPos = complaintListView.onSaveInstanceState();
}
public void onPause() {
super.onPause();
}
public void onResume() {
super.onResume();
fetchComplaintData();
}
BroadcastReceiver For class Where your Listview is
private BroadcastReceiver updateProfileBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fire your event
}
};
Register Broadcast in onResume()
registerReceiver(updateProfileBroadcast, new IntentFilter("KEY"));
Now fire Broadcast From Fragment
Intent intent = new Intent("KEY");
getActivity().sendBroadcast(intent);
As an alternative to SID's answer you may use EventBus. It works by event-driven architecture and able to transfer information between components really easy and fast.
That's how you use it:
1) add to project in app gradle: compile 'org.greenrobot:eventbus:3.0.0'
2) Register EventBus in fragment's onCreate() where you need to update ListView: eventBus.register(this);. And don't forget to unregister it on onDestryView(): eventBus.unregister(this);
3) Add the method to your ListView fragment which will handle event with list update:
#SupressWarning("unused")
#Subscribe
public void onEvent(List<YourListViewData> event) {/* update `ListView` */};
4) Fire that event from activity\fragment when you need to update ListView:
EventBus bus = EventBus.getInstance();
eventBus.post(List<YourListViewData> yourData);

How to Flurry Intigration with FlurryAdListener in android

i want to integrate flurry in my app. in the following code i am integrate flurry but that was not working properly in android. flurry listener call its method two times. how it working please help me.
LoginActivity.java
public class LoginActivity extends Activity implements OnClickListener,
AsyncTaskCompleteListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
setContentView(R.layout.login_activity);
Map<String, String> map = new HashMap<String, String>();
map.put("url", NFLConstanants.LOGIN_URL);
map.put("username", strUser);
map.put("passwd", strPassword);
new ParseController(LoginActivity.this, map,
NFLConstanants.SERVICE_CODE0, 1);
}
#Override
protected void onStart() {
super.onStart();
System.out.println("call on start method");
FlurryAgent.onStartSession(this, MACUtils.APIKEY_FLURRY);
FlurryAgent.enableTestAds(true);
FlurryAgent.initializeAds(this);
FlurryAgent.setLogEnabled(true);
}
#Override
protected void onStop() {
super.onStop();
System.out.println("call on stop method");
FlurryAgent.onEndSession(this);
}
#Override
public void onTaskCompleted(String responce, int sc) {
if (FlurryAgent.isAdAvailable(LoginActivity.this,
MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
final String msgv = "To help keep this app free please watch this short video. Thanks";
AlertDialog.Builder dlg = new AlertDialog.Builder(
LoginActivity.this);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msgv);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
try {
MyAdListener myAdListener = new MyAdListener(
LoginActivity.this,
LoginActivity.this, "3");
FlurryAgent
.setAdListener(myAdListener);
FrameLayout container = new FrameLayout(
LoginActivity.this);
FlurryAgent
.getAd(LoginActivity.this,
MACUtils.myAdSpaceName,
container,
FlurryAdSize.FULLSCREEN,
MACUtils.timeout);
} catch (Exception e) {
e.printStackTrace();
}
}
});
AlertDialog alert = dlg.create();
alert.show();
}
}
}
MyAdListener.java
public class MyAdListener implements FlurryAdListener {
public Activity activity;
public Context ctx;
String pagePosition;
boolean isDialogLaunch = false;
public MyAdListener(Activity act, Context ctx, String page) {
this.activity = act;
this.pagePosition = page;
this.ctx = ctx;
this.isDialogLaunch = false;
}
#Override
public boolean shouldDisplayAd(String myAdSpaceName, FlurryAdType type) {
System.out.println("shouldDisplayAd:: " + type);
return true;
}
#Override
public void onAdClosed(String myAdSpaceName) {
System.out.println("onAdClosed::: " + myAdSpaceName);
if (pagePosition.equals("1") || pagePosition.equals("2")) {
actionOnFlurryVideo();
} else {
if (!FlurryAgent.isAdAvailable(activity, MACUtils.myAdSpaceName,
FlurryAdSize.FULLSCREEN, MACUtils.timeout)) {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
#Override
public void onApplicationExit(String myAdSpaceName) {
System.out.println("onApplicationExit:: " + myAdSpaceName);
actionOnFlurryVideo();
}
#Override
public void onRenderFailed(String adSpace) {
System.out.println("onRenderFailed:: " + adSpace);
actionOnFlurryVideo();
}
#Override
public void spaceDidReceiveAd(String adSpace) {
System.out.println("spaceDidReceiveAd:: " + adSpace);
}
#Override
public void spaceDidFailToReceiveAd(String adSpace) {
System.out.println("spaceDidFailToReceiveAd:: " + adSpace);
}
#Override
public void onAdClicked(String id) {
System.out.println("onAdClicked:: " + id);
}
#Override
public void onAdOpened(String id) {
System.out.println("onAdOpened::: " + id);
}
public void actionOnFlurryVideo() {
System.out.println("call actionOnflurryvideo");
if (pagePosition.equals("1") || pagePosition.equals("2")) {
if (!isDialogLaunch) {
isDialogLaunch = true;
final String msg = "Thanks for supporting our free website. Your bet has now been confirmed.";
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx);
dlg.setCancelable(false);
dlg.setTitle("Message");
dlg.setMessage(msg);
dlg.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
NavigationGroupActivity parent = ((NavigationGroupActivity) activity
.getParent());
parent.backToFirst();
}
});
AlertDialog alert = dlg.create();
alert.show();
}
} else {
Intent macIntent = new Intent(activity, MACCustomTab.class);
macIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(macIntent);
activity.finish();
}
}
}
This issue will be fixed in our next release which is expected to come out very soon.
(Full disclosure: I work in the Support team at Flurry)

can't get alert to work after AsyncTask

i'm using facebook runner to apply some facebook api tesk.
i want to check if i got a JSON object with data or and error message so i'm checking the "message" field to check if it's null.
if it is not null and i have a massage, i want to display the message and exit the application.
this is my code in my activity:
public class Loader extends Activity implements FacebookConnectionListener, ServerDataListener {
private TextView loaderStatus;
private Facebook facebook;
private AsyncFacebookRunner facebookRunner;
private FacebookConnection facebookConnection;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loader);
facebook = new Facebook(facebookAppId);
facebookRunner = new AsyncFacebookRunner(facebook);
facebookConnection = new FacebookConnection(this, 1);
facebookRunner.request("me",facebookConnection);
}
#Override
public void onFacebookResponse(final String response , int step) {
final JSONObject facebookResults = convertToJSON(response);
final Context thisContext = (Context) getBaseContext();
String id = "", name = "", gender = "", homeTown = "";
Drawable profilePicture = null;
if (step == 1) {
if (facebookResults.isNull("message")) {
try {
id = facebookResults.getString("id");
name = facebookResults.getString("name");
gender = facebookResults.getString("gender");
JSONObject homeTownObject = (JSONObject) facebookResults.get("hometown");
homeTown = homeTownObject.getString("name");
profilePicture = getProfilePicture(id);
} catch (JSONException e) {
alert("Facebook", e.toString(), "Ok", thisContext);
}
facebookCurrentUser = new FacebookCurrentUser(id, name, gender);
facebookCurrentUser.setHomeTown(homeTown);
facebookCurrentUser.setProfilePicture(profilePicture);
app.setFacebookCurrentUser(facebookCurrentUser);
facebookConnection = new FacebookConnection(this, 2);
this.runOnUiThread(new Runnable() {
public void run() {
loaderStatus.setText("Getting friends details");
}
});
}
else {
this.runOnUiThread(new Runnable() {
public void run() {
alert("Facebook", "Can't get user details! Please try again", "Ok", thisContext);
}
});
}
}
public void alert (String title, String message, String ok, Context listener)
{
AlertDialog.Builder alert = new AlertDialog.Builder(listener);
alert.setMessage(message);
alert.setTitle(title);
alert.setPositiveButton(ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
this is FacebookConnection class:
public class FacebookConnection implements RequestListener {
private FacebookConnectionListener listener;
private int step;
public FacebookConnection (FacebookConnectionListener listener, int step) {
this.listener = listener;
this.step = step;
}
public void updateFacebookListener(String response) {
listener.onFacebookResponse(response, step);
}
#Override
public void onComplete(String response, Object state) {
updateFacebookListener(response);
}
#Override
public void onIOException(IOException e, Object state) { }
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) { }
#Override
public void onMalformedURLException(MalformedURLException e, Object state) { }
#Override
public void onFacebookError(FacebookError e, Object state) { }
}
the FacebookConnectionListener interface:
public interface FacebookConnectionListener {
public void onFacebookResponse(String response, int step);
}
my alerts keep giving me the :
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
and i can't understand why.. help ?
Well, try this:
public void alert (String title, String message, String ok) {
this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog alert = new AlertDialog.Builder(Loader.this).create();
alert.setMessage(message);
alert.setTitle(title);
alert.setPositiveButton(ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
});
}
Instead of what you have now, and when you call it, just call it like any other method:
this.alert("Facebook", "Can't get user details! Please try again", "Ok")
I'm not exactly sure where it goes wrong, it even might have to do with you forgetting the create() part when constructing the dialog.
Hope this will sort things for you.
The reason it is appearing is because you are trying to update Ui from a different thread. As this is a partial code, I can suggest you changing your code to
MyActivity.this.runOnUiThread(new Runnable() {
public void run() {
loaderStatus.setText("Getting friends details");
}
});
where MyActivity is your Activity's name.
the easy way:
u can publishProgress(something)
and process the publishing, to show your alert :D

Categories

Resources