soft keyboard not appearing - java

I have a following dialog:
import android.app.AlertDialog;
public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {
private View view;
private Context context;
private Activity activity;
private EditText ipEditText;
protected IpDiscoveryDialog(Context context) {
super(context);
this.context = context;
}
public IpDiscoveryDialog(Context context, Activity activity) {
this(context);
this.activity = activity;
}
#Override
public void setContentView(int layoutResID) {
View view = getLayoutInflater().inflate(layoutResID, null);
this.view = view;
this.setContentView(view);
}
#Override
public void setContentView(#NonNull View view) {
super.setContentView(view);
this.buildView(view);
this.setCancelable(false);
}
private void buildView(View view) {
view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
this.ipEditText = view.findViewById(R.id.ipEditText);
}
}
I open it from a different activity like this:
IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();
And the layout of the dialog is the following:
<?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:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/textView8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/set_ip_address"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="24sp" />
<EditText
android:id="#+id/ipEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/ip_address"
android:importantForAutofill="no"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/ipConfirmButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/confirm" />
</LinearLayout>
The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.
Code like this does not work:
InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);
What else can I try? What is the issue here?

Try this class
public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {
private View view;
private Context context;
private Activity activity;
private EditText ipEditText;
protected IpDiscoveryDialog(Context context) {
super(context);
this.context = context;
}
public IpDiscoveryDialog(Context context, Activity activity) {
this(context);
this.activity = activity;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.ip_discovery_dialog);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
buildView();
this.setCancelable(false);
}
private void buildView() {
findViewById(R.id.ipConfirmButton).setOnClickListener(this);
this.ipEditText = findViewById(R.id.ipEditText);
}
#Override
public void onClick(View v) {
}
}

try adding below code in menifext file -
<application
.....
android:hardwareAccelerated="true">
Hope this will help you.

Try this
ipDiscoveryDialog .setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});

Have you tried to post showSoftInput? I use a utility function for this:
public static void showSoftKeyboard(EditText v) {
Context c = v.getContext();
InputMethodManager keyboard = (InputMethodManager)
c.getSystemService(Context.INPUT_METHOD_SERVICE);
v.requestFocus();
keyboard.showSoftInput(v, 0);
}
public static boolean postShowSoftKeyboard(final EditText v) {
return v.post(new Runnable() {
#Override
public void run() {
showSoftKeyboard(v);
}
});
}

Related

Incorrect displaying items in RecyclerView while scrolling

Could you please assist in following issue:
I have incorrect displaying items in my messenger app.
My layout for items:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView 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:layout_marginHorizontal="10dp"
android:layout_marginTop="10dp"
app:cardElevation="0dp">
<TextView
android:id="#+id/message_my_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="invisible"
/>
<TextView
android:id="#+id/message_your_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:gravity="start"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="invisible"
/>
</com.google.android.material.card.MaterialCardView>
My layout for dialog activity:
<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=".DialogActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/dialog_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.AnonymousAd.AppBarOverlay">
<include
android:id="#+id/dialog_app_bar"
layout="#layout/app_bar_layout"
>
</include>
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_send"
android:visibility="invisible"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_attach"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_attach"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/dialog_gift"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
android:src="#drawable/ic_gift"
app:fabSize="mini"
tools:ignore="SpeakableTextPresentCheck" />
<EditText
android:id="#+id/dialog_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/dialog_send"
android:layout_toRightOf="#+id/dialog_gift"
android:autofillHints=""
android:backgroundTint="#color/teal_700"
android:hint="#string/dialog_enter_message"
android:inputType="textCapSentences|textMultiLine"
android:maxHeight="120dp"
android:maxLength="500"
android:minHeight="48dp"
android:textColorHint="#757575"
android:textSize="16sp" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/dialog_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/dialog_message"
android:layout_below="#+id/dialog_appbar"
android:layout_marginBottom="5dp"
android:focusedByDefault="true"
android:scrollbars="vertical" />
Class DialogActivity
public class DialogActivity extends AppCompatActivity {
private RecyclerView dialogRecyclerView;
private LinearLayoutManager layoutManager;
private final List<Message> messageList = new ArrayList<>();
private MessageAdapter messageAdapter;
private String idText;
private String userNameText;
private EditText dialogMessage;
private Toolbar toolbar;
private FloatingActionButton dialogSend;
private FloatingActionButton dialogAttach;
private String downloadedImageUrl;
private StorageTask uploadTask;
private Uri imageUri;
private DatabaseReference dialogsDataBase;
private ProgressDialog loadingBar;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference answersDataBase = db.collection("AnswersDataBase");
private StorageReference imageDataBase;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
idText = getIntent().getExtras().get("idText").toString();
userNameText = getIntent().getExtras().get("userNameText").toString();
dialogsDataBase = FirebaseDatabase.getInstance().getReference().child("DialogsDataBase").child(idText);
imageDataBase = FirebaseStorage.getInstance().getReference().child("imageDataBase");
toolbar = findViewById(R.id.dialog_app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(userNameText);
messageAdapter = new MessageAdapter(this, messageList);
dialogRecyclerView = findViewById(R.id.dialog_recycler_view);
dialogRecyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
dialogRecyclerView.setLayoutManager(layoutManager);
dialogRecyclerView.setAdapter(messageAdapter);
loadingBar = new ProgressDialog(this);
dialogMessage = findViewById(R.id.dialog_message);
dialogAttach = findViewById(R.id.dialog_attach);
dialogAttach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//startActivityForResult(intent, 438);
someActivityResultLauncher.launch(intent);
}
});
dialogMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(dialogMessage.getText().toString().length() > 0){
dialogAttach.setVisibility(View.INVISIBLE);
dialogSend.setVisibility(View.VISIBLE);
}
else {
dialogAttach.setVisibility(View.VISIBLE);
dialogSend.setVisibility(View.INVISIBLE);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
dialogSend = findViewById(R.id.dialog_send);
dialogSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(dialogMessage.getText().toString().length() > 0){
answersDataBase.document(idText).update("answer", dialogMessage.getText().toString());
dialogsDataBase.push().setValue(new Message(Paper.book().read("userName"), dialogMessage.getText().toString(), "text"));
dialogMessage.setText("");
}
}
});
}
#Override
protected void onStart() {
super.onStart();
dialogsDataBase.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Message message = snapshot.getValue(Message.class);
messageList.add(message);
messageAdapter.notifyDataSetChanged();
dialogRecyclerView.smoothScrollToPosition(dialogRecyclerView.getAdapter().getItemCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please wait, we are sending that image");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
// There are no request codes
Intent data = result.getData();
imageUri = data.getData();
StorageReference filePath = imageDataBase.child(System.currentTimeMillis() + ".jpg");
uploadTask = filePath.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if(!task.isSuccessful()){
throw task.getException();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful()){
Uri downloadUrl = task.getResult();
downloadedImageUrl = downloadUrl.toString();
answersDataBase.document(idText).update("answer", "Photo");
dialogsDataBase.push().setValue(new Message(Paper.book().read("userName"), downloadedImageUrl, "image"));
loadingBar.dismiss();
recreate();
}
}
});
}
}
});
#Override
protected void onDestroy() {
super.onDestroy();
messageList.clear();
}
#Override
protected void onPause() {
super.onPause();
messageList.clear();
}
}
Adapter class
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolderNew> {
private Context context;
private List<Message> messagesList;
private Dialog dialog;
private String userNameString;
public MessageAdapter(Context context, List<Message> messagesList){
this.context = context;
this.messagesList = messagesList;
userNameString = Paper.book().read("userName");
}
public class MessageViewHolderNew extends RecyclerView.ViewHolder{
private TextView messageMyMessage;
private TextView messageYourMessage;
private ImageView messageMyImage;
private ImageView messageYourImage;
public MessageViewHolderNew(#NonNull View itemView) {
super(itemView);
messageMyMessage = (TextView) itemView.findViewById(R.id.message_my_message);
messageYourMessage = (TextView) itemView.findViewById(R.id.message_your_message);
messageMyImage = (ImageView) itemView.findViewById(R.id.message_my_image);
messageYourImage = (ImageView) itemView.findViewById(R.id.message_your_image);
}
}
#NonNull
#Override
public MessageViewHolderNew onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_items_layout, parent, false);
return new MessageViewHolderNew(view);
}
#Override
public void onBindViewHolder(#NonNull MessageViewHolderNew holder, int position) {
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
}
else{
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
}
#Override
public int getItemCount() {
return messagesList.size();
}
}
In this place I check user name.
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
}
else{
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
If user name is my name then I set message and visible to holder.messageMyMessage.
Else I set message and visible to holder.messageYourMessage.
But sometimes message and visible are set to both messages while scrolling or sent new message. .
See attached screenshot for details
Your problem's here:
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
} else {
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
}
You're only making stuff visible, you're never hiding the other thing.
So if a specific ViewHolder is used to display one kind of message, it'll be made visible in onBindViewHolder. The view in that ViewHolder's layout will be set to VISIBLE.
Then, if you scroll down the list and the same ViewHolder is reused to display the other kind of message, the other message view in the layout will be set to VISIBLE. The other message view hasn't changed, it's still in the same state, VISIBLE. So you see them both (depending on how the layout works, one might be covering the other).
When you're using a RecyclerView, because the ViewHolders are reused (recycled) you need to set them up correctly for each item, clearing all the previous state. So in your case, for each message display, you have to either make it visible or hide it. You can't do nothing, because that can leave you with old state from the previous item it was displaying, right?
So you need to do this:
if(messagesList.get(position).getUserName().equals(userNameString)){
holder.messageMyMessage.setText(messagesList.get(position).getMessage());
holder.messageMyMessage.setVisibility(View.VISIBLE);
// now you need to make sure the other is -not- visible!
holder.messageYourMessage.setVisibility(View.GONE);
} else {
holder.messageYourMessage.setText(messagesList.get(position).getMessage());
holder.messageYourMessage.setVisibility(View.VISIBLE);
// same thing - explicitly hide the other one, assume it could be visible
holder.messageMyMessage.setVisibility(View.GONE);
}
This is the number one thing you need to do with a RecyclerView - in onBindViewHolder, always set up everything that can change depending on the item. Assume it has old data or the wrong thing set, and explicitly initialise everything. It's like a whiteboard - when you start using it you need to clean it, because maybe there's some old stuff on there

RecyclerView - I can't add more than 1 line

I'm with a problem to add more than 1 line(item) in my RecyclerView, the item overwrites the previous one when I tap the button, but if I create a List<> with data in hardcoded on onCreate, It works adding more than 1 line in the RecyclerView. Follow the code:
ListChecklistAdapter
public class ListChecklistAdapter extends RecyclerView.Adapter<ListChecklistAdapter.ListChecklistViewHolder> {
private List<Checklist> mChecklist;
private Context mCtx;
public ListChecklistAdapter(Context ctx, List<Checklist> checklists) {
mCtx = ctx;
mChecklist = checklists;
}
#Override
public ListChecklistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.item_checklist, parent, false);
return new ListChecklistViewHolder(view);
}
#Override
public void onBindViewHolder(ListChecklistViewHolder holder, int position) {
holder.cbItem.setText(mChecklist.get(position).getDescricao());
holder.cbItem.setChecked(mChecklist.get(position).isCheckado());
}
#Override
public int getItemCount() {
return mChecklist.size();
}
public class ListChecklistViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.item_checkbox)
CheckBox cbItem;
public ListChecklistViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
public void refreshData(List<Checklist> item) {
this.mChecklist.clear();
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
}
item_checklist
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/item_checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:paddingLeft="6dp"
android:text=" "
tools:text="Exemplo de item de lista" />
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity {
#BindView(R.id.rcv_lista)
RecyclerView rvLista;
int valor;
private List<Checklist> lista;
private ListChecklistAdapter listChecklistAdapter;
#BindView(R.id.btn_add_item)
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
private int cont() {
return valor++;
}
public void novoItem(View view) {
lista = new ArrayList<>();
lista.add(new Checklist("Item " + (cont() + 1), true));
loadRecycler(lista);
}
private void loadRecycler(List<Checklist> lista) {
if (listChecklistAdapter == null) {
Log.i("LOG", "IF");
listChecklistAdapter = new ListChecklistAdapter(this, lista);
rvLista.setAdapter(listChecklistAdapter);
rvLista.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rvLista.addItemDecoration(new DividerItemDecoration(this, 1));
return;
} else {
Log.i("LOG", "ELSE");
listChecklistAdapter.refreshData(lista);
listChecklistAdapter.onAttachedToRecyclerView(rvLista);
}
}
}
activity_main
<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:padding="16dp"
tools:context="teste.com.br.recyclercomcheckbox.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv_lista"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_add_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="5dp"
android:background="#android:color/transparent"
android:onClick="novoItem"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:text="+ novo item"
android:textColor="#009688" />
</LinearLayout>
Just remove this line this.mChecklist.clear(); from your refreshData() method.
public void refreshData(List<Checklist> item) {
this.mChecklist.addAll(item);
notifyDataSetChanged();
}
#Nilesh Rathod solved the problem! I just deleted this.mChecklist.clear(); from the ListCheckAdapter.java > refreshData()
Thanks for everyone to help too!

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();

Background image selecting in the app

What I wanted.
I'm currently having a problem setting the background for my app. What I wanted is a page with selections of wallpaper/background for the app user to choose. Once they chose the background the wanted by clicking the Image view, the whole app should use the image as their background.That's all.
What I've done.
I've created an activity that has 2 ImageView as the choices of wallpaper available and assigns the image view to set the background image when the user click on them. The problem now is I don't know how to save the setting and apply it to all other activity in my project.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:id="#+id/settingscreen"
tools:context="com.example.naris.auin.SettingsActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Background Selector"
android:id="#+id/textViewBackgroundSelector"
android:layout_below="#+id/switchNightMode"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="38dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewBackground1"
android:layout_marginLeft="23dp"
android:layout_marginStart="23dp"
android:src="#drawable/rateicon"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageViewBackground2"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/textViewBackgroundSelector"
android:layout_toEndOf="#+id/textViewBackgroundSelector"
android:layout_marginLeft="36dp"
android:layout_marginStart="36dp"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
Settings Activity
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final RelativeLayout Settingscreen = (RelativeLayout) findViewById(R.id.settingscreen);
ImageView ImageViewBackground1 = (ImageView) findViewById(R.id.imageViewBackground1);
ImageView ImageViewBackground2 = (ImageView) findViewById(R.id.imageViewBackground2);
ImageViewBackground1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Settingscreen.setBackgroundResource(R.drawable.faqicon);
}
});
ImageViewBackground2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Settingscreen.setBackgroundResource(R.drawable.rateicon);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == android.view.KeyEvent.KEYCODE_BACK)
{
startActivity(new Intent(SettingsActivity.this,
MainActivity.class));
finish();
}
return false;
};
}
Thanks in advance.
public class SettingsActivity extends AppCompatActivity {
private static final String PREF_NAME = "nextage_quiz";
private static final int PRIVATE_MODE = 0;
SharedPreferences getPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getPrefs = this.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
final RelativeLayout Settingscreen = (RelativeLayout) findViewById(R.id.settingscreen);
ImageView ImageViewBackground1 = (ImageView) findViewById(R.id.imageViewBackground1);
ImageView ImageViewBackground2 = (ImageView) findViewById(R.id.imageViewBackground2);
ImageViewBackground1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Settingscreen.setBackgroundResource(R.drawable.faqicon);
getPrefs.edit().putInt("id", R.drawable.faqicon).apply();
}
});
ImageViewBackground2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Settingscreen.setBackgroundResource(R.drawable.rateicon);
getPrefs.edit().putInt("id", R.drawable.faqicon).apply();
}
});
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String PREF_NAME = "nextage_quiz";
private static final int PRIVATE_MODE = 0;
SharedPreferences getPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getPrefs = this.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
ImageView background= (ImageView) findViewById(R.id.background);
if(getPrefs.getInt("id",0) != 0)
background.setBackgroundResource(getPrefs.getInt("id",0));
}
Upadate: Use these variables
private static final String PREF_NAME = "nextage_quiz";
private static final int PRIVATE_MODE = 0;
SharedPreferences getPrefs;
You should do that using Preferences.
see the link for more details...
https://developer.android.com/guide/topics/ui/settings.html

create an edit mode class with view switcher in android

I'm trying to create a page with an edit mode, what i mean by this, is that you can click on a button and all textview transforms into edittext. So i created a custom view for this with view switcher :
custom view :
public class EditabeText extends ViewSwitcher{
private Context m_context;
private View m_view;
private TextView tv;
private EditText edit;
public EditabeText(Context context, AttributeSet attrs) {
super(context, attrs);
m_context = context;
lauch();
}
public EditabeText(Context context) {
super(context);
m_context = context;
lauch();
}
public void lauch(){
inflate();
bind();
}
public void inflate(){
LayoutInflater inflater = (LayoutInflater)m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
m_view = inflater.inflate(R.layout.editable_text_view, this);
}
public void bind(){
tv = (TextView) m_view.findViewById(R.id.tv_editable_text);
edit = (EditText) m_view.findViewById(R.id.edit_editable_text);
}
public void init(){
}
public void showEditText(){
if(this.getCurrentView() == tv){
this.showNext();
Toast.makeText(m_context, "showing ... edit mode", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(m_context, "already in tv mode", Toast.LENGTH_SHORT).show();
}
}
public void showTextView(){
if(this.getCurrentView() == edit){
this.showPrevious();
Toast.makeText(m_context, "showing ... tv mode", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(m_context, "already in edit mode", Toast.LENGTH_SHORT).show();
}
}
}
And here's the xml :
<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_editable_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Text" />
<EditText
android:id="#+id/edit_editable_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:hint="Enter text" />
</ViewSwitcher>
And here's my main activity :
public class Test2 extends Activity {
EditabeText edit_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LinearLayout ll_layout = new LinearLayout(getApplicationContext());
//
edit_tv = new EditabeText(getApplicationContext());
//
Button button = new Button(getApplicationContext());
button.setText("change");
button.setOnClickListener(listener);
//
ll_layout.addView(edit_tv);
ll_layout.addView(button);
//
setContentView(ll_layout);
}
public OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_SHORT).show();
edit_tv.showEditText();
}
};
}
But it says "already in tv mode" while the TextView is the first view inside the view switcher.
Don't use in the layout file(R.layout.editable_text_view is what you posted I guess) another ViewSwitcher, because this will make you have a ViewSwitcher(EditabeText class) which has a single child view, another ViewSwitcher which has two child views(a TextView and an EditText). In this case, showing the TextView or the EditText will always fail because this.getCurrentView() == tv(or == edit) will match the wrapper ViewSwitcher to the TextView or EditText. Change your layout like this:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="#+id/tv_editable_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Text" />
<EditText
android:id="#+id/edit_editable_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:hint="Enter text" />
</merge>

Categories