App is crashing after mail sent successfully using Asynctask - android

Mail is successfully sending without Asynctask. But I need to show a progress dialog while sending the mail, so I implemented Asynctask to send the mail and while sending show the progress dialog. But after mail is successfully sent, the app gets crashed if I use Asynctask. What's the issue?
I implemented the mail sending feature without Asynctask and it was working well. But I need to show the progress dialog while sending the mail, so implemented Asynctask, but app is crashing after mail is successfully sent. or else please suggest any possible way that will help me to show a progress dialog while sending the mail cause that is my main goal. Any possible solution is most welcome.
WebView webView, webView1, webView2;
WebViewClient webViewClient;
EditText uid, concern, rno;
TextView contact, reel, raise, hostel;
ImageView AIML, BD, CC, IOT, CSE;
AsyncTask mytask;
public Session session;
public String username;
public String password;
public String subject;
public String messageToSend;
public String[] blocks = {"D1 ", "D2 ", "D3 ", "D4 ", "D5 "};
public String[] floors = {"1st floor ", "2nd floor ", "3rd floor ", "4th floor ", "5th floor "};
public String itemblock;
public String itemfloor;
AutoCompleteTextView autoCompleteTextViewblock, autoCompleteTextViewfloor;
ArrayAdapter<String> adapterItems;
public NotesFragment(){
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_notes, container, false);
AIML = v.findViewById(R.id.AIML);
BD = v.findViewById(R.id.BD);
CC = v.findViewById(R.id.CC);
IOT = v.findViewById(R.id.IOT);
CSE = v.findViewById(R.id.CSE);
contact = v.findViewById(R.id.contact);
reel = v.findViewById(R.id.reel);
uid = v.findViewById(R.id.uid);
rno = v.findViewById(R.id.roomno);
concern =v.findViewById(R.id.concern);
raise = v.findViewById(R.id.raise);
hostel = v.findViewById(R.id.hostel);
autoCompleteTextViewblock = v.findViewById(R.id.sblock);
autoCompleteTextViewfloor = v.findViewById(R.id.sfloor);
ProgressDialog progressDialog = new ProgressDialog(getActivity());
//selecting block
adapterItems = new ArrayAdapter<String>(getActivity(), R.layout.list_item,blocks);
autoCompleteTextViewblock.setAdapter(adapterItems);
autoCompleteTextViewblock.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
itemblock = adapterView.getItemAtPosition(i).toString();
// Toast.makeText(getActivity(), "Block: "+itemblock, Toast.LENGTH_SHORT).show();
}
});
//
// selecting floors
adapterItems = new ArrayAdapter<String>(getActivity(), R.layout.list_item,floors);
autoCompleteTextViewfloor.setAdapter(adapterItems);
autoCompleteTextViewfloor.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
itemfloor = adapterView.getItemAtPosition(i).toString();
// Toast.makeText(getActivity(), "Floor: "+itemfloor, Toast.LENGTH_SHORT).show();
}
});
//
//open cuims
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goLink("https://uims.cuchd.in/uims/");
}
});
//hosetel
hostel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), hostel.class));
getActivity().finish();
}
});
//issue raiser
raise.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = "my email";
password = "my password";
String messageToSendone = itemblock;
String messageToSendtwo = itemfloor;
String messageToSendthree = rno.getText().toString();
String messageToSendfour = concern.getText().toString();
StringBuilder all = new StringBuilder();
all.append(messageToSendone);
all.append(messageToSendtwo);
all.append(messageToSendthree+" is facing issue of: ");
all.append(messageToSendfour);
messageToSend = all.toString();
subject = uid.getText().toString();
if (TextUtils.isEmpty(subject)){
uid.setError("Please enter your registered CU mail ID!");
return;
}
if (TextUtils.isEmpty(messageToSendone)){
autoCompleteTextViewblock.setError("Please select the block no.");
return;
}
if (TextUtils.isEmpty(messageToSendtwo)){
autoCompleteTextViewfloor.setError("Please select the floor!");
return;
}
if (TextUtils.isEmpty(messageToSendthree)){
rno.setError("Please enter your room no.!");
return;
}
if (messageToSendthree.length() < 3) {
rno.setError("Please enter valid room no.!");
return;
}
if (messageToSendthree.length() > 4) {
rno.setError("Please enter valid room no.!");
return;
}
if (TextUtils.isEmpty(messageToSendfour)){
concern.setError("Please enter your issue!");
return;
}
// Properties properties = new Properties();
// properties.put("mail.smtp.auth", "true");
// properties.put("mail.smtp.starttls.enable", "true");
// properties.put("mail.smtp.host", "smtp.gmail.com");
// properties.put("mail.smtp.port", "587");
// properties.put("mail.smtp.socketFactory.port", "587");
// properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// session = Session.getInstance(properties,
// new javax.mail.Authenticator() {
// #Override
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication(username, password);
// }
// });
mytask = new Mytask().execute();
// void startAsynTask(View v){
// Mytask task = new Mytask();
// task.execute();
// }
// progressDialog.setTitle("Processing");
// progressDialog.setMessage("Calm down, your issue is being raised...");
//// progressDialog.show();
//
// try {
//
// Message message = new MimeMessage(session);
// message.setFrom(new InternetAddress(username));
// message.setRecipients(Message.RecipientType.TO,
// InternetAddress.parse("20BCS6515#cuchd.in"));
// message.setSubject(subject);
// message.setText(messageToSend);
// Transport.send(message);
//
//
// Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();
//
// }
// catch (MessagingException e) {
// throw new RuntimeException(e);
// }
//// progressDialog.dismiss();
}
});
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
//stay nerd card
webView = v.findViewById(R.id.wb);
webView.loadUrl("https://sites.google.com/d/1r16RJHz0_2FwcYyP5V0pnrr_3pombkrA/p/1T5T_7ckEO9cSJK2TnV41PNBJXQlHzp3x/edit");
webView.setBackgroundColor(0);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
//INTERNET ERROR MSG
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/nerd.html");
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
// webView.setVerticalScrollBarEnabled(false);
// webView.getSettings().setUseWideViewPort(true);
//shottbyparth
webView2 = v.findViewById(R.id.wb2);
webView2.loadUrl("https://sites.google.com/view/shottbyparth");
webView2.setBackgroundColor(0);
//keep in app
webView2.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return true;
}
});
//INTERNET ERROR MSG
webView2.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/partherror.html");
}
});
WebSettings webSettings2 = webView2.getSettings();
webSettings2.setJavaScriptEnabled(true);
webView2.getSettings().setPluginState(WebSettings.PluginState.ON);
webView2.getSettings().setAllowFileAccess(true);
// webView2.setVerticalScrollBarEnabled(false);
// webView2.getSettings().setUseWideViewPort(true);
//magic happens compiler
webView1 = v.findViewById(R.id.wb1);
webView1.loadUrl("https://www.tutorialspoint.com/online_cpp_compiler.php");
webView1.setBackgroundColor(0);
//keep in app
webView1.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
//back button
webView1.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if(keyEvent.getAction() == keyEvent.ACTION_DOWN){
if(keyCode == KeyEvent.KEYCODE_BACK){
if(webView1 != null){
if(webView1.canGoBack()){
webView1.goBack();
}else {
getActivity().onBackPressed();
}
}
}
}
return true;
}
});
webView1.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/compiler.html");
}
});
//hiding web element with error message
webView1.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
view.loadUrl("javascript:(function() { " +
"document.getElementById('north').style.display='none';})()");
}
});
WebSettings webSettings1 = webView1.getSettings();
webSettings1.setJavaScriptEnabled(true);
webView1.setVerticalScrollBarEnabled(true);
webView1.setHorizontalScrollBarEnabled(true);
webView1.setScrollbarFadingEnabled(false);
webView1.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
// webView1.requestFocus();
//reel
reel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goLink("https://sites.google.com/view/shottbyparth");
}
});
//notes
AIML.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goLink("https://drive.google.com/drive/folders/1bolCGvvV9dKUFH8Uooe3DQGsP4gL1Vwu?usp=share_link");
}
});
BD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
}
});
CC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
}
});
IOT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
}
});
CSE.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Content coming soon...", Toast.LENGTH_SHORT).show();
}
});
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goLink("https://uims.cuchd.in/uims/");
}
});
return v;
}
//asynctask class
public class Mytask extends AsyncTask<Void, Void, Void>
{
ProgressDialog dialogue;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogue = new ProgressDialog(getActivity());
dialogue.setTitle("Processing");
dialogue.setMessage("Calm down, your issue is being raised...");
dialogue.setIndeterminate(true);
dialogue.setCancelable(false);
dialogue.show();
}
#Override
protected Void doInBackground(Void... params) {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.socketFactory.port", "587");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("20BCS6515#cuchd.in"));
message.setSubject(subject);
message.setText(messageToSend);
Transport.send(message);
Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();
}
catch (MessagingException e) {
throw new RuntimeException(e);
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(dialogue.isShowing()){
dialogue.dismiss();}
// Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();
// startActivity(new Intent(getActivity(), NotesFragment.class));
}
}
private void goLink(String s) {
Uri uri = Uri.parse(s);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
}```
I implemented the mail sending feature without Asynctask and it was working well. But I need to show the progress dialog while sending the mail, so implemented Asynctask, but app is crashing after mail is successfully sent. or else please suggest any possible way that will help me to show a progress dialog while sending the mail cause that is my main goal. Any possible solution is most welcome.

Toast needs to happen on the main thread. Move it from doInBackground to onPostExecute.
Toast.makeText(getActivity(), "Concern Raised Successfully", Toast.LENGTH_LONG).show();
You'll need to change the result type to Boolean or Exception to handle both success and failure.
private class MyTask extends AsyncTask<Void, Void, Exception> {
protected Exception doInBackground(Void... ignore) {
try {
// ...
return null;
} catch (Exception e) {
return e;
}
}
protected void onPostExecute(Exception e) {
if (e == null) {
// Handle success...
} else {
// Handle failure...
}
}
}

Related

Can't log out on button click on my android app

i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.

when i am pressing back button(up button) it is showing "app stopped unfortunately" after using volley

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
but1=(Button)findViewById(R.id.btnlogin);
//
final String Token=getIntent().getExtras().getString("token");
// Toast.makeText(getApplicationContext(),Token, Toast.LENGTH_SHORT).show();
final String firstName=getIntent().getExtras().getString("firstname");
//getting cardview data's
String url =
com.android.volley.toolbox.JsonObjectRequest jsonRequest = new com.android.volley.toolbox.JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
JSONArray obj = response.getJSONArray("result");
int o = obj.length();
Log.v("Length", String.valueOf(o));
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
//listname.add(jsonObject.getString("templateId"));
listehr.add(jsonObject.getString("templateId"));
listdate.add(jsonObject.getString("startTime"));
listtime.add(jsonObject.getString("category"));
// ehrUid.add(jsonObject.getString("ehrUid"));
List<String> compositionUid = new ArrayList<>();
// String startTime = jsonObject.getString("startTime");
// Log.v("startTime",startTime);
}
Log.v("listtime", String.valueOf(listtime.size()));
Log.v("Response", response.toString());
String total = response.getString("total");
Log.v("Total",total);
String result = response.getString("result");
Log.v("Result",result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization",Token);
return headers;
}
};
com.android.volley.toolbox.Volley.newRequestQueue(NavigationActivity.this).add(jsonRequest);
//
You have to send String Values for these two Keys "token","firstname".
final String Token=getIntent().getExtras().getString("token");
final String firstName=getIntent().getExtras().getString("firstname");
If you cant find it send the code snippet of intent in another class.
Punithapriya this is the code for main activity
public class MainActivity extends AppCompatActivity {
TextView t;
private EditText username;
private EditText password;
EditText showPsd;
CheckBox mCbShowPwd;
public Button but1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//login page using json
but1=(Button)findViewById(R.id.btnlogin);
username=(EditText)findViewById(R.id.editText2);
password=(EditText)findViewById(R.id.btnpass);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//validation for login
if(username.getText().toString().length()==0){
username.setError("Username not entered");
username.requestFocus();
}
else if(password.getText().toString().length()==0){
password.setError("Password not entered");
password.requestFocus();
}
//
String url = ;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
Log.v("Hai", response.toString());
String firstName = response.getString("firstName");
Log.v("firstName", firstName);
String organizationList = response.getString("organizationList");
Log.v("organizationList",organizationList);
String token = response.getString("token");
Log.v("token",token);
Toast.makeText(getApplicationContext(),"Logged in Suceessfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,NavigationActivity.class);
i.putExtra("token",token);
i.putExtra("firstname",firstName);
startActivity(i);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
Toast.makeText(getApplicationContext(),"Login Error", Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(MainActivity.this).add(jsonRequest);
}
});
//password
showPsd = (EditText) findViewById(R.id.btnpass);
// get the show/hide password Checkbox
mCbShowPwd = (CheckBox) findViewById(R.id.btnshow);
// add onCheckedListener on checkbox
// when user clicks on this checkbox, this is the handler.
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
showPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
} else {
// hide password
showPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
}
}
});
//
//Textview calling
final TextView regLink=(TextView)findViewById(R.id.register1);
final TextView forLink=(TextView)findViewById(R.id.forgot);
//register
regLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regIntent=new Intent(MainActivity.this,RegisterActivity.class);
MainActivity.this.startActivity(regIntent);
}
});
//forgot
forLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forIntent=new Intent(MainActivity.this,ForgotActivity.class);
MainActivity.this.startActivity(forIntent);
}
});
}
//exit dialog box
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("EHR Store");
builder.setIcon(R.drawable.sd);
builder.setMessage("Do you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

Content shared using dynamic link not getting displayed as same as it was shared after opening it

I'm developing an android app. Some data is getting retrieved from the FirebaseDatabase and is getting shown in a RecyclerView in my app.
The RecyclerView has cards in it. In every card, the images and text is shown. On the card there is a 'share' button, by clicking on which a dynamic-link is generated and is getting shared with anybody. When I click on the shared dynamic-link, the app gets open and what happens is that the image which was on the same card the share button was clicked is getting displayed, but the text is always getting displayed of the last saved data. I hope you got my point.
Here's how I'm generating dynamic-link:
Button btnShare = (Button) holder.itemView.findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URL = Uri.parse("http://www.appwebsite.com/");
holder.APP_URI = BASE_URL.buildUpon().path(imageUIDh).build();
packageName = holder.itemView.getContext().getPackageName();
deepLinkTS = Uri.parse("https://u9p25.app.goo.gl/?link="+holder.APP_URI+"&apn="+packageName+"&amv="+16+"&ad="+0);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Please help this needy: " + deepLinkTS.toString() + "\n-shared through app.");
holder.itemView.getContext().startActivity(Intent.createChooser(intent, "Share via..."));
}
});
Here's how I'm handling dynamic-link in onCreate() method of MainActivity.class:
boolean autoLaunchDeepLink = false;
AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, MainActivity.this, autoLaunchDeepLink)
.setResultCallback(
new ResultCallback<AppInviteInvitationResult>() {
#Override
public void onResult(#NonNull AppInviteInvitationResult result) {
if (result.getStatus().isSuccess()) {
// Extract deep link from Intent
Intent intent = result.getInvitationIntent();
final String deepLink = AppInviteReferral.getDeepLink(intent);
// Handle the deep link. For example, open the linked
// content, or apply promotional credit to the user's
// account.
final ProgressDialog openingSharedRequest = new ProgressDialog(MainActivity.this);
openingSharedRequest.setMessage("Opening shared help-request...");
openingSharedRequest.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent helpRequestIntent = new Intent(MainActivity.this, HelpRequestThroughDeepLink.class);
helpRequestIntent.putExtra("deepLink", deepLink);
// helpRequestIntent.putExtra("deepLinkTS", HelpRequest.deepLinkTS.toString());
// helpRequestIntent.putExtra("APP_URI", HelpRequest.ViewHolder.APP_URI.toString());
helpRequestIntent.putExtra("postedFrom", postedFromS);
// new AlertDialog.Builder(MainActivity.this)
// .setMessage(deepLink)
// .setPositiveButton("OK", null)
// .create()
// .show();
startActivity(helpRequestIntent);
openingSharedRequest.dismiss();
}
}, 1200);
// [START_EXCLUDE]
// Display deep link in the UI
// ((TextView) findViewById(R.id.link_view_receive)).setText(deepLink);
// [END_EXCLUDE]
} else {
// Log.d(TAG, "getInvitation: no deep link found.");
// Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
});
// [END get_deep_link]
Here's code from HelpRequestThroughDeepLink.java:
public class HelpRequestThroughDeepLink extends AppCompatActivity {
String deepLink, deepLinkTS, APP_URI, imageUID, imageUIDFD, hDescription;
Button btn_accept, btn_reject;
ImageView hImageHDL;
TextView imageUIDHDL, hDescriptionHDL;
DatabaseReference databaseReference1, databaseReferenceUsers;
MapView mapView;
ProgressBar progressBar;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help_request_through_deep_link);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.myCoordinatorLayout);
databaseReference1 = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/");
databaseReferenceUsers = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/users");
if (getIntent().getExtras() != null) {
deepLink = getIntent().getExtras().getString("deepLink");
deepLinkTS = getIntent().getExtras().getString("deepLinkTS");
APP_URI = getIntent().getExtras().getString("APP_URI");
postedFrom = getIntent().getExtras().getString("postedFrom");
String imageUIDD = deepLink.substring(28);
try {
imageUID = URLDecoder.decode(imageUIDD, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
} else {
Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
hImageHDL = (ImageView) findViewById(R.id.hImageHDL);
imageUIDHDL = (TextView) findViewById(R.id.imageUIDHDL);
hDescriptionHDL = (TextView) findViewById(R.id.homelessDescriptionHDL);
btn_accept = (Button) findViewById(R.id.btn_accept);
btn_reject = (Button) findViewById(R.id.btn_reject);
progressBar = (ProgressBar) findViewById(R.id.progressBar_loading_image);
}
public void operateDeepLinkRequest() {
if (deepLink.contains(imageUID)) {
if ((imageUID.startsWith("https://firebasestorage.googleapis.com/") || imageUID.startsWith("content://"))) {
retrieveRespectiveRequest();
}
}
}
public void retrieveRespectiveRequest() {
databaseReference1.child("help-requests").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
imageUIDFD = newRequest.get("imageUIDh");
hDescription = newRequest.get("hDescription");
progressBar.setVisibility(View.VISIBLE);
imageUIDHDL.setText(imageUID);
doSomethingWithPicaso(imageUID, hImageHDL);
hDescriptionHDL.setText(hDescription);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseReference1.child("help-requests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void doSomethingWithPicaso(String imageUIDh, ImageView target){
// Picasso.with(itemView.getContext()).cancelRequest(homelessImage);
Picasso.with(getBaseContext())
.load(imageUIDh)
.error(R.drawable.ic_warning_black_24dp)
.into(target, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
Toast.makeText(getBaseContext(), "Error occurred while loading images. Please retry.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) HelpRequestThroughDeepLink.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void ifNetworkAvailable(){
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
}
}
Please let me know how can I achieve this?

clicking report activity nothing was happening in android

Hi in the below code when clicking the report button not going to login activity even though it's not happening anything.
In login activity first of all I am checking the login username and password using session object.
if the username and password working fine and then want to move to next activity.
Can any one help me from this issue.
Mainactivity.java
report1=(TextView)findViewById(R.id.report1);
report=(ImageView)findViewById(R.id.report);
report1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
In the below when I am putting comment for session then it's moving but after entering the username and password it was showing logcat Admin user found but not going to next activity.it was staying in same activity itself.
update Login
public class Login extends Activity {
ImageButton login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword,ustype;
TextView tv,tv1;
Boolean isInternetPresent = false;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String queryString;
String data="";
int i;
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
SessionManager session;
private ProgressDialog progressDialog;
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// session = new SessionManager(getApplicationContext());
// session.checkLogin();
// final HashMap<String, String> user = session.getUserDetails();
login = (ImageButton)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
ustype= (EditText)findViewById(R.id.usertype);
tv = (TextView)findViewById(R.id.tv);
tv1 = (TextView)findViewById(R.id.tv1);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
cd = new ConnectionDetector(getApplicationContext());
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
String username = usname.getText().toString();
String password = pword.getText().toString();
// String name = user.get(SessionManager.KEY_USERNAME);
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
queryString = "username=" + username + "&password="
+ password ;
String usertype = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.print(usertype);
if(usertype.equalsIgnoreCase("Admin user Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this, "Login Sucess",
Toast.LENGTH_LONG).show();
}
});
Intent in=new Intent(Login.this, Reports.class);
startActivity(in);
}
else if(usertype.equalsIgnoreCase("No User Found")){
runOnUiThread(new Runnable() {
public void run() {
tv1.setText("InValid UserName and Password");
}
});
}
}
}
});
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Do not use the application's context, use the context the view currently be presented.
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(v.getContext(), Login.class);
startActivity(i);
}
});

Using android generated LoginActivity with Parse.com

I am attempting to use the android built in login view and parse together.
code
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
ParseUser newUser = new ParseUser();
newUser.setEmail(mEmail);
newUser.setPassword(mPassword);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Success!
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
// Oops!
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage().toUpperCase())
.setTitle("Oops!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
return true;
}
When I run it, I type in my email / password and the application fails.
Have look at this code:
public class LoginActivity extends PlanndActivity
{
public EditText emailField;
public EditText passwordField;
public Button loginButton;
public View.OnClickListener loginButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
PushService.setDefaultPushCallback(getApplicationContext(), PlanndActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!= null)
Log.e(Constants.TAG, "ERROR adding callback", e);
}
}
);
emailField = (EditText) findViewById(R.id.email_login);
passwordField = (EditText) findViewById(R.id.password_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setEnabled(false);
String email = ((EditText) findViewById(R.id.email_login)).getText().toString().trim();
String password = ((EditText) findViewById(R.id.password_login)).getText().toString().trim();
ParseUser.logInInBackground(email, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if(parseUser != null)
{
// User is valid and is now logged in
Log.i(Constants.TAG, "Successful login for user " + parseUser.getUsername());
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
PushService.subscribe(getApplicationContext(), "user_" + ParseUser.getCurrentUser().getObjectId(), PlanndActivity.class);
}
else
{
loginButton.setEnabled(true);
Log.i(Constants.TAG, "Unsuccessful login for user");
// sign up failed and the problems
// needs to go and do the sign up activity
}
}
});
}
});
((Button)findViewById(R.id.register_button)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
}
});
((Button)findViewById(R.id.fake_login)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailField.setText("rberidon#gmail.com");
passwordField.setText("test");
}
});
}
}
Source: plannd
Try implement this with animation of view like use inline progress bar when user clicks sign in, switch the content and progress bar depending on your logic!
The problem is that your are executing signUpInBackground() inside AsyncTask.doInBackground(). doInBackground is already using a background thread. Just use newUser.signUp()

Categories

Resources