I am a student who currently taking mobile application development. Although my app can run but it doesnt show any activity instead of just give me W/RecyclerView: No adapter attached; skipping layout. I dont know how to solve the issue, so I was hoping can get some guidlines from experts.
Here is my code
MainActivity.java
package my.edu.utar.practicalassignment;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private Toolbar tool;
private TextView textView;
private RecyclerView recyclerView;
private Button AddBtn;
RecyclerView.LayoutManager layoutManager;
private FirebaseAuth auth;
private DatabaseReference ref;
private String userID = "";
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tool = findViewById(R.id.toolbar);
setSupportActionBar(tool);
//getSupportActionBar().setTitle("Today's Spending");
textView=findViewById(R.id.totalCashBack);
recyclerView =findViewById(R.id.recycle_view);
// recyclerView =(RecyclerView)findViewById(R.id.recycleView);
// layoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(layoutManager);
AddBtn = findViewById(R.id.add_new);
auth = FirebaseAuth.getInstance();
userID = auth.getCurrentUser().getUid();
ref = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
// if(userID !=null){
// try{
// ref = FirebaseDatabase.getInstance().getReference().child("expenses").child(userID);
//
// }catch (NullPointerException ex){
// ex.printStackTrace();
// }
// }
progressDialog = new ProgressDialog(this);
AddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addItem();
}
});
}
private void addItem() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater layout = LayoutInflater.from(this);
View view = layout.inflate(R.layout.input_layout, null);
alert.setView(view);
final AlertDialog dialog = alert.create();
dialog.setCancelable(false);
final Spinner spinnerItem = view.findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.category));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerItem.setAdapter(adapter);
final EditText amount = view.findViewById(R.id.insert_amount);
final EditText notes = view.findViewById(R.id.insert_note);
final Button saveButton = view.findViewById(R.id.add_button);
final Button cancelButton = view.findViewById(R.id.cancel_button);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountGet = amount.getText().toString();
String notesGet = notes.getText().toString();
String categoryGet = spinnerItem.getSelectedItem().toString();
Drawable icon = getResources().getDrawable(R.drawable.error);
if(amountGet.isEmpty()){
amount.setError("Please enter an amount!!!", icon );
return;
}
if(notesGet.isEmpty()){
notes.setError("Please enter a notes!!!", icon );
return;
}
if(categoryGet.equals("Select a Category")){
Toast.makeText(MainActivity.this, "Please select a valid category", Toast.LENGTH_SHORT).show();
}
else{
progressDialog.setMessage("Had added the information into database");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
String id = ref.push().getKey();
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar calendar = Calendar.getInstance();
String date = format.format(calendar.getTime());
Data inform = new Data(categoryGet, date, id, notesGet, Integer.parseInt(amountGet));
ref.child(id).setValue(inform).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Information added successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Fail to add the information", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
});
}
dialog.dismiss();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
}
MainActivity.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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff00"
android:elevation="4dp" />
<TextView
android:id="#+id/totalCashBack"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:text=" Total Cash Back = RM 0"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycle_view"
android:layout_width="match_parent"
android:layout_height="556dp" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</LinearLayout>
<Button
android:id="#+id/add_new"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="16dp"
android:backgroundTint="#ffff00"
android:text="Add"
app:fabSize="normal" />
</LinearLayout>
InputLayout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:elevation="10dp"
app:cardElevation="10dp"
android:layout_margin="10dp"
android:orientation="vertical"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#000"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="What did you had spend on ?"
android:gravity="center"
android:textColor="#fff"
android:textStyle="bold"
android:layout_margin="5dp"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#ffff00"
android:entries="#array/category"/>
<EditText
android:id="#+id/insert_amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Please enter a amount:"
android:textColor="#fff"
android:inputType="number"
android:textColorHint="#fff"/>
<EditText
android:id="#+id/insert_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Please enter a note:"
android:textColor="#fff"
android:textColorHint="#fff"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<Button
android:id="#+id/cancel_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Cancel"
android:textAllCaps="false"
android:textColor="#000"
android:textStyle="bold"
android:background="#fff"
android:layout_margin="2dp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<Button
android:id="#+id/add_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Transaction"
android:textAllCaps="false"
android:textColor="#000"
android:textStyle="bold"
android:background="#ffff00"
android:layout_margin="2dp"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
strings.xml
<resources>
<string name="app_name">PracticalAssignment</string>
<string-array name="category">
<item>Select a category</item>
<item>Petrol Spend</item>
<item>Groceries Spend</item>
<item>eWallet Transaction</item>
<item>Other Eligible Spend</item>
</string-array>
</resources>
You have to create an adapter class and add with your recycler view.
The basic snippet to set adapter to recycler view is like bellow
YourAdater adapter = YourAdater();
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
for more detail that how to create a RecyclerView AdapterClass you can see this or this
Related
I am programming a simple search for users but my app is not displaying the results of the query and crashes about 40% of the time after I click search. Here is my code. Any advice would be appreciated.
My Activity:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.MyApp.Objects.ParticipantsObject;
import com.MyApp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class ParticipantsActivity extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_neighbors);
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Participants");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(view -> {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(ParticipantsActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText);
FirebaseRecyclerOptions<ParticipantsObject> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<ParticipantsObject>()
.setQuery(firebaseSearchQuery, ParticipantsObject.class)
.build();
class UserHolder extends RecyclerView.ViewHolder {
private TextView imageThumbTextView, nameTextView
UserHolder(View itemView) {
super(itemView);
imageThumbTextView = itemView.findViewById(R.id.profile_image);
nameTextView = itemView.findViewById(R.id.name_text);
}
void setUsers(ParticipantsObject participantsObject) {
String imageThumb = driverObject.getThumb_image();
imageThumbTextView.setText(imageThumb);
String name = participantsObject.getName();
nameTextView.setText(name);
}
}
FirebaseRecyclerAdapter<ParticipantsObject, UserHolder> firebaseRecyclerAdapter;
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ParticipantsObject, UserHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull UserHolder userHolder, int position, #NonNull ParticipantsObject participantsObject) {
userHolder.setUsers(participantsObject);
}
#Override
public UserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UserHolder(view);
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
}
My activity_participants.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context="com.MyApp.ParticipantsActivity">
<TextView
android:id="#+id/heading_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Firebase Search"
android:textColor="#555555"
android:textSize="24sp" />
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/heading_label"
android:layout_below="#+id/heading_label"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_toStartOf="#+id/search_btn"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search here"
android:inputType="textPersonName"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:textColor="#999999"
android:textSize="16sp" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_field"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/search_field"
android:layout_marginRight="30dp"
android:background="#android:color/background_light"
app:srcCompat="#mipmap/search_button" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/search_field"
android:layout_marginTop="50dp">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
My list layout:
<?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">
<ImageView
android:id="#+id/profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
app:srcCompat="#mipmap/ic_default_user" />
<TextView
android:id="#+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="14dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="213dp"
android:layout_marginRight="20dp"
android:layout_toEndOf="#+id/profile_image"
android:text="Username"
android:textColor="#555555"
android:textSize="16sp" />
</RelativeLayout>
Anyone have any ideas as to why it's not displaying results?
My relevant Firebase DB basic paths are like so:
Users -> Participants -> UserIDs -> name, image, etc
Logcat isn't giving me much at the moment.
Working in Android studio and as part of a bigger app. I will have an ArrayList of Integers and want to send this to a new instance/screen where each integer in the list displays a string description from which the user can pick whatever entry they want. Once they click it, I want the new instance to send back the integer corresponding to the position in the array of their choice so that I can use it for the next operation.
I made this program as a stand-alone just to get this operation down, but it fails to work (ListChooser has stopped working on load)
my MainActivity.java:
package com.example.kenn.listchooser;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.hardware.camera2.TotalCaptureResult;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.app.ListActivity;
public class MainActivity extends ListActivity {
private static final String TOTAL_COUNT = "total_count";
public ArrayList<Integer> listValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listValues= new ArrayList<Integer>();
listValues.add(1);
listValues.add(2);
listValues.add(4);
listValues.add(5);
}
public int randomMe(View view) {
Intent randomIntent = new Intent(this, Chooser.class);
randomIntent.putExtra(TOTAL_COUNT, listValues);
startActivity(randomIntent);
int pick=getIntent().getIntExtra (TOTAL_COUNT, 2);
return pick;
}
public void action(View view) {
TextView showCountTextView = (TextView) findViewById(R.id.textViewA);
showCountTextView.setText(Integer.toString(this.randomMe(view)));
} }
my Chooser.java:
package com.example.kenn.listchooser;
import ...
public class Chooser extends ListActivity{
private String TOTAL_COUNT = "total_count";
private TextView text;
private ArrayList<Integer> listHere;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chooser);
List<Integer> def = new ArrayList<Integer>();
listHere=getIntent().getIntegerArrayListExtra(TOTAL_COUNT);
text = (TextView) findViewById(R.id.mainText);
// initiate the listadapter
ArrayAdapter<Integer> myAdapter = new ArrayAdapter <Integer>(this,
R.layout.row_layout, R.id.listText, listHere);
// assign the list adapter
setListAdapter(myAdapter);
}
// when an item of the list is clicked
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
String selectedItem = (String) getListView().getItemAtPosition(position);
Intent randomIntent = new Intent(this, com.example.kenn.listchooser.MainActivity.class);
randomIntent.putExtra(TOTAL_COUNT, selectedItem);
} }
my activity main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:background="#color/colorPrimary"
tools:context=".MainActivity">
<Button
android:id="#+id/random_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="24dp"
android:layout_marginTop="8dp"
android:background="#color/colorPrimaryDark"
android:onClick="action"
android:text="Choose"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="#+id/textViewA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:text="Alert Dialog"
android:textSize="35dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
my chooser.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"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mainText"
android:text="My list" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:id="#android:id/list"
android:background="#aaaaaa" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:id="#android:id/empty"
android:text="There is no data"
android:textStyle="bold" />
</RelativeLayout>
my row_layout.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:orientation="vertical" >
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="18sp"
android:textStyle="bold"
android:textColor="#ff00ff" />
</LinearLayout>
My problem is that once my editText fields are created, I don't know how to remove them one by one with the other button in my app. I don't really understand the android:id element as it relates to setID() in my java code. I guess my main question is, how do I figure out how to target dynamically created editText views with their id's if I don't know their id's. Here is my code, any help is really appreciated:
Java:
package com.zdowning.decisionmaker;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ScrollView;
import android.widget.Toast;
import java.lang.*;
import static com.zdowning.decisionmaker.R.layout.activity_main;
public class MainActivity extends AppCompatActivity {
public int numberOfLines = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer();
}
});
final Button add_button = (Button) findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_Line();
}
});
final Button remove_button = (Button) findViewById(R.id.remove_button);
remove_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Remove_Line();
}
});
}
public void Add_Line() {
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new
LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setId(numberOfLines++);
et.setText("Enter Answer #" + numberOfLines++);
ll.addView(et);
numberOfLines++;
Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show();
}
public void Remove_Line() {
}
public void getAnswer() {
String[] options = new String[numberOfLines];
EditText text = (EditText)findViewById(R.id.editText2);
options[0] = text.getText().toString();
text = (EditText)findViewById(R.id.editText3);
options[1] = text.getText().toString();
text = (EditText)findViewById(R.id.editText4);
options[2] = text.getText().toString();
int number = (int)(Math.random() * 3);
String answer = options[number];
TextView answerBox = (TextView)findViewById(R.id.textView7);
answerBox.setText(answer);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:background="#d4cfcd">
tools:context="com.zdowning.decisionmaker.MainActivity">
<LinearLayout
android:id="#+id/linearLayoutMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Your Question Here"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"/>
<LinearLayout
android:id="#+id/linearLayoutDecisions"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Answer #2" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Answer #1" />
<EditText
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="45dp"
android:gravity="center"
android:hint="Enter Answer #3" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:id="#+id/add_button"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="+"
android:textColor="#android:color/background_light"
android:textSize="18sp"/>
<View
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1" />
<Button
android:id="#+id/remove_button"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="-"
android:textColor="#android:color/background_light"
android:textSize="18sp"
android:layout_margin="10dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/button"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="DECIDE!"
android:textColor="#android:color/background_light"
android:textSize="18sp"
android:layout_centerInParent="true" />
</RelativeLayout>
<TextView
android:id="#+id/textView7"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_margin="20dp"
android:textColor="#android:color/black"
android:textSize="36sp" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
There is no relationship between android:id and your setID.
Check this answer to unsderstand more about that.
Anyway, one approach to achieve to remove a generated line could be based on the children index of your LinearLayout like this:
private LinearLayout mEditTextContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mEditTextContainer = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
...
}
public void addLine() {
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new
LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setText("Enter Answer #" + (mEditTextContainer.getChildCount()+1));
mEditTextContainer.addView(et);
Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show();
}
public void removeLine() {
mEditTextContainer.removeViewAt(mEditTextContainer.getChildCount()-1);
}
I have tried many answers already given to this, but nothing seems to work properly. And the answers are only for changing state of the button, not colour and text. What am I missing?
I am a very VERY new learner to both Android and programming. And this is my first question on Stack Overflow. Hope it's as per guidelines.
I have a login page which looks like below (img1) [disabled][1]. If textfield has any value, the button should get enabled (img2) [enabled][2]. The Java and XML files are given below.
package io.kaapi.kaapimobileassistant.Activities;
import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.TextView;
import io.kaapi.kaapimobileassistant.Misc.StorageManager;
import io.kaapi.kaapimobileassistant.R;
public class LoginActivity extends AppCompatActivity {
private final static String TAG = "LoginActivity";
private Button login_button;
private TextInputLayout login_activation_layout;
private EditText login_activation_code;
private LinearLayout login_signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login_button = (Button) findViewById(R.id.login_button);
login_activation_layout = (TextInputLayout) findViewById(R.id.login_acitivation_layout);
login_activation_code = (EditText) findViewById(R.id.login_activation_code);
login_signup = (LinearLayout) findViewById(R.id.login_signup);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "Login pressed");
String activation_code_layout = login_activation_layout.getEditText().getText().toString();
Log.v(TAG, "Layout "+activation_code_layout);
String activation_code = login_activation_code.getText().toString();
Log.v(TAG, "Code "+activation_code);
if(activation_code.equalsIgnoreCase("")){
Log.v(TAG, "It's blank");
login_activation_layout.setError("Please enter an activation code");
} else {
Log.v(TAG, "Call login API, validate and show errors or login");
//StorageManager.write(LoginActivity.this, null, "client_domain", "http://ankit50.kaapi.io");
//StorageManager.write(LoginActivity.this, null, "client_logo", "http://cdn.kaapi.io/static");
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
}
}
});
login_activation_code.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
enableSubmitIfReady();
}
#Override
public void afterTextChanged(Editable s) {
}
public void enableSubmitIfReady() {
Button login_button = (Button) findViewById(R.id.login_button);
if(login_activation_code.toString().trim().length()==0){
login_button.setEnabled(false);
} else {
login_button.setEnabled(true);
}
}
});
login_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://business.kaapi.io");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
The XML file is below
<?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:background="#android:color/white"
android:gravity="center_vertical|center_horizontal"
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="io.kaapi.kaapimobileassistant.Activities.LoginActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="71dp"
android:layout_marginRight="71dp"
android:layout_marginTop="66dp"
android:src="#drawable/kaapi_logo_login"
android:scaleType="fitCenter"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="65dp"
android:layout_marginLeft="28dp"
android:layout_marginRight="28dp"
android:textStyle="bold"
android:gravity="center"
android:textColor="#color/colorTitle"
android:text="Activate Mobile Assistant"
android:textSize="24sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|top"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:layout_marginTop="36dp"
android:orientation="horizontal">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorText"
android:src="#drawable/ic_info_outline_black_24dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorText"
android:textSize="14sp"
android:textStyle="italic"
android:layout_marginLeft="5dp"
android:text="The code was sent to you in sign up email and your web dashboard." />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/login_acitivation_layout"
android:layout_width="match_parent"
android:layout_marginTop="29dp"
android:layout_height="wrap_content">
<EditText
android:id="#+id/login_activation_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:maxLength="20"
android:hint="Activation code"
android:maxLines="1"
android:textSize="14sp" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
style="#style/Widget.AppCompat.Button"
android:text="Activate"/>
<LinearLayout
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center|top"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="New to Kaapi? " />
<LinearLayout
android:id="#+id/login_signup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|top"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center|top"
android:text="Sign up first"
android:textColor="#color/colorPrimary"
android:textSize="12sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorPrimary" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
try this
public void enableSubmitIfReady() {
Button login_button = (Button) findViewById(R.id.login_button);
if(login_activation_code.toString().trim().length()==0){
login_button.setClickable(false);
login_button.setBackgroundColor(getResources().getColor(R.color.holo_light_green));// change color here so it's look like button disable
} else {
login_button.setClickable(true);
login_button.setBackgroundColor(getResources().getColor(R.color.holo_dark_green));
}
}
So,
I am building a basic app which has 2 activivities. Now, the first one works well, the second one does not. It does not show any errors while I edit the codes, but when I run the app and when I am in the second acitivity it gives me an annoying error. Saying "Stops unexpectedly...." You know. I tried debugging but failed. In the second activity called Troll.java I should be able to check a checkbox and when I do that a text is supposed to change to something else. It says stops unexpe.....
main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:padding="0dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
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" >
<include
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/resuable_pizza_layout" />
<TextView
android:id="#+id/display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:text="#string/display"
android:textColor="#FFFFFF"
android:textSize="18sp" />
<ImageView
android:id="#+id/lol"
android:onClick="onlol"
android:contentDescription="#string/lol2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/display"
android:layout_centerHorizontal="true"
android:layout_marginTop="66dp"
android:src="#drawable/lol" />
troll.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:background="#FF69B4"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<CheckBox
android:id="#+id/box1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onChecked1"
android:text="#string/ch1"
android:textColor="#000000" />
<CheckBox
android:id="#+id/box2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onChecked2"
android:text="#string/ch2"
android:textColor="#000000" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:gravity="center"
android:layout_weight="0.26" >
<TextView
android:id="#+id/textView1"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trollFace"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
</LinearLayout>
mainActitvity.java :
package com.example.pizza2;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
CheckBox pepp, cheese;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pepp = (CheckBox) findViewById(R.id.check1);
cheese = (CheckBox) findViewById(R.id.check2);
tv = (TextView) findViewById(R.id.display);
}
public void onShow(View view){
StringBuilder str = new StringBuilder();
if (pepp.isChecked() && cheese.isChecked()){
str.append("Pepperoni, extra cheese pizza!");
}
else if (pepp.isChecked()){
str.append("Pepperoni pizza!");
}
else if (cheese.isChecked()){
str.append("Extra cheese pizza!");
}
tv.setText(str);
}
public void onlol(View view){
Intent intent = new Intent(this, Troll.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Troll.java:
package com.example.pizza2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class Troll extends Activity{
CheckBox box11, box22;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.troll);
box11 = (CheckBox) findViewById(R.id.box1);
box22 = (CheckBox) findViewById(R.id.box2);
tv = (TextView) findViewById(R.id.display);
}
public void onChecked1(View view){
StringBuilder str = new StringBuilder();
if(box11.isChecked()){
str.append("Lol bro!");
}
tv.setText(str);
}//end of "onChecked1"
public void onChecked2(View view){
StringBuilder str = new StringBuilder();
if(box22.isChecked()){
str.append("XD XD Kaki");
}
tv.setText(str);
} //end of "onChecked2"
}