android dynamic generate edittext and use its values - android-view

My app. has a button which if it's presses a 2 editText fields apear , and if it's pressed again 2 other editText fields apear and so on.
I want to save all the data in this fields in arrayList (or any structure)
This is a sample of my code 1- The EditText field that apears:
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="50dp"
And This is the mainAcvtivity code :
LinearLayout lLayout;
ArrayList<String> mArray = new ArrayList<String>();
int numberOfBoxes = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
lLayout = (LinearLayout)findViewById(R.id.layout1);
final EditText AddEduDate = (EditText)inflater.inflate(R.layout.text, null);
final EditText AddEduInfo = (EditText)inflater.inflate(R.layout.text, null);
Button b2 = (Button)findViewById(R.id.button2);
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lLayout.getChildAt(numberOfBoxes) == null) {
lLayout.addView(AddEduDate);
lLayout.addView(AddEduInfo);
numberOfBoxes += 2;
}
}
});

If I understand your problem properly, simple
ArrayList<String> list=new ArrayList<String>();
list.add(AddEduDate.getText().toString());
should work.

Related

how can i retrieve different child firebase database in single activity

I am trying to retrieve data from Firebase Database and set them to text view. My database has different multiple child data. I want to retrieve all child in a single activity like globally. I have a different card view click in the main activity. when I click on any item it does not show the same child data with related that item. It shows single child data on every item click. How can I get them in a signal Activity on card view click? I am new to Android and I have tried multiple answers here, but failed. Can anyone help me with this?
public class GlobalActivity extends AppCompatActivity
RecyclerView mRecyclerView;
List<User> myUserList;
User mUser;
ProgressDialog progressDialog;
private DatabaseReference db;
private ValueEventListener eventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_global);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait its loding..");
mRecyclerView = (RecyclerView) findViewById(R.id.farazList);
GridLayoutManager gridLayoutManager = new GridLayoutManager(AhmedFarazActivity.this, 1);
mRecyclerView.setLayoutManager(gridLayoutManager);
myUserList = new ArrayList<>();
final ReAdapter reAdapter = new ReAdapter(GlobalActivity.this, myUserList);
mRecyclerView.setAdapter(reAdapter);
db = FirebaseDatabase.getInstance().getReference().child("Spinner").child("US");
progressDialog.show();
eventListener = db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
myUserList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
User userData = ds.getValue(User.class);
myUserList.add(userData);
}
reAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
}
Handle to click
This is handler in the adapter when I click on any item it does not show the same child data with related that item. It shows single child data on every item click.
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
// Hide data
holder.nameText.setText(models.get(position).getName());
holder.img.setImageResource(models.get(position).getImg());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int pos) {
//Go to UK Item to show UK data
if (models.get(pos).getName().equals("US")){
//Start Display Activity on click
Toast.makeText(c, "US", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, GlobalActivity.class);
c.startActivity(intent);
}
//Go to UK Item to show UK data
if (models.get(pos).getName().equals("UK")){
//Start System Info Activity on click
Toast.makeText(c, "UK", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, GlobalActivity.class);
c.startActivity(intent);
}
}
});
}
Now i figure out my solution
I add just Intent.putExtra("data","1"); in every handler click
#Override
public void onBindViewHolder(#NonNull MyHolder holder, int position) {
// Hide data
holder.nameText.setText(models.get(position).getName());
holder.img.setImageResource(models.get(position).getImg());
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int pos) {
//Go to UK Item to show UK data
if (models.get(pos).getName().equals("US")){
//Start Display Activity on click
Toast.makeText(c, "US", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, GlobalActivity.class);
intent.putExtra("data","1");
c.startActivity(intent);
}
//Go to UK Item to show UK data
if (models.get(pos).getName().equals("UK")){
//Start System Info Activity on click
Toast.makeText(c, "UK", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, GlobalActivity.class);
intent.putExtra("data","2");
c.startActivity(intent);
}
}
});
}
In GlobalActivity i create a method for data
initialize data(); inside onCreate
public class GlobalActivity extends AppCompatActivity
RecyclerView mRecyclerView;
List<User> myUserList;
User mUser;
ProgressDialog progressDialog;
private DatabaseReference db;
private ValueEventListener eventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_global);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait its loding..");
mRecyclerView = (RecyclerView) findViewById(R.id.farazList);
GridLayoutManager gridLayoutManager = new GridLayoutManager(AhmedFarazActivity.this, 1);
mRecyclerView.setLayoutManager(gridLayoutManager);
myUserList = new ArrayList<>();
final ReAdapter reAdapter = new ReAdapter(GlobalActivity.this, myUserList);
mRecyclerView.setAdapter(reAdapter);
data();
progressDialog.show();
eventListener = db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
myUserList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
User userData = ds.getValue(User.class);
myUserList.add(userData);
}
reAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
method for getting
public void data() {
String data = getIntent().getStringExtra("data");
if (data.equals("1")) {
db = FirebaseDatabase.getInstance().getReference().child("Spinner").child("India");
db.keepSynced(true);
} else if (data.equals("2")) {
db = FirebaseDatabase.getInstance().getReference().child("Spinner").child("Pak");
db.keepSynced(true);
} else if (data.equals("3")) {
db = FirebaseDatabase.getInstance().getReference().child("Spinner").child("UK");
db.keepSynced(true);
}
}

AppBarLayout CollapsingToolbar how to disable expand on EditText click?

In my test app I disable expansion of AppBarLayout when it is collapsed (by scrolling RecycleView). I do that by adding addOnOffsetChangedListener to AppBarLayout.
However, when I click EditText it expands again but, I do not want it to expand.
How to disable the expansion of AppBarLayout when I click EditText?
I have put the whole code, so that everyone can copy/paste the code, create new project and test this fast.
Here is how the .gif looks
Here is XML code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="400dp"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#android:color/transparent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/beachcroatia"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycleView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<LinearLayout
android:id="#+id/messages_linear_layout"
android:layout_width="match_parent"
android:layout_height="58dp"
android:layout_gravity="bottom"
android:background="#E1F5FE"
android:orientation="horizontal"
tools:layout_editor_absoluteY="453dp">
<EditText
android:id="#+id/editText_messageBox"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:layout_weight="0.85"
android:hint="Enter a message"/>
<ImageView
android:id="#+id/messages_sendArrow"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_gravity="center"
android:layout_weight="0.15"
android:src="#drawable/ic_send_message_" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Here is full MainActivity code:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerChat;
private AdapterChat mAdapterChat;
CollapsingToolbarLayout collapsingToolbarLayout;
AppBarLayout appBarLayout;
ImageView sendMessageImageViewButton;
EditText editTextMessage;
private List<Message> messagesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
appBarLayout = findViewById(R.id.app_bar_layout);
sendMessageImageViewButton = findViewById(R.id.messages_sendArrow);
editTextMessage = findViewById(R.id.editText_messageBox);
messagesList = new ArrayList<>();
messagesList.addAll(getMessagesList());
mRecyclerChat = findViewById(R.id.recycleView);
LinearLayoutManager manager = new LinearLayoutManager(this);
mRecyclerChat.setLayoutManager(manager);
mAdapterChat = new AdapterChat(this, messagesList);
mRecyclerChat.setAdapter(mAdapterChat);
//move to the last item in recycleview
mRecyclerChat.getLayoutManager().scrollToPosition(mAdapterChat.getMessagesObekt().size() - 1);
editTextMessage.requestFocus();
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
// Collapsed
Toast.makeText(MainActivity.this, "Collapsed", Toast.LENGTH_SHORT).show();
// disable expanding
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
} else if (verticalOffset == 0) {
Toast.makeText(MainActivity.this, "Extend", Toast.LENGTH_SHORT).show();
// Expanded
} else {
// Somewhere in between
}
}
});
//sending new message and updating recycleview
sendMessageImageViewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Message Send", Toast.LENGTH_SHORT).show();
mAdapterChat.updateLastMessage(new Message(editTextMessage.getText().toString()));
editTextMessage.getText().clear();
mRecyclerChat.getLayoutManager().scrollToPosition(mAdapterChat.getMessagesObekt().size() - 1);
}
});
}
//ading some items to a list
private List<Message> getMessagesList() {
List<Message> mMessages = new ArrayList<>();
for (int i = 0; i < 200; i++) {
mMessages.add(new Message("message " + i));
}
return mMessages;
}
}
Here is my message class where i add dummy data to show in RecycleView
public class Message {
private String message;
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Here is RecycleView Adapter code:
package com.example.petar.collapsingtolbartestiramo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class AdapterChat extends RecyclerView.Adapter<AdapterChat.ChatHolder> {
private LayoutInflater mInflater;
private List<Message> messagesObekt;
public AdapterChat(Context context, List<Message> listOfMassages) {
mInflater = LayoutInflater.from(context);
messagesObekt = new ArrayList<>();
messagesObekt.addAll(listOfMassages);
notifyDataSetChanged();
}
public void updateChat(List<Message> porukeObjekt){
this.messagesObekt.addAll(porukeObjekt);
notifyDataSetChanged();
}
public void updateLastMessage(Message porukeObjekt) {
this.messagesObekt.add(porukeObjekt);
//notifyDataSetChanged();
notifyItemInserted(messagesObekt.size());
}
public List<Message> getMessagesObekt() {
return messagesObekt;
}
#Override
public ChatHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_message, parent, false);
ChatHolder holder = new ChatHolder(view, messagesObekt);
return holder;
}
#Override
public void onBindViewHolder(ChatHolder holder, int position) {
holder.textViewMessage.setText(messagesObekt.get(position).getMessage());
}
#Override
public int getItemCount() {
return messagesObekt.size();
}
public static class ChatHolder extends RecyclerView.ViewHolder {
TextView textViewMessage;
public ChatHolder(View itemView, List<Message> messagesObekt) {
super(itemView);
textViewMessage = itemView.findViewById(R.id.rv_message);
}
}
}
Here is RecycleView item XML code (list_message.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="vertical">
<TextView
android:id="#+id/rv_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Poruka Ovdje"
android:textSize="14sp"/>
</LinearLayout>
:
EDIT
I tried adding focus listener to EditText but, that did not helped. This is how i try:
editTextMessage.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
appBarLayout.setExpanded(false);
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
}
}
});
I do not know is the best solution, but it works nice. If someone has better solution, feel free to write it.
There is indeed a better, cleaner and simpler solution.
The culprit that leads to this "issue" is actually a feature that was added by Google inside AppBarLayout.ScrollingViewBehavior. That's the one you set via app:layout_behavior="#string/appbar_scrolling_view_behavior". Inside that class, onRequestChildRectangleOnScreen calls setExpanded(false, !immediate) whenever the keyboard is shown. You simply override this method and return false to disable this default behavior. Add this class to your project:
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.appbar.AppBarLayout;
public class FixedScrollingViewBehavior extends AppBarLayout.ScrollingViewBehavior {
public FixedScrollingViewBehavior() {
super();
}
public FixedScrollingViewBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onRequestChildRectangleOnScreen(#NonNull CoordinatorLayout parent,
#NonNull View child, #NonNull Rect rectangle, boolean immediate) {
return false;
}
}
Then just use this new class by changing app:layout_behavior="#string/appbar_scrolling_view_behavior" to app:layout_behavior="your.source.package.FixedScrollingViewBehavior".
I have find the answer. I do not know is the best solution, but it works nice. If someone has better solution, feel free to write it.
So, what i done is i put the whole AppBarLayout params to 0 when i click EditText or when EditText get focus.
So, when EditText is clicked, AppBarLayout is still there but, now his height is 0 and it is not visible.
This do the trick:
//Collaps AppBarLayout
public void collapsAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
params.height = 0; // setting new param height to 0
//setting params to appbarLayout (now AppBarLayout is 0)
appBarLayout.setLayoutParams(params);
appBarLayout.setExpanded(false);
}
Also, if you want to have expand option, you need to save height of previous params and then just add that height again.
So, this is a code how i done it:
Fist, when i scroll RecycleView i disable expand of appBarLayout using addOnOffsetChangedListener. However i also save params height for future use.
int sizeParams; //save params height
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
// Collapsed
Toast.makeText(MainActivity.this, "Collapsed", Toast.LENGTH_SHORT).show();
// disable expanding and scroll
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params.setScrollFlags(0);
//saving height for future use
sizeParams = params.height;
} else if (verticalOffset == 0) {
Toast.makeText(MainActivity.this, "Extend", Toast.LENGTH_SHORT).show();
// Expanded
} else {
// Somewhere in between
}
}
});
Now i make this 2 method which i call when i need expand/collaps.
//Collaps AppBarLayout
public void collapsAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
sizeParams = params.height;//save params height for future use
params.height = 0; // setting new param height to 0
//setting params to appbarLayout (now AppBarLayout is 0
appBarLayout.setLayoutParams(params);
appBarLayout.setExpanded(false);
}
//Expand AppBarLayout
public void expandAppBarLayout(){
CoordinatorLayout.LayoutParams params =(CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
params.height = 3*sizeParams; // HEIGHT
appBarLayout.setLayoutParams(params); //add height to appbarlayout
//enable scroll and expand
AppBarLayout.LayoutParams params1 = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
params1.setScrollFlags(1);
appBarLayout.setExpanded(true);//expand
}

Could not get or set edittext value from separate OnClickListener class using android studio 3

Using eclipse i was able to get edittext value from separate onclicklistener class, but after i transfer the same style of code to android studio 3 the edittext returns empty here is my code
public class MainActivity extends AppCompatActivity {
Button btnGenerate;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the generate_btn actually works
btnGenerate = findViewById(R.id.generate_btn);
btnGenerate.setOnClickListener(new OnClickListenerGenerate());
}
}
And here is the OnClickListener class
public class OnClickListenerGenerate implements View.OnClickListener {
EditText second_digit;
private static final String TAG = OnClickListenerGenerate.class.getSimpleName();
#Override
public void onClick(View view) {
final Context context = view.getRootView().getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.activity_main, null, false);
second_digit = formElementsView.findViewById(R.id.txtSecondDigit);
//returns empty
Log.d(TAG, ">>" + second_digit.getText().toString());
}
}
I found the answer from this link Android::findViewByID - how can I get View of a TextView through a Listener of another UI element? and now it's working.
class ButtonListener implements android.view.View.OnClickListener {
public void onClick(View v) {
View parent = (View)v.getParent();
if (parent != null) {
TextView txtView = parent.findViewById(R.id.mytextview);
txtView.setText(...);
}
}
}

Multi Select Spinner Xamarin Android

I am using a spinner and an arrayAdapter to populate items in spinner. I want to make the spinner multi-selectable but I just select one row.I searched in Google, solution available in Java, but i don't have any idea on how to implement it in Xamarin.
My code is as below,
adapterList= new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItemMultipleChoice);
spnMultiTest.Adapter = adapterList;
I want to make the spinner multi-selectable but I just select one row.I searched in Google, solution available in Java, but i don't have any idea on how to implement it in Xamarin.
Basically I just translate the codes from Android Spinner with multiple choice
to Xamarin codes. I have tested it and it works fine:
MultiSpinner.cs:
public interface MultiSpinnerListener
{
void onItemsSelected(bool[] selected);
}
public class MultiSpinner : Spinner, IDialogInterfaceOnMultiChoiceClickListener, IDialogInterfaceOnCancelListener
{
Context _context;
private List<String> items;
private bool[] selected;
private String defaultText;
private MultiSpinnerListener listener;
public MultiSpinner(Context context) : base(context)
{
_context = context;
}
public MultiSpinner(Context context, IAttributeSet arg1) : base(context, arg1)
{
_context = context;
}
public MultiSpinner(Context context, IAttributeSet arg1, int arg2) : base(context, arg1, arg2)
{
_context = context;
}
public void OnClick(IDialogInterface dialog, int which, bool isChecked)
{
if (isChecked)
selected[which] = true;
else
selected[which] = false;
}
public override void OnClick(IDialogInterface dialog, int which)
{
dialog.Cancel();
}
public override bool PerformClick()
{
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.SetMultiChoiceItems(
items.ToArray(), selected, this);
builder.SetPositiveButton("OK",this);
builder.SetOnCancelListener(this);
builder.Show();
return true;
}
public void SetItems(List<String> items, String allText,
MultiSpinnerListener listener)
{
this.items = items;
this.defaultText = allText;
this.listener = listener;
// all selected by default
selected = new bool[items.Count];
for (int i = 0; i < selected.Length; i++)
selected[i] = true;
ArrayAdapter<string> adapter = new ArrayAdapter<string>(_context,Resource.Layout.simple_spinner_item,Resource.Id.tv_item,new string[] { allText });
// all text on the spinner
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(_context,Resource.Layout.simple_spinner_item, new String[] { allText });
Adapter = adapter;
}
public void OnCancel(IDialogInterface dialog)
{
Java.Lang.StringBuffer spinnerBuffer = new Java.Lang.StringBuffer();
bool someUnselected = false;
for (int i = 0; i < items.Count; i++)
{
if (selected[i] == true)
{
spinnerBuffer.Append(items[i]);
spinnerBuffer.Append(", ");
}
else
{
someUnselected = true;
}
}
String spinnerText;
if (someUnselected)
{
spinnerText = spinnerBuffer.ToString();
if (spinnerText.Length > 2)
spinnerText = spinnerText.Substring(0, spinnerText.Length - 2);
}
else
{
spinnerText = defaultText;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(_context,Resource.Layout.simple_spinner_item,Resource.Id.tv_item,new string[] { spinnerText });
Adapter = adapter;
if (listener != null)
{
listener.onItemsSelected(selected);
}
}
}
simple_spinner_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Update:
Here is the codes for using this MultiSpinner:
Main.axml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<MultiSpinner.MultiSpinner
android:id="#+id/mSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
MainActivity.cs:
public class MainActivity : Activity
{
MultiSpinner mSpinner;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
mSpinner = FindViewById<MultiSpinner>(Resource.Id.mSpinner);
List<string> items = new List<string> {
"Android",
"iOS",
"UWP"
};
mSpinner.SetItems(items, "AllText", null);
}
}

NetworkOnMainThreadException crashes android app

I built a webservice and tested it with SoapUI and everything is ok. Now when I try to submit the form to register an user, I get NetworkOnMainThreadException error. It looks the main thread is having to much work.
Can you help me with AsyncTask and doInBackground() method? Where and how should I do that? On my user register layout class (RegUser.java) or where the insert method is (UserDAO.java)?
RegUser.java
public class RegUser extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user);
final EditText username = (EditText) findViewById(R.id.username);
final EditText email = (EditText) findViewById(R.id.email);
final EditText password = (EditText) findViewById(R.id.password);
final EditText salt = (EditText) findViewById(R.id.salt);
final EditText nome = (EditText) findViewById(R.id.nome);
final EditText sobrenome = (EditText) findViewById(R.id.sobrenome);
final EditText telefone = (EditText) findViewById(R.id.telefone);
final EditText cel_wts = (EditText) findViewById(R.id.cel_wts);
final EditText rua = (EditText) findViewById(R.id.rua);
final EditText numero = (EditText) findViewById(R.id.numero);
final EditText bairro = (EditText) findViewById(R.id.bairro);
final EditText cidade = (EditText) findViewById(R.id.cidade);
final EditText estado = (EditText) findViewById(R.id.estado);
final EditText pais = (EditText) findViewById(R.id.pais);
final EditText cpf_cnpj = (EditText) findViewById(R.id.cpf_cnpj);
final EditText empresa= (EditText) findViewById(R.id.empresa);
final EditText cargo = (EditText) findViewById(R.id.cargo);
final Button cadProfile = (Button) findViewById(R.id.cadProfile);
cadProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
UserDAO dao = new UserDAO();
boolean resultado = dao.insertUser(new User(0, username.getText().toString(),
email.getText().toString(),
password.getText().toString(),
salt.getText().toString(),
nome.getText().toString(),
sobrenome.getText().toString(),
telefone.getText().toString(),
cel_wts.getText().toString(),
rua.getText().toString(),
numero.getText().toString(),
bairro.getText().toString(),
cidade.getText().toString(),
estado.getText().toString(),
pais.getText().toString(),
cpf_cnpj.getText().toString(),
empresa.getText().toString(),
cargo.getText().toString()));
if(resultado){
finish();
}else{
Toast.makeText(RegUser.this, "Erro ao cadastrar :(", Toast.LENGTH_LONG).show();
}
}
});
}
}
UserDAO.java
public class UserDAO {
private static final String URL = "...meuIP:8080/Meuprojeto/services/EventoDAO?wsdl";
private static final String NAMESPACE = "...meuprojetoWS.habitodigital.com";
private static final String INSERIR = "insertUser";
private static final String EXCLUIR = "deletetUser";
private static final String ATUALIZAR = "updateUser";
private static final String BUSCAR_TODOS = "searchAllUsers";
private static final String BUSCAR_POR_ID = "searchUserById";
public boolean insertUser(User user){
SoapObject insertUser = new SoapObject(NAMESPACE, INSERIR);
SoapObject usr = new SoapObject(NAMESPACE, "user");
usr.addProperty("id", user.getId());
usr.addProperty("username", user.getUsername());
usr.addProperty("email", user.getEmail());
usr.addProperty("password", user.getPassword());
usr.addProperty("salt", user.getSalt());
usr.addProperty("nome", user.getNome());
usr.addProperty("sobrenome", user.getSobrenome());
usr.addProperty("telefone", user.getTelefone());
usr.addProperty("cel_wts", user.getCel_wts());
usr.addProperty("rua", user.getRua());
usr.addProperty("numero", user.getNumero());
usr.addProperty("bairro", user.getBairro());
usr.addProperty("cidade", user.getCidade());
usr.addProperty("estado", user.getEstado());
usr.addProperty("pais", user.getPais());
usr.addProperty("cpf_cnpj", user.getCpf_cnpj());
usr.addProperty("empresa", user.getEmpresa());
usr.addProperty("cargo", user.getCargo());
insertUser.addSoapObject(usr);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(insertUser);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("urn:" + INSERIR, envelope);
SoapPrimitive resposta = (SoapPrimitive) envelope.getResponse();
return Boolean.parseBoolean(resposta.toString());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
I should do it in the userDOA.java. The ASynctask will look like this.
AsyncTask<String, Void, Boolean) task =new AsyncTask<String, Void, Boolean>() {
#Override
protected Boolean doInBackground(String... params) {
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("urn:" + INSERIR, envelope);
SoapPrimitive resposta = (SoapPrimitive) envelope.getResponse();
return Boolean.parseBoolean(resposta.toString());
} catch (Exception e) {
//handle exception
}
}
#Override
protected void onPostExecute(Boolean result) {
//Do something with result
}
}
You need to call it like
task.execute(params);
Hope this helps.

Resources