how to Sending sms in android - java

I am developing an application using sms, my requirement is 1) send sms with static values 2)whenever we click on edit button we can change values and send sms , I can do both of them successfully but my third requirement is to send sms only when click on edit and change values click on submit buttons, without change value I do not want send sms. I want when click on edit button then only send sms, i tried with if(editBtn.isSelected) but it is not working. please tell any solution
my code is
xml file
<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: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=".MainActivity"
android:orientation="vertical" >
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editBtn"
android:text="EDIT"
android:textColor="#00FF00"
android:onClick="editListener"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NUMBER"
android:textSize="20dip"/>
<EditText android:layout_width="150dip"
android:layout_height="wrap_content"
android:id="#+id/numberEdit"
android:text="8989897979"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MESSAGE"
android:textSize="20dip"/>
<EditText android:layout_width="150dip"
android:layout_height="wrap_content"
android:id="#+id/messageEdit"
android:text="HAI HOW R U"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</LinearLayout>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/subBtn"
android:text="SUBMIT"/>
</LinearLayout>
Activty
public class MainActivity extends Activity {
private EditText contactEdit;
private EditText messageEdit;
private Button submitBtn;
private Button editBtn;
String contact;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactEdit = (EditText)findViewById(R.id.numberEdit);
messageEdit = (EditText)findViewById(R.id.messageEdit);
submitBtn = (Button)findViewById(R.id.subBtn);
editBtn = (Button)findViewById(R.id.editBtn);
if(editBtn.isSelected()){
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contact = contactEdit.getText().toString();
message = messageEdit.getText().toString();
try{
SmsManager manger = SmsManager.getDefault();
manger.sendTextMessage(contact, null, message, null,
null);
Toast.makeText(getApplicationContext(), "SMS SENT",
100).show();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "SMS NOT
SEND", 100).show();
e.printStackTrace();
}
}
});
}
else {
Toast.makeText(getApplicationContext(), "NOT EDITED", 100).show();
}
editBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
changeEdit();
}
});
}
private void changeEdit(){
contactEdit.setClickable(true);
contactEdit.setCursorVisible(true);
contactEdit.setFocusable(true);
contactEdit.setFocusableInTouchMode(true);
messageEdit.setClickable(true);
messageEdit.setCursorVisible(true);
messageEdit.setFocusable(true);
messageEdit.setFocusableInTouchMode(true);
}
}

Try to use OnTouchListener for the edittext
sample,
editBtn.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
changeEdit();
return true;
}
});
if its not working
Create a boolean variable Globally and make it true if u touched onto the edittext,
//In grobal
boolean e_clicked = false;
//Inside the Edittext onTouchListener
e_clicked=true;
and check
if(e_clicked)
{
// your sms send action
}

try this
public class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent=new Intent(context,Service.class);
//get lat/lng and pass it or get from service if u want
intent.putExtra("lat","lat");
intent.putExtra("lon","lng");
context.startService(intent);
}
}
public void SetAlarm(Context context) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 10);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
calendar.getTimeInMillis(), pi);
}

Related

How to show Cancel and Accept button in AlertDialog Android

I am having troubles setting the two buttons on the lower part of the alert what I am trying to do is get a similar look to the IOS look of the buttons.
here is my current code:
public void openInstructions() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
setNewDateOnView();
dialog.cancel();
}
}).setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create();
TextView myMsg = new TextView(getActivity());
myMsg.setText("ExampleText ");
myMsg.setTextSize(15);
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
dialog.setView(myMsg);
dialog.setTitle("Confirm Date of Purchase");
dialog.setOnShowListener( new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface arg0) {
Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
negativeButton.setTextColor(0xFFFF0000);
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(0xFF0000FF);
}
});
dialog.show();
}
Example of how it looks right now:
How I wanted it to look:
To design Dialog like ios , we can create custom dialog using custom layout like this :
dialog_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
android:background="#android:color/transparent"
android:orientation="vertical"
app:layout_constraintHeight_max="wrap">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/custom_bg">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="#+id/title"
android:gravity="center"
android:text="Confirm Date of Purchase"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="17sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_ll"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/rebooking_single_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textAlignment="center"
android:text="#string/dummuy"
android:textColor="#android:color/black"
android:textSize="17sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/back_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<LinearLayout
android:id="#+id/rebooking_back_button_ll"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/ok_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".49"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Ok"
android:textAlignment="center"
android:textColor="#FF6363"
android:textSize="17sp"
android:textStyle="bold" />
<View
android:layout_width="0dp"
android:layout_weight=".01"
android:layout_height="match_parent"
android:layout_below="#+id/end_time_recycle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#8F8F8F" />
<TextView
android:id="#+id/cancel_btn"
android:layout_width="0dp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textAlignment="center"
android:paddingRight="10dp"
android:text="Cancle"
android:textColor="#7BC5FF"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Main_Activity
final Dialog dialog=new Dialog(FirstActivity.this);
dialog.setCancelable(false);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_custom);
TextView cancel_btn=dialog.findViewById(R.id.cancel_btn);
cancel_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
TextView ok_btn=dialog.findViewById(R.id.ok_btn);
ok_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
dialog.dismiss();
}
});
dialog.show();
Well, as a start, google recommends you use the Android Design Guidelines when creating Android apps, really you should be sticking to those as that's what your users will be used to (not Apple's).
Also there's no reason to be assigning the dialog a TextView if all you're doing is showing text, the AlertDialog provides this functionality with setMessage.
If that hasn't convinced you to stick to the normal design rules, the only other option would be creating a Custom View and assign it to the AlertDialog with setView(similar to how you're doing it with the TextView).
Here's a tutorial on creating a Custom View
You can create a custom view such as the one sent and inflate it
Example:
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
View mView=getActivity().getLayoutInflater().inflate(R.layout.custom_layout, null);
mBuilder.setView(mView);
Button close = (Button) mView.findViewById(R.id.close);
Button OK = (Button) mView.findViewById(R.id.ok);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//close the dialog
hideDialog1();
}
});
OK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
dialog = mBuilder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
Use .setNeutralButton that make place left most
TextView textview;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button =(Button)findViewById(R.id.button1);
textview = (TextView)findViewById(R.id.textView1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this).setIcon(R.drawable.ic_launcher_background)
.setTitle("Alert Dialog Box Title")
.setMessage("Are you sure( Alert Dialog Message )")
.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Yes", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on Cancel", Toast.LENGTH_SHORT).show();
}
})
.setNeutralButton("NO", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(MainActivity.this, "You Clicked on NO", Toast.LENGTH_SHORT).show();
}
})
.show();
}
});
}
===============================================

How to Save google profile after google signin in another activity

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

NullPointerException when trying to open ZXingScannerView

I'm new to Android development so please bear with me.
I have the code inside an activity that implements qr scanning. Basically there is an activity before this segments of codes, but its just clicking of a button to go here. and whenever I do that, my app crashes and that is the error that returns. The idea of the app is once the user click the button, it will first display a qr scanner, once it has been scanned, it will now call this XML File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/scanbg"
tools:context=".ScanActivity">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="62dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question Here"
android:textSize="22dp"
android:id="#+id/questionhere"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/questionhere"
android:hint="Answer"
android:id="#+id/answerhere"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct or not indicator"
android:id="#+id/indicator"
android:layout_below="#id/answerhere"
android:textSize="18dp"/>
<!--this textview will be programmed to be changed as correct or not-->
<!--if answer == correct then "correct!" else "wrong answer"-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Point(s):"
android:id="#+id/userpoints"
android:layout_below="#id/indicator"
android:textSize="18dp"/>
<Button
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/userpoints"
android:layout_alignParentEnd="true"
android:text="Go"
android:textSize="14dp"
android:background="#B0DAD5"
android:id="#+id/gosagot"/>
</RelativeLayout>
and Here is the java file
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Button validateanswer;
ProgressDialog progress;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
validateanswer = (Button)findViewById(R.id.gosagot); //Im having error here
validateanswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
EditText theanswer = (EditText)findViewById(R.id.answerhere);
String sagotdito = theanswer.getText().toString();
RequestFactory.confirmanswer(ScanActivity.this, sagotdito, new RequestCallback<Boolean>() {
#Override
public void onSuccess(Boolean response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
//load new question
progress.dismiss();
}
});
}
#Override
public void onFailed(String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanActivity.this, "Wrong Answer. Try Again!", Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
continuation...
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
Log.w("handleResult",result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText answertoQuestion = new EditText(this);
answertoQuestion.setHint("answer");
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setContentView(R.layout.activity_scan);
TextView j = (TextView)findViewById(R.id.questionhere);
EditText k = (EditText)findViewById(R.id.answerhere);
String n = k.getText().toString();
j.setText(result.getText());
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help me.
If you check the examples of ZXing...
In your activity XML, you can add a region for the QR scanner.
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Grab that and add the scanner view there.
public class ScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_simple_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
Your error is that you can't findViewById on your button when you replaced the content view with some other view that doesn't have the ID you want to find.
And even if you "switched" findViewById and setContentView around, your code wouldn't crash, but you would no longer have a button in the content view, so having the click action would be pointless.
The problem is that the button is a part of activity_scan and you set setContentView(mScannerView) to other layout.You are bound to get this error as the activity does not have a refernce to the view(button) you are refering.
What you can do is make the mScannerView a part of your main layout and then get it with findViewById();

Country code is not getting from country code picker in Android

I am developing an signup activity in android app. I want show the country telephone code(get the country from device). It may show the list of countries containing with flag, country telephone code, country name. I get the code of country code picker from https://github.com/mukeshsolanki/country-picker-android . It contain the complete code. I want to set the default country is in the phone.
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+country);
When i using this code i get the country code "in". But i want to display telephone code and flag, name. When i open the screen. I want to display it automatically.
My code is shown below
Main.xml
<?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"
android:background="#color/colorBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<ImageView
android:background="#drawable/logo"
android:layout_gravity="center_horizontal"
android:layout_width="150dp"
android:layout_height="150dp" />
<Button
android:text="Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/buttonCountry" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:backgroundTint="#d11f08"
android:entries="#array/android_dropdown_arrays"
android:padding="5dp" />
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp">
<EditText android:id="#+id/editTextPhone"
android:layout_width="match_parent"
android:layout_height="44dp"
android:inputType="phone"
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttonSubmit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login"/>
</LinearLayout>
</ScrollView>
Main.Activity
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
Button buttonCountry;
private Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editTextPhone);
button = (Button) findViewById(R.id.buttonSubmit);
buttonCountry = (Button) findViewById(R.id.buttonCountry);
spinner1 = (Spinner) findViewById(R.id.spinner1);
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
System.out.println("country = "+countryCodeValue);
//String mPhoneNumber = tm.getLine1Number(); //not getting phone number
//System.out.println("phone no = "+mPhoneNumber);
buttonCountry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner1.setOnItemSelectedListener(new ItemSelectedListener());
final CountryPicker picker = CountryPicker.newInstance("Select Country");
picker.show(getSupportFragmentManager(), "COUNTRY_PICKER");
picker.setListener(new CountryPickerListener() {
#Override
public void onSelectCountry(String name, String code, String dialCode, int flagDrawableResID) {
// Implement your code here
Log.d("LOGTAG", "output1 : name = "+name+" code = "+code+" dialcode = "+dialCode+" flag = "+flagDrawableResID);
picker.dismiss();
}
});
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public class ItemSelectedListener implements AdapterView.OnItemSelectedListener {
//get strings of first item
String firstItem = String.valueOf(spinner1.getSelectedItem());
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (firstItem.equals(String.valueOf(spinner1.getSelectedItem()))) {
// ToDo when first item is selected
} else {
Toast.makeText(parent.getContext(),
"You have selected : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
// Todo when item is selected by the user
}
}
#Override
public void onNothingSelected(AdapterView<?> arg) {
}
}
}
Reference : https://github.com/hbb20/CountryCodePickerProject
try to get country code using Lat, long
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1); // lati : Latitude ,longi : Longitude
if (addressList != null && addressList.size() > 0) {
Address address = addressList.get(0);
code=addressList.get(0).getCountryCode();
System.out.println("code :: "+addressList.get(0).getCountryCode());
}
} catch (IOException e) {
Log.e(TAG, "Unable connect to Geocoder", e);
}
String locale = context.getResources().getConfiguration().locale.getCountry();
You can use this library
Click here
by then you can do this
new DialogPlusBuilder().blurBackground()
.buildCountriesListDialog(true,new DialogPlus.CountriesDialogListener() {
#Override
public void onItemClicked(CountryDataModel countryDataModel, DialogPlus dialogPlus) {
super.onItemClicked(countryDataModel, dialogPlus);
Toast.makeText(MainActivity.this,countryDataModel.getName()+ countryDataModel.getPhone_code(), Toast.LENGTH_SHORT).show();
}
})
.show(this.getSupportFragmentManager(), "Countries List Dialog");

SeekBar null pointer exception

I am using SeekBar to change the opacity level in drawing But I am getting Nullpointer exception in the lines
seekOpq.setMax(100);
and
seekTxt.setText(currLevel);
in the following code..
public void onClick(View view){
if(view.getId()==R.id.opacity_btn){
//launch opacity chooser
final Dialog seekDialog = new Dialog(this);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekDialog.setContentView(R.layout.opacity_chooser);
seekOpq.setMax(100);
int currLevel = drawView.getPaintAlpha();
seekTxt.setText(currLevel);
seekOpq.setProgress(currLevel);
seekOpq.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekTxt.setText(Integer.toString(progress)+" % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Button opqBtn = (Button)seekDialog.findViewById(R.id.opq_ok);
opqBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setPaintAlpha(seekOpq.getProgress());
Toast.makeText(getApplicationContext(),
"end.", Toast.LENGTH_SHORT).show();
seekDialog.dismiss();
}
});
}
I have tried giving numeric arguments manualy to these lines like
seekTxt.setText(50);
But the error still remains the same
This is my opacity_chooser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/opq_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="100%"
android:textStyle="bold" />
<SeekBar
android:id="#+id/seek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="#+id/opq_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
First set Content View after initialize seekbar & textview.
eg.
final Dialog seekDialog = new Dialog(this);
seekDialog.setContentView(R.layout.opacity_chooser);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekOpq.setMax(100);
-------------------

Categories