How to create a view programmatically at 12 AM every day - android

How would I go about creating a TextView at 12 AM every day, regardless if the app is open or not (unbound to app lifetime)? I already have the code to create the TextView, I just need to know how I would execute the code at 12 AM every day.
I'm not going to be opening another activity, everything will be done within the same activity.
Here is my code and my xml:
package com.example.app1;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;
import java.util.ArrayList;
import java.util.Calendar;
public class NotesActivity extends AppCompatActivity implements View.OnClickListener {
LinearLayout linearLayout;
ImageButton addNoteButton, infoButton;
TextView titleTextNotes;
ArrayList<TextView> notesList;
SharedPreferences sharedPreferences;
Calendar calendar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
sharedPreferences = this.getSharedPreferences("Notes Preferences", Context.MODE_PRIVATE);
linearLayout = findViewById(R.id.linearLayout);
addNoteButton = findViewById(R.id.addNoteButton);
infoButton = findViewById(R.id.infoButton);
titleTextNotes = findViewById(R.id.titleTextNotes);
notesList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
String noteTitle = extras.getString("noteTitle");
if(notesList.size() == 0) {
notesList.add(getStyledNote(noteTitle));
linearLayout.addView(notesList.get(notesList.size() - 1));
}
/*addNoteButton.setOnClickListener(view -> {
notesList.add(getStyledNote("My Log"));
notesList.get(notesList.size() - 1).setOnClickListener(this);
linearLayout.addView(notesList.get(notesList.size() - 1));
});*/
for(int i = 0; i < notesList.size(); i++) {
notesList.get(i).setOnClickListener(this);
}
titleTextNotes.setOnClickListener(this);
for(int i = 0; i < sharedPreferences.getInt("Number of notes", 0); i++) {
notesList.add(getStyledNote(sharedPreferences.getString("Note " + i, "My Log")));
linearLayout.addView(notesList.get(notesList.size() - 1));
}
infoButton.setOnClickListener(view -> callInfoActivity());
}
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("Number of notes", notesList.size());
for (int i = 0; i < notesList.size(); i++) {
editor.putString("Note " + i, notesList.get(i).getText().toString());
}
editor.apply();
for (int i = 0; i < notesList.size(); i++) {
if (view.getId() == notesList.get(i).getId())
callMainActivity(i);
}
}
public void callMainActivity(int pos) {
Intent sendInfoBack = new Intent();
sendInfoBack.putExtra("noteTitleSentBack", notesList.get(pos).getText());
setResult(RESULT_OK, sendInfoBack);
overridePendingTransition(R.anim.leave, R.anim.enter);
finish();
}
public void callInfoActivity() {
Intent intentToLoad = new Intent(NotesActivity.this, InfoActivity.class);
startActivity(intentToLoad);
overridePendingTransition(R.anim.enter, R.anim.leave);
}
public TextView getStyledNote(String noteTitle) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 175);
params.gravity = Gravity.CENTER;
params.setMargins(0, 10, 0, 10);
TextView note = new TextView(NotesActivity.this);
note.setId(View.generateViewId());
note.setLayoutParams(params);
note.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.note_style, null));
note.setTextSize(20);
note.setTextColor(Color.BLACK);
note.setGravity(Gravity.CENTER);
note.setTypeface(getResources().getFont(R.font.sfprodisplaybold));
if(noteTitle == null || noteTitle.equals(""))
note.setText("My Log");
else
note.setText(noteTitle);
return note;
}
}
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:orientation="vertical"
tools:context=".NotesActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<ImageButton
android:id="#+id/infoButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight=".2"
android:background="#android:color/transparent"
app:srcCompat="#drawable/info_mark" />
<TextView
android:id="#+id/titleTextNotes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight=".8"
android:fontFamily="#font/sfprodisplaybold"
android:gravity="center"
android:text="My Logs"
android:textColor="#color/teal_200"
android:textSize="30sp" />
<ImageButton
android:id="#+id/addNoteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight=".2"
android:background="#android:color/transparent"
app:srcCompat="#drawable/bar_chart" />
</LinearLayout>
<View
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="40dp"
android:layout_weight="1"
android:background="#color/teal_200" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
</LinearLayout>
</ScrollView>
</LinearLayout>

You need to schedule a periodic task using Work Manager.
val myUploadWork = PeriodicWorkRequestBuilder<SaveImageToFileWorker>(
24,TimeUnit.HOURS) // The work is scheduled to repeat after 24 hours.
.build()
Then you can submit the request to system :
WorkManager
.getInstance(myContext)
.enqueue(myUploadWork)
You can get more code and help from here.

Related

How to create nested child on firebase android

[Solved. I solved it myself]
Tips: if you want to access a child in the firebase realtime database for collecting data and then by using that data u store or upload something at that child on the firebase realtime database again, then you can't access it. Either u have to create another child or u must not use that child. (I don't no the actual solution but It works for me)]
I want to create a child under the reference of the user phone number. That child will store one or more childs. These child will be called "serialNo" of the item. And under serialNo child, the item name and amount of piece will store. I want to create like this:
[N: B: I've created this on firebase directly, not by my application.]
But when I put my data object as .setValue(dtObject) the previous one will always be replaced.
"orderNo: 1" child was replaced by "orderNo: 2" child
I also use .updateChildren(dtMap) but everytime previous orderNo child was replaced.
My Code of confirm Fragment(from where I upload):
package com.binarysoftwareltd.airaid;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class AddressFragment extends Fragment {
private int orderNo = 1;
private int orderSerial = 0;
private DatabaseReference dbReference, dbr;
private static final String STATE_USER = "user";
private String mUser;
private View oldView;
private TextView numWarning;
private EditText nameField, phoneField, areaField, addressField,
detailsField;
private CardView confirmCV;
private int len;
private String nameOfPerson, phoneNumber, areaName, addressOfOrder,
detailsOfOrder;
private int[] serialNos = new int[100];
private String[] names = new String[100];
private int[] pieces = new int[100];
private String imageUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mUser = savedInstanceState.getString(STATE_USER);
} else {
// Probably initialize members with default values for a new
instance
mUser = "NewUser";
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString(STATE_USER, mUser);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
if (oldView != null) {
return oldView;
}
View v = inflater.inflate(R.layout.fragment_address, container,
false);
initializeAll(v);
Bundle bundle = getArguments();
if (bundle != null) {
len = bundle.getInt("cValue");
imageUri = bundle.getString("imgUri");
serialNos = bundle.getIntArray("mSerialNos");
names = bundle.getStringArray("mNames");
pieces = bundle.getIntArray("mPieces");
}
confirmCV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
collectAllData();
if (!phoneNumber.equals("")) {
checkOrderSerial();
} else {
phoneField.requestFocus();
Toast.makeText(getContext(), orderSerial,
Toast.LENGTH_SHORT).show();
}
}
});
oldView = v;
return v;
}
private void checkOrderSerial() {
dbr=FirebaseDatabase.getInstance().getReference(phoneNumber).
child("currentOrderSerial");
dbr.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Integer value = dataSnapshot.getValue(Integer.class);
if (value != null)
orderSerial = value;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
showConfirmDialog();
}
private void showConfirmDialog() {
AlertDialog.Builder alb = new AlertDialog.Builder(getContext());
alb.setIcon(R.drawable.question);
alb.setTitle("Confirm");
alb.setMessage("Are you sure want to order?");
alb.setPositiveButton(R.string.exit_no, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alb.setNegativeButton(R.string.exit_yes, new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setOrderSerial();
}
});
AlertDialog ald = alb.create();
ald.show();
}
private void setOrderSerial() {
dbr = FirebaseDatabase.getInstance().getReference(phoneNumber);
if (orderNo <= orderSerial) {
orderNo = orderSerial;
orderNo += 1;
}
OrderSerial osObject = new OrderSerial(orderNo);
dbr.setValue(osObject);
uploadAllData();
}
private void uploadAllData() {
dbReference =
FirebaseDatabase.getInstance().getReference(phoneNumber).child("orderNo:
"+orderNo);
DataTemplate dtObject;
int i;
for (i = 0; i < len; i++) {
if (pieces[i] != 0) {
dtObject = new DataTemplate(names[i],pieces[i]);
dbReference.child("serialNo:
"+serialNos[i]).setValue(dtObject);
}
}
}
private void collectAllData() {
nameOfPerson = nameField.getText().toString();
phoneNumber = phoneField.getText().toString();
areaName = areaField.getText().toString();
addressOfOrder = addressField.getText().toString();
detailsOfOrder = detailsField.getText().toString();
}
private void initializeAll(View v) {
numWarning = v.findViewById(R.id.numWarning);
nameField = v.findViewById(R.id.nameField);
phoneField = v.findViewById(R.id.phoneField);
areaField = v.findViewById(R.id.areaField);
addressField = v.findViewById(R.id.addressField);
detailsField = v.findViewById(R.id.detailsField);
confirmCV = v.findViewById(R.id.confirmCV);
}
}
My OrderSerial Class::
package com.binarysoftwareltd.airaid;
public class OrderSerial {
private int currentOrderSerial;
public OrderSerial() {
}
public OrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
public int getCurrentOrderSerial() {
return currentOrderSerial;
}
public void setCurrentOrderSerial(int currentOrderSerial) {
this.currentOrderSerial = currentOrderSerial;
}
}
The XML code of the AddressFragment:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/app_main_bg"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="120dp"
android:text="#string/address_fragment_title"
android:textColor="#color/pureBlack"
android:textSize="25sp"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:id="#+id/numWarning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="15dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="#string/number_warning"
android:textColor="#color/img_warning"
android:textSize="15sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/name_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_person"/>
<EditText
android:id="#+id/nameField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_weight="7"
android:layout_height="70dp"
android:hint="#string/name_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/phone_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_phone"/>
<EditText
android:id="#+id/phoneField"
android:layout_marginStart="5dp"
android:inputType="phone"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="4"
android:hint="#string/phone_field" />
<EditText
android:id="#+id/areaField"
android:layout_marginStart="10dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3"
android:hint="#string/area_field" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/address_fragment_title"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_location"/>
<EditText
android:id="#+id/addressField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/address_fragment_title" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="15dp"
android:layout_marginTop="15dp"
android:gravity="center_vertical"
android:weightSum="8"
android:orientation="horizontal">
<ImageView
android:contentDescription="#string/details_field"
android:layout_width="0dp"
android:layout_height="35dp"
android:layout_weight="1"
android:src="#drawable/ic_details"/>
<EditText
android:id="#+id/detailsField"
android:layout_marginStart="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="7"
android:hint="#string/details_field" />
</LinearLayout>
<androidx.cardview.widget.CardView
android:id="#+id/confirmCV"
android:layout_width="match_parent"
android:layout_height="40dp"
android:clickable="true"
android:focusable="true"
android:layout_marginStart="15dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="15dp"
app:cardCornerRadius="18dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/card_view_bg"
android:gravity="center">
<ImageView
android:contentDescription="#string/order_now"
android:layout_width="30dp"
android:layout_height="30dp"
android:src="#drawable/ic_confirm" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:text="#string/order_now"
android:textColor="#color/pureWhite"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>
here my JSON::
{
"23" : {
"currentOrderSerial" : 2,
"orderNo: 2" : {
"serialNo: 1" : {
"name" : "napa Extra",
"piece" : 200
}
}
}
}
[I use phone number as primary Identifier for every user. That's why phone numbers must be required.]
Please help to fix this...
Thanks in Advance...

How to set a line break after a set of EditText which have been dynamically created?

I am trying to show few EditText field just like n*n Matrix. I am creating these EditText field dynamically.
Problem is all my EditText field prints in the same line horizontally.
I wanted to know is there anything like "System.out.println();" in Android Studio!
Note: I want this line break in between Views, not in between Text, so \n doesn't work here!
This is my activity_main.xml file,
<?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:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity">
<EditText
android:id="#+id/a"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:gravity="center"
android:inputType="number" />
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/holo_purple"
android:text="Click"
android:textColor="#android:color/white" />
<LinearLayout
android:id="#+id/child_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<!--EditText Fields going to be here!-->
</LinearLayout>
</LinearLayout>
And Here's my MainActivity.java file
package com.ridi.magicfield;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
public class MainActivity extends AppCompatActivity {
private static int a;
private static EditText magicField, ainput;
private static Button btn;
private static LinearLayout child_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
child_layout = (LinearLayout) findViewById(R.id.child_layout);
ainput = (EditText) findViewById(R.id.a);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(ainput.getText().toString());
child_layout.removeAllViews();
createMatrixInputField();
}
});
}
private void createMatrixInputField() {
int p = 1;
for (int t = 1; t <= a; t++) {
for (int i = 1; i <= a; i++) {
magicField = new EditText(MainActivity.this);
magicField.setId((p));
magicField.setHint("et-" + (Integer.toString(p)));
magicField.setGravity(Gravity.CENTER);
child_layout.addView(magicField);
p++;
}
}
}
}
Here's my output screen. I want et-3 and et-4 to go to next line.
Is there anyone who can help please...
Output Screen Image
Use TableLayout instead of LinearLayout for n*n matrix pattern
for (int i = 0; i < noOfRows; i++) {
TableRow row= new TableRow(this);
TableRow.LayoutParams lp = new
TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT
,TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(lp);
for(int j = 0; j < noOfColumns; j++) {
EditText et = new EditText(this);
//Extra properties goes here...
et.setText("Your text");
row.addView(et,j);
}
tableLayout.addView(row,i);
}

button not functioning?

I created a android studio button for my app and when I click on the register button it doesn't work . I don't get any errors it just doesn't work . When the user clicks the quiz button I want to go to the quiz activity
MainActivity.java
package com.littlekidsmath.yoong.mathlearningforkids;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemSelectedListener{
Button addBtn, subBtn, multiBtn, divisionBtn,quiz;
String[] levels = {"Easy","Medium","Hard"};
SharedPreferences prefs;
Switch settings;
Spinner language;
public String[] languages = {GameActivity.ENG,GameActivity.ARABIC,"বাংলা",GameActivity.FRENCH,GameActivity.GERMAN,GameActivity.MALAY};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("MyPref",MODE_PRIVATE);
settings = (Switch) findViewById(R.id.settings);
if(prefs.getBoolean("SOUND", false)){
settings.setChecked(true);
}
settings.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
prefs.edit().putBoolean("SOUND",b).commit();
}
});
addBtn = (Button) findViewById(R.id.addtion);
subBtn = (Button) findViewById(R.id.sub);
multiBtn = (Button) findViewById(R.id.multi);
divisionBtn = (Button) findViewById(R.id.divide);
quiz = (Button) findViewById(R.id.quiz);
language = (Spinner) findViewById(R.id.language);
addBtn.setOnClickListener(this);
subBtn.setOnClickListener(this);
multiBtn.setOnClickListener(this);
divisionBtn.setOnClickListener(this);
quiz.setOnClickListener(this);
language.setOnItemSelectedListener(this);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
language.setAdapter(adapter);
int pos = 0;
//
for(int i=0;i<languages.length;i++){
if(prefs.getString(GameActivity.LANGUAGE,"").equals(languages[i])){
pos = i;
break;
}
}
language.setSelection(pos);
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA)){
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addtion: {
levelChooseDialog("+");
break;
}
case R.id.sub: {
levelChooseDialog("-");
break;
}
case R.id.multi: {
levelChooseDialog("X");
break;
}
case R.id.divide: {
levelChooseDialog("/");
break;
}
case R.id.quiz: {
Intent intent = new Intent(MainActivity.this, HomeScreen.class);
startActivity(intent);
}
}
}
public void levelChooseDialog(final String operator){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = View.inflate(this,R.layout.level_dialog,null);
builder.setView(view);
ListView listView = (ListView) view.findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,levels);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int level = 0;
if (position == 0){
level = 0;
}else if(position == 1){
level = 1;
}else {
level = 2;
}
startActivity(new Intent(MainActivity.this,LessonActivity.class).putExtra("level",level)
.putExtra("operator",operator));
}
});
builder.create().show();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
prefs.edit().putString(GameActivity.LANGUAGE,languages[position]).commit();
if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.BANGLA))
{
setBangla();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ARABIC)){
setArabic();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.FRENCH)){
setFrence();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.GERMAN)){
setGerman();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.ENG)){
setEnglish();
}else if(prefs.getString(GameActivity.LANGUAGE,"").equals(GameActivity.MALAY)){
setMalay();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void setBangla(){
addBtn.setText(Languages.BANGLA[0]);
subBtn.setText(Languages.BANGLA[1]);
multiBtn.setText(Languages.BANGLA[3]);
divisionBtn.setText(Languages.BANGLA[2]);
settings.setText(Languages.BANGLA[4]);
levels[0] = Languages.BANGLA[7];
levels[1] = Languages.BANGLA[8];
levels[2] = Languages.BANGLA[9];
}
public void setArabic(){
addBtn.setText(Languages.ARABIC[0]);
subBtn.setText(Languages.ARABIC[1]);
multiBtn.setText(Languages.ARABIC[3]);
divisionBtn.setText(Languages.ARABIC[2]);
settings.setText(Languages.ARABIC[4]);
levels[0] = Languages.ARABIC[7];
levels[1] = Languages.ARABIC[8];
levels[2] = Languages.ARABIC[9];
}
public void setMalay(){
addBtn.setText(Languages.MALAY[0]);
subBtn.setText(Languages.MALAY[1]);
multiBtn.setText(Languages.MALAY[3]);
divisionBtn.setText(Languages.MALAY[2]);
settings.setText(Languages.MALAY[4]);
levels[0] = Languages.MALAY[7];
levels[1] = Languages.MALAY[8];
levels[2] = Languages.MALAY[9];
}
public void setFrence(){
addBtn.setText(Languages.FRENCH[0]);
subBtn.setText(Languages.FRENCH[1]);
multiBtn.setText(Languages.FRENCH[3]);
divisionBtn.setText(Languages.FRENCH[2]);
settings.setText(Languages.FRENCH[4]);
levels[0] = Languages.FRENCH[7];
levels[1] = Languages.FRENCH[8];
levels[2] = Languages.FRENCH[9];
}
public void setGerman(){
addBtn.setText(Languages.GERMAN[0]);
subBtn.setText(Languages.GERMAN[1]);
multiBtn.setText(Languages.GERMAN[3]);
divisionBtn.setText(Languages.GERMAN[2]);
settings.setText(Languages.GERMAN[4]);
levels[0] = Languages.GERMAN[7];
levels[1] = Languages.GERMAN[8];
levels[2] = Languages.GERMAN[9];
}
public void setEnglish(){
addBtn.setText(Languages.ENGLISH[0]);
subBtn.setText(Languages.ENGLISH[1]);
multiBtn.setText(Languages.ENGLISH[3]);
divisionBtn.setText(Languages.ENGLISH[2]);
settings.setText(Languages.ENGLISH[4]);
levels[0] = Languages.ENGLISH[7];
levels[1] = Languages.ENGLISH[8];
levels[2] = Languages.ENGLISH[9];
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.littlekidsmath.yoong.mathlearningforkids.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/addtion"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/add"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Addition" />
<Button
android:id="#+id/sub"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/minus"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Subtraction" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/multi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/cancel"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Multiplication" />
<Button
android:id="#+id/divide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:drawableTop="#drawable/division"
android:paddingBottom="25dp"
android:paddingTop="25dp"
android:text="Division" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/quiz"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawablePadding="#dimen/activity_horizontal_margin"
android:paddingBottom="20dp"
android:paddingTop="20dp"
android:text="Quiz" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:text=""
android:textColor="#color/white"
android:textSize="18sp" />
<Switch
android:id="#+id/settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="#dimen/activity_horizontal_margin"
android:text="Sound"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_horizontal_margin"
android:text="Language" />
<Spinner
android:id="#+id/language"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:background="#color/white"
android:padding="10dp"></Spinner>
</LinearLayout>
Can anyone help please? When click on the quiz button the application will close. I want it to go to quiz page which called HomeScreen.java
looks good to me, did u declare the second activity in the manifest file? :
<activity android:name="HomeScreen"/>
If that doesn't work, use some break points and the debugger, hope it helps.

show EditText on condition

Right now I have an idea for a project and I would like to know if anyone can help me on the same logic.
As such I need to create or generate a number of EditText according to amount you enter, ie, to select or enter a number such as 5, show me 5 EditText layout for type 5 values​​. They know that the form could accomplish this? Any ideas please?
I guess it must be a way to do it with a loop, but not like carrying this calculation Java to XML. Thank you.
Here is an example of generating EditText items based on the number you enter. You can ignore the scrollview in the layout file I just put it in case someone added a lot of EditText items that would go off the screen.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final TextView output = (TextView) findViewById(R.id.output);
final Button generate = (Button) findViewById(R.id.generate);
final Button values = (Button) findViewById(R.id.values);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] editTextValues = new String[container.getChildCount()];
StringBuilder editTextValuesBuilder = new StringBuilder();
for (int counter = 0; counter < container.getChildCount(); counter++) {
EditText child = (EditText) container.getChildAt(counter);
editTextValues[counter] = child.getText().toString().trim();
editTextValuesBuilder.append(editTextValues[counter]).append("\n");
}
output.setText(editTextValuesBuilder.toString());
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
activity_main.xml
<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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp"
tools:context="${packageName}.${activityClass}" >
<EditText
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="#+id/generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
<Button
android:id="#+id/values"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Values" />
<TextView
android:id="#+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>

How to fit my design to all devices?

Hi I am developing a app in which alphabets are not fitting for every device. For HCL ME tablet my design won't fit. For samsung it is working. MY XML file is:
<?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:layout_weight="2" android:orientation="vertical">
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_weight="1">
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_weight="1">
<TextView android:id="#+id/letter1" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></TextView>
<TextView android:id="#+id/letter2" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip"></TextView>
<TextView android:id="#+id/letter3" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip"></TextView>
</LinearLayout>
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_weight="1">
<ImageView android:id="#+id/imag"
android:gravity="center"
android:scaleType = "fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_gravity="center">
</ImageView>
</LinearLayout>
</LinearLayout>
<LinearLayout android:layout_gravity="bottom"
android:id="#+id/linearLayout2"
android:layout_height="wrap_content" android:orientation="horizontal" android:layout_width="match_parent">
<Button android:id="#+id/previous" android:layout_width="wrap_content" android:layout_weight="1" android:text="Previous" android:layout_height="wrap_content" ></Button>
<Button android:id="#+id/practice" android:layout_width="wrap_content" android:layout_weight="1" android:text="Practice" android:layout_height="wrap_content" android:onClick="onClick"></Button>
<Button android:id="#+id/home" android:layout_width="wrap_content" android:layout_weight="1" android:text="Home" android:layout_height="wrap_content"></Button>
<Button android:id="#+id/spell" android:layout_width="wrap_content" android:layout_weight="1" android:text="Spell" android:layout_height="wrap_content" android:onClick="Content"></Button>
<Button android:id="#+id/next" android:layout_width="wrap_content" android:layout_weight="1" android:text="Next" android:layout_height="wrap_content" android:onClick="Content"></Button>
</LinearLayout>
</LinearLayout>
and my java file is:
package com.android;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.SimpleGestureFilter.SimpleGestureListener;
public class MyAcivity extends Activity implements SimpleGestureListener {
private SimpleGestureFilter detector;
private static int counter=-1;
private String[] mBtn1 ={"C","D","E","F","G","H","IÄ","J","K","L","M","N","O","CA","CB"};
private TextView txtLetter;
private ImageView imgLetter;
private int[] imgArr={R.drawable.w1,R.drawable.w2,R.drawable.w3,R.drawable.w4,R.drawable.w5,R.drawable.w6,R.drawable.w7,R.drawable.w8,R.drawable.w9,R.drawable.w10,R.drawable.w11,R.drawable.w12,
R.drawable.w13,R.drawable.w14,R.drawable.w15};
private TextView txtKannada;
private String[] mBtn2 = {"CgÀ¸À","DªÉÄ","E°","F±À","GqÀ","Hl","IĶ","J¯É","Kr","LzÀÄ","M¯É","N¯É","OµÀzsÀ",
"CAUÀr","CB"};
private String[] mBtn3 = {"ARASA","AME","ILI","ISA","UDA","UTA","RUSHI","ELE","EDI","AIDU","oLE","OLE","AUSHADA",
"ANGADI","AHA"};
private TextView txtEnglish;
private int[] mAudio = {R.raw.a,R.raw.b,R.raw.c,R.raw.d,R.raw.e,R.raw.f,R.raw.g,R.raw.h,R.raw.i,R.raw.j,
R.raw.k,R.raw.l,R.raw.m,R.raw.n,R.raw.o};
protected MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
detector = new SimpleGestureFilter(this,this);
if(counter == -1)
counter =getIntent().getExtras().getInt("POSITION");
Typeface tf = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/brhknd.ttf");
txtLetter = (TextView)findViewById(R.id.letter1);
txtKannada = (TextView)findViewById(R.id.letter2);
txtEnglish = (TextView)findViewById(R.id.letter3);
imgLetter = (ImageView)findViewById(R.id.imag);
txtLetter.setTypeface(tf);
txtLetter.setText(mBtn1[counter]);
txtLetter.setTextSize(350);
txtKannada.setTypeface(tf);
txtKannada.setText(mBtn2[counter]);
txtKannada.setTextSize(100);
txtEnglish.setText(mBtn3[counter]);
txtEnglish.setTextSize(50);
Button btnNext = (Button)findViewById(R.id.next);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(counter<imgArr.length-1)
counter++;
changeContent();
}
});
Button mPlay = (Button)findViewById(R.id.spell);
mPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MySwara.this, mAudio[counter]);
mp.start();
}
});
Button btnPrvs = (Button)findViewById(R.id.previous);
btnPrvs.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(counter>0)
counter--;
changeContent();
}
});
Button btnPractice = (Button)findViewById(R.id.practice);
btnPractice.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MySwara.this,DrawingActivity.class);
startActivity(intent);
}
});
Button btnHome = (Button)findViewById(R.id.home);
btnHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MySwara.this,mainClass.class);
startActivity(intent);
}
});
}
public void changeContent()
{
txtLetter.setText(mBtn1[counter]);
txtKannada.setText(mBtn2[counter]);
txtEnglish.setText(mBtn3[counter]);
//imgLetter.setBackgroundResource(imgArr[counter]);
Bitmap bm = BitmapFactory.decodeResource(getResources(), imgArr[counter]);
imgLetter.setImageBitmap(bm);
}
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
if(counter>0)
counter--;
changeContent();
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
if(counter<imgArr.length-1)
counter++;
changeContent();
break;
}
}
}
How i can fit to all devices. Can anyone help?? Thanks in advance.
There are couple of possibilities:
use different xml files for different sizes of screen -> check here http://developer.android.com/guide/practices/screens_support.html
you may use scrollview -> http://developer.android.com/reference/android/widget/ScrollView.html
or simply make your layout fit to the smallest screen size you like to support and then just have "a little" unused space on the larger screens.
It really depends on what you need. Probably the most compatible and advanced solution would be 1.
BUT be aware of the fact that EVERY change on the screen layout has to be duplicated for each xml file following this route!
create xml for each device separately. follow this
second way:
create a parent LinearLayout and pass it to the following method
public static boolean isTabletPC(Context context) {
Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getWidth() >= 1200) {
isTabletPC = true;
return isTabletPC;
} else {
isTabletPC = false;
return isTabletPC;
}
}
public static void fixUiDeviceDependencies(
Activity act, LinearLayout llParent) {
if (Utilities.isTabletPC(act)) {
Display display = ((WindowManager) act
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
LayoutParams params = (LayoutParams) llParent
.getLayoutParams();
params.width = display.getWidth() / 2;
llParent.setLayoutParams(params);
}
}

Categories

Resources