I developing app with ccavenue payment gateway Integration. I searched in google, I download code. but it works fine in eclipse, then comes in studio it crashes. I tried. but I didn't get output. please any one help me.
public class WebViewActivity extends Activity {
private ProgressDialog dialog;
Intent mainIntent;
String html, encVal;
public static final String TAG = "WebViewStatus : ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
mainIntent = getIntent();
Log.d(TAG,"main 1 ");
new RenderView().execute();
}
private class RenderView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(WebViewActivity.this);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
Log.d(TAG,"main 3 ");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add((NameValuePair) new BasicNameValuePair(AvenuesParams.ACCESS_CODE, mainIntent.getStringExtra(AvenuesParams.ACCESS_CODE)));
params.add((NameValuePair) new BasicNameValuePair(AvenuesParams.ORDER_ID, mainIntent.getStringExtra(AvenuesParams.ORDER_ID)));
String vResponse = sh.makeServiceCall(mainIntent.getStringExtra(AvenuesParams.RSA_KEY_URL), ServiceHandler.POST,params);//, params
System.out.println(vResponse);
if(!ServiceUtility.chkNull(vResponse).equals("")
&& ServiceUtility.chkNull(vResponse).toString().indexOf("ERROR")==-1){
StringBuffer vEncVal = new StringBuffer("");
vEncVal.append(ServiceUtility.addToPostParams(AvenuesParams.AMOUNT, mainIntent.getStringExtra(AvenuesParams.AMOUNT)));
vEncVal.append(ServiceUtility.addToPostParams(AvenuesParams.CURRENCY, mainIntent.getStringExtra(AvenuesParams.CURRENCY)));
encVal = RSAUtility.encrypt(vEncVal.substring(0,vEncVal.length()-1), vResponse);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog.isShowing())
dialog.dismiss();
Log.d(TAG,"main 4 ");
#SuppressWarnings("unused")
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
// process the html as needed by the app
String status = null;
if(html.indexOf("Failure")!=-1){
status = "Transaction Declined!";
}else if(html.indexOf("Success")!=-1){
status = "Transaction Successful!";
}else if(html.indexOf("Aborted")!=-1){
status = "Transaction Cancelled!";
}else{
status = "Status Not Known!";
}
Intent intent = new Intent(getApplicationContext(),StatusActivity.class);
intent.putExtra("transStatus", status);
startActivity(intent);
}
}
final WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webview, url);
if(url.indexOf("/ccavResponseHandler.jsp")!=-1){
webview.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
StringBuffer params = new StringBuffer();
params.append(ServiceUtility.addToPostParams(AvenuesParams.ACCESS_CODE,mainIntent.getStringExtra(AvenuesParams.ACCESS_CODE)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.MERCHANT_ID,mainIntent.getStringExtra(AvenuesParams.MERCHANT_ID)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.ORDER_ID,mainIntent.getStringExtra(AvenuesParams.ORDER_ID)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.REDIRECT_URL,mainIntent.getStringExtra(AvenuesParams.REDIRECT_URL)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.CANCEL_URL,mainIntent.getStringExtra(AvenuesParams.CANCEL_URL)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.ENC_VAL,URLEncoder.encode(encVal)));
String vPostParams = params.substring(0,params.length()-1);
try {
webview.postUrl(Constants.TRANS_URL, EncodingUtils.getBytes(vPostParams, "UTF-8"));
} catch (Exception e) {
showToast("Exception occured while opening webview.");
}
}
}
public void showToast(String msg) {
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}
}
The Error is :
--------- beginning of crash
11-16 11:19:56.256 21909-21909/com.reports.com.ccavenueseamless
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reports.com.ccavenueseamless, PID: 21909
java.lang.IllegalStateException: Could not find method Next(View)
in a parent or ancestor Context for android:onClick attribute defined on
view class android.support.v7.widget.AppCompatButton with id 'nextButton'
at android.support.v7.app.AppCompatViewInflater
$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater
$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit
$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:698)
The MainActivity is----
public class MainActivity extends AppCompatActivity {
private EditText accessCode, merchantId, currency, amount, orderId, rsaKeyUrl, redirectUrl, cancelUrl;
private Button webview;
private void init() {
accessCode = (EditText) findViewById(R.id.accessCode);
merchantId = (EditText) findViewById(R.id.merchantId);
orderId = (EditText) findViewById(R.id.orderId);
currency = (EditText) findViewById(R.id.currency);
amount = (EditText) findViewById(R.id.amount);
rsaKeyUrl = (EditText) findViewById(R.id.rsaUrl);
redirectUrl = (EditText) findViewById(R.id.redirectUrl);
cancelUrl = (EditText) findViewById(R.id.cancelUrl);
webview = (Button) findViewById(R.id.nextButton);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.activity_main);
init();
webview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Next();
}
});
//generating order number
Integer randomNum = ServiceUtility.randInt(0, 9999999);
orderId.setText(randomNum.toString());
}
public void Next() {
//Mandatory parameters. Other parameters can be added if required.
String vAccessCode = ServiceUtility.chkNull(accessCode.getText()).toString().trim();
String vMerchantId = ServiceUtility.chkNull(merchantId.getText()).toString().trim();
String vCurrency = ServiceUtility.chkNull(currency.getText()).toString().trim();
String vAmount = ServiceUtility.chkNull(amount.getText()).toString().trim();
if(!vAccessCode.equals("") && !vMerchantId.equals("") && !vCurrency.equals("") && !vAmount.equals("")){
Intent intent = new Intent(this,WebViewActivity.class);intent.putExtra(AvenuesParams.ACCESS_CODE, ServiceUtility.chkNull(accessCode.getText()).toString().trim());
intent.putExtra(AvenuesParams.MERCHANT_ID, ServiceUtility.chkNull(merchantId.getText()).toString().trim());
intent.putExtra(AvenuesParams.ORDER_ID, ServiceUtility.chkNull(orderId.getText()).toString().trim());
intent.putExtra(AvenuesParams.CURRENCY, ServiceUtility.chkNull(currency.getText()).toString().trim());
intent.putExtra(AvenuesParams.AMOUNT, ServiceUtility.chkNull(amount.getText()).toString().trim());
intent.putExtra(AvenuesParams.REDIRECT_URL, ServiceUtility.chkNull(redirectUrl.getText()).toString().trim());
intent.putExtra(AvenuesParams.CANCEL_URL, ServiceUtility.chkNull(cancelUrl.getText()).toString().trim());
intent.putExtra(AvenuesParams.RSA_KEY_URL, ServiceUtility.chkNull(rsaKeyUrl.getText()).toString().trim());
startActivity(intent);
}else{
showToast("All parameters are mandatory.");//09438576355
}
}
public void showToast(String msg) {
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}
}
the activity_main.xml is---
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="left"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/access_code" />
<EditText
android:id="#+id/accessCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="AVPE07CL82AO87EPOA" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/merchant_id" />
<EditText
android:id="#+id/merchantId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="84472"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="Order Id" />
<EditText
android:id="#+id/orderId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/currency" />
<EditText
android:id="#+id/currency"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="INR"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/amount" />
<EditText
android:id="#+id/amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="1.00"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/redirect_url" />
<EditText
android:id="#+id/redirectUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/ccavResponseHandler.jsp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/cancel_url" />
<EditText
android:id="#+id/cancelUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/ccavResponseHandler.jsp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/rsa_url" />
<EditText
android:id="#+id/rsaUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/GetRSA.jsp" />
<Button
android:id="#+id/nextButton"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:text="#string/pay_button" />
</LinearLayout>
</ScrollView>
Related
I am getting and error while uploading an image and storing data to Firebase. I am using Bitmap to display the images. After submitting the data the app crashes and returns to the previous Activity. Also, when I pick an image from the device it is not displaying in the ImageView.
My error:
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bloodsavelife, PID: 6642
java.lang.IllegalArgumentException: uri cannot be null
at com.google.android.gms.common.internal.Preconditions.checkArgument(com.google.android.gms:play-services-basement##17.2.1:35)
at com.google.firebase.storage.StorageReference.putFile(StorageReference.java:238)
at com.example.bloodsavelife.Activities.MakeRequest.uploadToFirebase(MakeRequest.java:153)
at com.example.bloodsavelife.Activities.MakeRequest.access$000(MakeRequest.java:47)
at com.example.bloodsavelife.Activities.MakeRequest$2.onClick(MakeRequest.java:121)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) I/Process: Sending signal. PID: 6642 SIG: 9
XML file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activities.MakeRequest">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="18dp"
android:text="Write your message and add an image for the community, somebody will
defintely help you if possible"
android:textColor="#android:color/black"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/post_image"
android:layout_width="192dp"
android:layout_height="150dp"
android:padding="8dp"
android:src="#drawable/ic_launcher_background_image" />
<Button
android:id="#+id/browse"
android:layout_width="141dp"
android:layout_height="57dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="60dp"
android:background="#drawable/button_bg"
android:gravity="center"
android:text="Browse"
android:textAlignment="gravity"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:background="#drawable/border_background">
<EditText
android:id="#+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#null"
android:cursorVisible="true"
android:gravity="top"
android:hint="Message to donors and mention for what purpose blood needed Include your
contact and location here."
android:maxLines="15"
android:minLines="7"
android:padding="10dp"
android:textAlignment="gravity"
android:textColor="#android:color/black"
android:textColorHint="#color/DarkGreen"
android:textSize="15sp"
android:textStyle="bold" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/bloodgroup"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Required Blood Group"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="dropdown_menu">
<AutoCompleteTextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/quantity"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Quantity Needed(in ml)"
android:inputType="text"
android:textColor="#android:color/black"
android:textSize="20sp"
app:boxBackgroundMode="outline"
app:endIconMode="clear_text">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<Button
android:id="#+id/btn_post"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:background="#drawable/button_bg"
android:text="Post Request"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</ScrollView>
Java code:
public class MakeRequest extends AppCompatActivity {
EditText message;
TextInputLayout bloodgroup, quantity;
TextView title;
ImageView image;
Uri filepath;
Bitmap bitmap;
Button postReq, browse;
private AutoCompleteTextView dropDownText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_request);
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
browse = findViewById(R.id.browse);
title = findViewById(R.id.title);
image = findViewById(R.id.image);
postReq = findViewById(R.id.btn_post);
dropDownText = findViewById(R.id.dropdown_text);
String[] item = new String[]{
"A+Ve",
"A-Ve",
"B+Ve",
"B-Ve",
"AB+Ve",
"AB-Ve",
"O+Ve",
"O-Ve"
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(
MakeRequest.this,
R.layout.dropdown_item,
item
);
dropDownText.setAdapter(adapter);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Dexter.withActivity(MakeRequest.this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "select image"), 1);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission,
PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
});
postReq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uploadToFirebase();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 1 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadToFirebase() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle("File Uploader");
dialog.show();
enter code here
message = findViewById(R.id.message);
bloodgroup = findViewById(R.id.bloodgroup);
quantity = findViewById(R.id.quantity);
FirebaseStorage storage = FirebaseStorage.getInstance();
//need improvement by using date and time instead of random method.
StorageReference uploader = storage.getReference("Image1" + new Random().nextInt(100));
uploader.putFile(filepath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
dialog.dismiss();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("RequestPost");
RequestHelper obj = new RequestHelper(message.getText().toString(),
bloodgroup.getEditText().getText().toString(), quantity.getEditText().getText().toString(),
uri.toString());
root.child(bloodgroup.getEditText().getText().toString()).setValue(obj);
message.setText("");
bloodgroup.getEditText().setText("");
quantity.getEditText().setText("");
image.setImageResource(R.drawable.ic_image_black_24dp);
Toast.makeText(getApplicationContext(), "Uploaded",
Toast.LENGTH_LONG).show();
}
});
}
})
.addOnProgressListener(snapshot -> {
float percent = (100 * snapshot.getBytesTransferred()) /
snapshot.getTotalByteCount();
dialog.setMessage("Uploaded:" + (int) percent + "%");
});
}
Try with this code
Pick an image from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(intent, 1001);
onActivityforresult get Uri
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001 && requestCode == RESULT_OK) {
filepath = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(filepath);
bitmap = BitmapFactory.decodeStream(inputStream);
image.setImageBitmap(bitmap);
} catch (Exception ex) {
// You can catch the exception here
}
}
}
I make a chat app using a video tutorial, but this tutorial does not show how to make messages from different people appear on different sides. The sender and receiver see all messages on the left. Could you please give some advices on this? Thanks in advance.
Now it looks like this
Main code
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_CODE=1;
private RelativeLayout activity_main;
private FirebaseListAdapter<Message> adapter;
private FloatingActionButton sendBtn;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SIGN_IN_CODE) {
if(requestCode == RESULT_OK) {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
} else {
Snackbar.make(activity_main, "You are not authorized", Snackbar.LENGTH_LONG).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.activity_main);
sendBtn = findViewById(R.id.btnSend);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText textField = findViewById(R.id.messageField);
if(textField.getText().toString().equals(""))
return;
FirebaseDatabase.getInstance().getReference().push().setValue(
new Message(
FirebaseAuth.getInstance().getCurrentUser().getEmail(),
textField.getText().toString()));
textField.setText("");
}
});
//Пользователь ещё не авторизован
if (FirebaseAuth.getInstance().getCurrentUser()==null)
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_CODE);
//Пользователь авторизован
else {
Snackbar.make(activity_main, "You are authorized", Snackbar.LENGTH_LONG).show();
displayAllMessages();
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
private void displayAllMessages() {
ListView listOfMessages = findViewById(R.id.list_of_messages);
FirebaseListOptions<Message> options =
new FirebaseListOptions.Builder<Message>()
.setQuery(FirebaseDatabase.getInstance().getReference(), Message.class)
.setLayout(R.layout.list_item)
.build();
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Message Class
public class Message {
private String UserName;
private String TextMessage;
private long MessageTime;
public Message() {}
public Message (String UserName, String TextMessage){
this.UserName = UserName;
this.TextMessage = TextMessage;
this.MessageTime = new Date().getTime();
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getTextMessage() {
return TextMessage;
}
public void setTextMessage(String textMessage) {
TextMessage = textMessage;
}
public long getMessageTime() {
return MessageTime;
}
public void setMessageTime(long messageTime) {
MessageTime = messageTime;
}
}
Main XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/activity_main">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send_button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
app:fabSize="normal">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#id/btnSend"
>
<EditText
android:id="#+id/messageField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" Message..."
/>
</com.google.android.material.textfield.TextInputLayout>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/text_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
XML for the message bubbles
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Try adding layout_gravity attribute in your BubbleTextView when you need this like this:
android:layout_gravity="right"
Every user will have a unique email - Let say here in the example - d#mail.ru is your email. You need to add user logic to dynamically check to decide whether you want a bubble test layout to be LEFT or RIGHT.
Update the message bubble layout.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:id="#+id/message_time"
/>
<com.github.library.bubbleview.BubbleTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:id="#+id/message_text"
android:layout_marginTop="9dp"
android:layout_below="#id/message_user"
android:textSize="18sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#fff"
android:padding="10dp"
app:angle="10dp"
app:arrowWidth="8dp"
app:arrowHeight="10dp"
app:arrowPosition="10dp"
app:bubbleColor="#03dac5"
/>
</RelativeLayout>
Adapter code:- you can update as you need either LEFT or RIGHT.
adapter = new FirebaseListAdapter<Message>(options){
#Override
protected void populateView(View v, Message model, int position) {
TextView mess_user, mess_time;
BubbleTextView mess_text;
RelativeLayout Layout = v.findViewById(R.id.parentlayout);
mess_user = v.findViewById(R.id.message_user);
mess_time = v.findViewById(R.id.message_time);
mess_text = v.findViewById(R.id.message_text);
mess_user.setText(model.getUserName());
mess_text.setText(model.getTextMessage());
mess_time.setText(DateFormat.format("dd-MM-yyyy HH:mm:ss", model.getMessageTime()));
if(!model.getUserName().equals("d#mail.ru")) {
mess_text.setGravity(Gravity.LEFT)
} else {
mess_text.setGravity(Gravity.RIGHT)
}
}
};
Check this link as a reference - https://github.com/rpadma/Trip-Planner/blob/master/app/src/main/java/com/etuloser/padma/rohit/homework09a/ChatAdapter.java
It is allowing me to login through Gmail and its showing display picture, my name etc. but its not working with other random people's id.
I've added more owners on developer.google.com and its also allowing them but not me.
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout Prof_Section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Pic;
private GoogleApiClient googleApiClient;
private static final int REQ_CODE=9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Prof_Section = (LinearLayout)findViewById(R.id.Prof_Section);
SignOut = (Button)findViewById(R.id.bn_logout);
SignIn = (SignInButton)findViewById(R.id.bn_login);
Name=(TextView)findViewById(R.id.name);
Email=(TextView)findViewById(R.id.email);
Prof_Pic=(ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,signInOptions).build();
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.bn_login:
signIn();
break;
case R.id.bn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn()
{
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent,REQ_CODE);
}
private void signOut()
{
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void handleResult(GoogleSignInResult result)
{if(result.isSuccess())
{
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
// Glide.with(this).load(img_url).into(Prof_Pic);
// Glide.with(this)
// .load(img_url)
// // .override(300, 200)
// .into(Prof_Pic);
// Glide.with(this).load(img_url).into(Prof_pic);
updateUI(true);
}
else
{updateUI(false);}
}
private void updateUI(boolean isLogin){
if(isLogin){
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility((View.GONE));
}
else
{
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==REQ_CODE)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/Prof_Section"
android:layout_width="match_parent"
android:layout_height="176dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="113dp"
android:layout_height="match_parent"
android:src="#drawable/myalpha"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="37dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Name display here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Email display here"
android:textSize="12dp"
android:textStyle="bold" />
<Button
android:id="#+id/bn_logout"
android:layout_width="match_parent"
android:layout_height="61dp"
android:text="Logout Google Account" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:id="#+id/bn_login"
>
</com.google.android.gms.common.SignInButton>
</LinearLayout>
Its logging me and showing me my details but not others people details.
I want that if they try to login, they also get there details
SignInButton Signin = findViewById(R.id.);
findViewById(R.id.bn_login).setOnClickListener(this);
findViewById(R.id.bn_login).setVisibility(View.GONE);
I am new to Android Programming. I successfully integrated the Google sign-in and successful in Passing data to another Activity. But When I am going back to the activity through the navigation drawer where I passed the data it sowing empty screen. I Want to Save user Profile in that Activity. I want to save user details by clicking the save button permanently in the app to show as a user profile. Please help me in solving this Problem. Thanks, in Advance for the Solution.
Here are my java files and XML files.
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main3Activity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="90dp"
android:layout_height="125dp"
android:src="#drawable/profilep" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Disply Name Here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Disply Email Here"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/butn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/butn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
</com.google.android.gms.common.SignInButton>
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Detail">
<ImageView
android:id="#+id/dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="#+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
Detail.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
dp = (ImageView) findViewById(R.id.dp);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
name.setText(i_name);
email.setText(i_email);
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(i_url);
InputStream is = url.openConnection().getInputStream();
final Bitmap bmp = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
#Override
public void run() {
dp.setImageBitmap(bmp);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Main3Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main2Activity.class));
finish();
}
Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.butn_logout);
SignIn = (SignInButton) findViewById(R.id.butn_login);
Name = (TextView) findViewById(R.id.name);
Email = (TextView) findViewById(R.id.email);
Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.butn_login:
signIn();
break;
case R.id.butn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, REQ_CODE);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void updateUI(boolean isLogin) {
if (isLogin) {
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
} else {
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount account = googleSignInResult.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
updateUI(true);
preferenceConfig.writeLoginStatus(true);
try {
Intent sendData = new Intent(Main3Activity.this, Detail.class);
name = account.getDisplayName();
email = account.getEmail();
img_url = account.getPhotoUrl().toString();
sendData.putExtra("p_name", name);
sendData.putExtra("p_email", email);
sendData.putExtra("p_url", img_url);
startActivity(sendData);
} catch (Exception e) {
Toast.makeText(Main3Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main3Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Use shared preferences for your purpose. You can read more about it here.
An example is provided here sharedPreferences
I am trying to create a login page. Onclick of the button, I am calling a method to verify the login credentials if already present in the backend django server. I am able to fetch the values of the username and password. The problem that I am currently facing is, if I give the login credentials already present in the backend server, the application works fine. But if I give login credentials which are not in the backend database, the application crashes. Kindly help
Code for Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/login_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/login_background"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/appName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:text="Teacher Diary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="By"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<ImageView
android:id="#+id/logo"
android:layout_width="100sp"
android:layout_height="100sp"
android:layout_gravity="center"
android:contentDescription="#string/home_screen_description"
android:src="#drawable/lo_logo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="25dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_username"
android:singleLine="true"
android:textColor="#color/blue" />
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_password"
android:imeOptions="actionGo"
android:inputType="textPassword"
android:textColor="#color/blue" />
<Button
android:id="#+id/btLogin"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="20dp"
android:background="#drawable/button_background"
android:text="#string/login"
android:textColor="#color/white"
android:textSize="20dp" />
<TextView
android:id="#+id/tvDisplayMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp"
android:text="The easiest way to conduct assessments!"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
Code for login.java
public class Login extends Activity implements View.OnClickListener {
private SQLiteDatabase m_database;
private LODatabaseHelper m_databaseHelper;
private Button m_btLogin;
private Animation m_anim;
private EditText m_etUsername, m_etPassword;
private String m_username, m_password, m_role, m_schoolId;
private TextView m_displayMessage;
private String ACCESS_TOKEN = "f59Gh28E6#2h13Y";
private static RequestToServiceCallback mGetRequestToServiceCallback;
public static void setCallback(RequestToServiceCallback callback) {
mGetRequestToServiceCallback = callback;
}
public interface RequestToServiceCallback {
void statusReporting(int id);
void stopService();
}
boolean login = true;
ProgressDialog pDialog;
//List of type books this list will store type Book which is our data model
private static List<LoginModel> logindata;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActionBar().hide();
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CC25AAE2")));
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView abTitle = (TextView) findViewById(titleId);
abTitle.setTextSize(15.5f);
abTitle.setTextColor(Color.WHITE);
SharedPreferences prefs = this.getSharedPreferences("global_settings",
Context.MODE_PRIVATE);
m_username = prefs.getString("username", "");
m_role = prefs.getString("role", "");
if (m_username.contentEquals("")) {
// do Nothing and continue further the user hasn't logged in yet.
// mSync.adminSync("2");
} else {
Intent intent;
if (m_role.contentEquals("admin"))
intent = new Intent(getApplicationContext(), AdminSync.class);
else
intent = new Intent(getApplicationContext(), Home.class);
finish();
startActivity(intent);
}
setContentView(R.layout.login);
/** Initialise m_database variables */
m_databaseHelper = LODatabaseHelper.getHelper(getApplicationContext());
m_database = m_databaseHelper.getWritableDatabase();
LODatabaseUtility.getInstance().setDatabase(m_database);
m_btLogin = (Button) findViewById(R.id.btLogin);
m_btLogin.setOnClickListener(this);
m_displayMessage = (TextView) findViewById(R.id.tvDisplayMessage);
m_etUsername = (EditText) findViewById(R.id.etUserName);
m_etPassword = (EditText) findViewById(R.id.etPassword);
/* Put the last login credentials into the edit texts */
String lastUsername = prefs.getString("username_last", "");
String lastPassword = prefs.getString("password_last", "");
if (lastUsername.contentEquals("")) {
/* Do Nothing */
} else {
m_etUsername.setText(lastUsername);
m_etPassword.setText(lastPassword);
}
setAnimationValue();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void setAnimationValue() {
m_anim = new AlphaAnimation(0.0f, 1.0f);
m_anim.setDuration(100); // You can manage the time of the blink with
// this parameter
m_anim.setStartOffset(20);
m_anim.setRepeatMode(Animation.REVERSE);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btLogin:
/* check the username and password */
if (m_etUsername.getText().length() == 0) {
m_displayMessage.setText("Enter User Name");
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Name and Password");
}
return;
}
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Password");
return;
}
m_username = m_etUsername.getText().toString();
m_password = m_etPassword.getText().toString();
//Calling the method that will fetch data
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
break;
}
}
private void getLoginDetails(final String m_username, final String m_password, final String ACCESS_TOKEN) {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(Login.this, "Please wait... ", "Login in progress", false, false);
Log.e("m_username:", m_username);
Log.e("m_password:", m_password);
App.getRestClient()
.getLoginService()
.getLoginData(m_username, m_password, ACCESS_TOKEN,
new Callback<List<LoginAPIModel>>() {
#Override
public void failure(RetrofitError arg0) {
if(arg0.getKind() == RetrofitError.Kind.CONVERSION || arg0.getKind() == RetrofitError.Kind.NETWORK){
Log.e("Exception","");
}
/*Log.e( "TAG" + "ERROR", "Logindetails table: start = "
+ "" + retrofitError.getMessage());
if (retrofitError.getKind() == RetrofitError.Kind.CONVERSION
|| retrofitError.getKind() == RetrofitError.Kind.NETWORK) {
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
} else {
mGetRequestToServiceCallback.stopService();
}*/
}
#Override
public void success(List<LoginAPIModel> arg0,
Response response) {
//Dismissing the loading progressbar
loading.dismiss();
Log.e("schoolid", arg0.get(0).getSchoolId());
Log.e("username:", arg0.get(0).getUsername());
Log.e("role:", arg0.get(0).getRole());
SharedPreferences prefs = getSharedPreferences(
"global_settings",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("school_id",
arg0.get(0).getSchoolId());
editor.putString("username",
arg0.get(0).getUsername());
editor.putString("password",
arg0.get(0).getPassword());
editor.putString("role",
arg0.get(0).getRole());
editor.putString("email",
arg0.get(0).getEmail());
editor.putString("user",
arg0.get(0).getUser());
editor.putString("otp",
arg0.get(0).getOtp());
editor.putString("telephone_no",
arg0.get(0).getTelephoneNo());
editor.commit();
String temp1 = arg0.get(0).getRole();
Log.e("Temp1 values:", temp1);
String tempUsername=arg0.get(0).getUsername();
Log.e("username values:", tempUsername);
String tempPassword=arg0.get(0).getPassword();
Log.e("password values:", tempPassword);
Intent intent = null;
if (temp1.contentEquals("admin")) {
intent = new Intent(Login.this, AdminSync.class);
intent.putExtra("mSchoolId", m_schoolId);
finish();
startActivity(intent);
new loginUser().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else if (temp1.contentEquals("teacher")) {
loading.dismiss();
m_displayMessage.setText("Invalid username password !");
} else {
//intent = new Intent(Login.this, Home.class);
}
//
}
});
}
My Logcat:
05-03 13:02:17.156 13719-13719/? E/m_username:: GChjvbj
05-03 13:02:17.156 13719-13719/? E/m_password:: chknmnvv
05-03 13:02:17.293 7409-7419/? E/Parcel: Reading a NULL string not supported here.
05-03 13:02:17.555 13719-13719/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.learningoutcomes, PID: 13719
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.learningoutcomes.Login$1.success(Login.java:206)
at com.learningoutcomes.Login$1.success(Login.java:184)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)