I'm trying to create a view that allows me to add pictures from the phone photos. In the Layout file I currently have a grid layout with nested LinearLayouts separated into 2 rows x 3 columns. The user will Long Click when they want to delete a photo. The expectation is that after the the image is deleted then the views will reorganize so that there aren't space between the LinearLayout views. Instead I'm getting errors. I think the main issue is that the ImageViews nested withing the LinearLayouts don't have IDs. I've tried using GridViews, swapping ImageView positions, adding copying The ImageView uri to another Imageview. It seems like I'm trying to extend the functionalities to places that they aren't meant to go. Can someone help me ?
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pictureGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="3"
android:orientation="horizontal"
android:rowCount="2"
android:layout_marginTop="330dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:columnOrderPreserved="true">
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_row="0"
android:layout_column="0"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_row="0"
android:layout_column="1"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_row="0"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="0dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_column="0"
android:background="#drawable/custom_border"
>
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="0dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:background="#drawable/custom_border"
android:layout_column="1">
</LinearLayout>
<LinearLayout
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_weight="1"
android:layout_marginTop="0dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:background="#drawable/custom_border"
>
</LinearLayout>
</GridLayout>
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.google.firebase.storage.FirebaseStorage;
import java.net.URI;
import java.util.ArrayList;
public class RegisterPictures extends android.app.Activity {
FirebaseStorage storage = FirebaseStorage.getInstance("gs://foodz-310506.appspot.com");
private static final int SELECT_IMAGE_GALLERY = 3;
GridLayout table;
View img;
View longClickView;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_pictures);
table = findViewById(R.id.pictureGrid);
for(int i = 0; i < table.getChildCount(); i++) {
img = table.getChildAt(i);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Open Up Gallery
try {
Intent toPhonePhotos = new Intent(Intent.ACTION_GET_CONTENT);
toPhonePhotos.setType("image/*");
toPhonePhotos.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
toPhonePhotos.putExtra(Intent.CATEGORY_OPENABLE, true);
startActivityForResult(Intent.createChooser(toPhonePhotos, "select Picture"), SELECT_IMAGE_GALLERY);
} catch (ActivityNotFoundException e) {
Log.w("TAG", "Unable to start phone gallery");
}
}
});
img.setOnLongClickListener(new View.OnLongClickListener(){
#Override
public boolean onLongClick(View view){
try {
Log.wtf("TAG", "long clicking");
LinearLayout v = (LinearLayout) view;
removeSelectedView(v);
sortImages();
} catch (ActivityNotFoundException e) {
Log.wtf("TAG", "wrong");
}
return true;
}
});
j++;
}
}
protected void onStart(){
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Was a photo picked?
if(resultCode != RESULT_CANCELED && data.getData()!=null/*requestCode == SELECT_IMAGE_GALLERY*/) {
ClipData clip = data.getClipData();
//one photo picked
if(clip == null){
Log.e("TAG", "only one image was selected");
Uri uri = data.getData();
photoCounter();
addSinglePhoto(uri);
//Mult photos picked
}else{
photoCounter();
addMultPhoto(clip);
}
}else{
Log.e("TAG", "SHIT IS NOOOT WORKING");
}
}
//Consecutively organizes images without whitespace
private void sortImages(){
for(int i=0; i < table.getChildCount(); i++){
LinearLayout imgHolder = (LinearLayout) table.getChildAt(i);
LinearLayout imgHolder2 = (LinearLayout)table.getChildAt(i+1);
ImageView image = (ImageView)imgHolder.getChildAt(0);
ImageView image2 = (ImageView)imgHolder2.getChildAt(0);
if( image2 != null && image == null){
//Get Drawable from ImageView and set to first ImageView
float x = imgHolder2.getX();
float y = imgHolder2.getY();
Bitmap bitmap = ((BitmapDrawable) image2.getDrawable()).getBitmap();
image.setImageBitmap(bitmap);
imgHolder2.removeAllViews();
/* imgHolder2.setX(imgHolder.getX());
imgHolder2.setY(imgHolder.getY());
imgHolder.setX(x);
imgHolder.setY(y);*/
}
}
}
// Copies ImageView to the previous index
private Drawable CheckView( ImageView iv2) {
Drawable iv2Image = iv2.getDrawable();
return iv2Image;
}
private void removeSelectedView(LinearLayout v){
v.removeAllViews();
}
private void photoCounter(){
}
//Adds one photo
private void addSinglePhoto( Uri uri){
int numOfCells = table.getChildCount();
for(int i=0; i < numOfCells; i++){
Log.e("TAG","Started for statement");
LinearLayout imageHolder = (LinearLayout) table.getChildAt(i);
if(imageHolder.getChildCount() == 0){
imageHolder.addView(imageViewCreater(uri));
i = numOfCells;
}
}
}
//adds multiple photos from Clip
private void addMultPhoto(ClipData clip){
int numOfCells = table.getChildCount();
int j = clip.getItemCount()-1;
for(int i=0; i < numOfCells-1; i++){
LinearLayout cell = (LinearLayout) table.getChildAt(i);
Uri uri = clip.getItemAt(j).getUri();
cell.addView(imageViewCreater(uri));
}
}
private ImageView imageViewCreater(Uri uri){
ImageView grandChildImage = new ImageView(this);
grandChildImage.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
grandChildImage.setImageURI(uri);
return grandChildImage;
}
}
Related
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.
[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...
I am trying to programmatically generate two RadioGroups. I have succesfully generated the first one but I need to generate the second one onCheckedChangeListener of the first radio group. Here is my code for the activity.
package com.packr.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.avast.android.dialogs.fragment.SimpleDialogFragment;
import com.avast.android.dialogs.iface.ISimpleDialogListener;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import com.packr.R;
import com.packr.adapters.ShipmentsAdapter;
import com.packr.classes.Item;
import com.packr.classes.Packr;
import com.packr.classes.Shipment;
import com.packr.database.DBShipments;
import com.packr.logging.L;
import java.util.ArrayList;
public class ItemDetailsActivity extends AppCompatActivity implements ISimpleDialogListener, ImageChooserListener {
private Toolbar toolbar;
private ImageChooserManager imageChooserManager;
private SeekBar seekBar;
private Intent intent;
private RadioGroup itemTypeRadioGroup, deliveryMethod;
private TextView addImage;
private Bitmap myBitmap;
private ShipmentsAdapter mShipmentAdapter;
private static long back_pressed;
private MyShipmentsActivity activity;
private ImageView itemImage;
private LinearLayout itemDetailsLinearLayout, weightTypeLinearLayout;
private TextInputLayout itemDescriptionText, quantityText, valueOfItemText;
private EditText itemDescription, quantity, valueOfItem;
private TextView weightUnit, weightValue, selectWeight;
private ArrayList<Shipment> shipmentArrayList = new ArrayList<>();
private ArrayList<Item> deliveryTypeArrayList = new ArrayList<>();
private ArrayList<Item> itemTypeArrayList = new ArrayList<>();
private ArrayList<Item> shipmentTypeArrayList = new ArrayList<>();
private ArrayList<Item> weightTypeArrayList = new ArrayList<>();
private String city, state, pincode, recipientName, recipientContact, street, itemType = "", deliveryType = "", route;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_details);
initialize();
onClick();
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Item details");
setSupportActionBar(toolbar);
deliveryTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.DELIVERY_TYPE);
for (int i = 0; i < deliveryTypeArrayList.size(); i++) {
}
itemTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.ITEM_TYPE);
int itemId;
//first radio group
RadioButton rb = null;
float scale = getResources().getDisplayMetrics().density;
final int dpAsPixels = (int) (10 * scale + 0.5f);
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
rg.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
final Drawable drawableTop = getResources().getDrawable(R.drawable.document_icon);
for (int i = 0; i < itemTypeArrayList.size(); i++) {
if (itemTypeArrayList.get(i).getActive() == 1) {
rb = new RadioButton(this);
rg.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
rb.setText(itemTypeArrayList.get(i).getCode());
rb.setId(itemTypeArrayList.get(i).getId());
L.m(itemTypeArrayList.get(i).getId() + "hello");
}
if (rb != null) {
rb.setAllCaps(true);
}
assert rb != null;
rb.setGravity(Gravity.CENTER_VERTICAL);
rb.setButtonDrawable(null);
rb.setPadding(dpAsPixels, 0, dpAsPixels, 0);
rb.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);
}
itemDetailsLinearLayout.addView(rg);
final RadioGroup weightTypeRadioGroup = new RadioGroup(this); //create the RadioGroup
weightTypeRadioGroup.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
weightTypeRadioGroup.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
shipmentTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.SHIPMENT_TYPE);
for (int i = 0; i < shipmentTypeArrayList.size(); i++) {
}
final RadioButton finalRb = rb;
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (finalRb != null) {
checkedId = finalRb.getId();
System.out.print(checkedId);
L.m(group.getCheckedRadioButtonId() + "");
weightTypeArrayList = Packr.getWritableDatabase().readWeightType();
for (int i = 0; i < weightTypeArrayList.size(); i++) {
L.m(weightTypeArrayList.get(i).getTitle());
//second radio group
RadioButton weightTypeRadioButton = null;
weightTypeRadioButton = new RadioButton(getApplicationContext());
weightTypeRadioGroup.addView(weightTypeRadioButton);
weightTypeRadioButton.setText(weightTypeArrayList.get(i).getTitle());
weightTypeRadioButton.setId(weightTypeArrayList.get(i).getId());
}
if (weightTypeRadioGroup.getParent() != null){
((ViewGroup)weightTypeRadioGroup.getParent()).removeView(weightTypeRadioGroup);
weightTypeLinearLayout.addView(weightTypeRadioGroup);
}
}
}
});
deliveryMethod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.normalDeliveryRadioButton) {
deliveryType = "Normal Delivery";
} else {
deliveryType = "Express Delivery";
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_item_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_done) {
if (validationCheck()) {
Shipment shipment = new Shipment();
shipment.setRecipientName(recipientName);
shipment.setRecipientContact(recipientContact);
shipment.setCity(city);
shipment.setState(state);
shipment.setStreetNo(street);
shipment.setRoute(route);
shipment.setPostalCode(pincode);
shipment.setItemQuantity(quantity.getText().toString());
shipment.setItemType(itemType);
shipment.setDeliveryType(deliveryType);
shipmentArrayList.add(shipment);
Packr.getWritableDatabase().insertShipment(shipmentArrayList, false);
mShipmentAdapter = new ShipmentsAdapter(getApplicationContext(), activity);
mShipmentAdapter.setShipmentArrayList(shipmentArrayList);
Intent intent = new Intent(ItemDetailsActivity.this, MyShipmentsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void initialize() {
intent = getIntent();
recipientName = intent.getStringExtra("recipientName");
recipientContact = intent.getStringExtra("recipientContact");
city = intent.getStringExtra("city");
state = intent.getStringExtra("state");
pincode = intent.getStringExtra("pincode");
street = intent.getStringExtra("street");
route = intent.getStringExtra("route");
deliveryMethod = (RadioGroup) findViewById(R.id.radioGroupShippingMethod);
selectWeight = (TextView) findViewById(R.id.selectWeight);
addImage = (TextView) findViewById(R.id.addImage);
itemImage = (ImageView) findViewById(R.id.item_image);
itemDescriptionText = (TextInputLayout) findViewById(R.id.item_description_text_input_layout);
quantityText = (TextInputLayout) findViewById(R.id.item_quantity_text_input_layout);
valueOfItemText = (TextInputLayout) findViewById(R.id.item_value_text_input_layout);
itemDescription = (EditText) findViewById(R.id.item_description_edit_text);
quantity = (EditText) findViewById(R.id.item_quantity_edit_text);
valueOfItem = (EditText) findViewById(R.id.item_value_edit_text);
itemDetailsLinearLayout = (LinearLayout) findViewById(R.id.itemDetailsLinearLayout);
weightTypeLinearLayout = (LinearLayout) findViewById(R.id.weightTypeRadioButton);
}
public void onClick() {
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDialogFragment.createBuilder(getApplicationContext(), getSupportFragmentManager()).setTitle("Choose item image").setMessage(R.string.selectImage).setNegativeButtonText("Gallery").setPositiveButtonText("Camera").show();
}
});
}
public Boolean validationCheck() {
if (itemDescription.getText().length() == 0) {
itemDescriptionText.setErrorEnabled(true);
itemDescriptionText.setError("Please provide an item description");
} else if (quantity.getText().length() == 0) {
quantityText.setErrorEnabled(true);
quantityText.setError("Provide item quantity");
} else if (valueOfItem.getText().length() == 0) {
valueOfItemText.setErrorEnabled(true);
valueOfItemText.setError("Please provide value of item");
} else {
return true;
}
return false;
}
public void chooseImage() {
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_PICK_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
public void snapImage() {
imageChooserManager = new ImageChooserManager(this, ChooserType.REQUEST_CAPTURE_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onNegativeButtonClicked(int i) {
chooseImage();
}
#Override
public void onNeutralButtonClicked(int i) {
}
#Override
public void onPositiveButtonClicked(int i) {
snapImage();
}
#Override
public void onImageChosen(ChosenImage chosenImage) {
myBitmap = BitmapFactory.decodeFile(chosenImage.getFileThumbnail());
runOnUiThread(new Runnable() {
public void run() {
itemImage.setImageBitmap(myBitmap);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK &&
(requestCode == ChooserType.REQUEST_PICK_PICTURE ||
requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
imageChooserManager.submit(requestCode, data);
}
}
#Override
public void onError(String s) {
}
#Override
public void onBackPressed() {
AlertDialog.Builder alert = new AlertDialog.Builder(ItemDetailsActivity.this);
alert.setTitle("Cancel shipment");
alert.setMessage("Are you sure?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ItemDetailsActivity.this, MyShipmentsActivity.class);
startActivity(intent);
finish();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Cancel
}
});
alert.show();
}
}
Here is the code for my layout xml file.
<RelativeLayout
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context="com.packr.activities.ItemDetailsActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<ScrollView
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="80dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="What are you sending?"
android:fontFamily="sans-serif-light"
android:padding="20dp"
android:textColor="#color/textColorPrimary"/>
<LinearLayout
android:id="#+id/itemDetailsLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
tools:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UseCompoundDrawables">
<ImageView
android:id="#+id/item_image"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:src="#drawable/image_background"
android:layout_margin="16dp"
android:contentDescription="#string/product_image" />
<TextView
android:id="#+id/addImage"
android:padding="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add an image"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:textColor="#color/textColorSecondary"
/>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_description_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="gone"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<EditText
android:id="#+id/item_description_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/item_description"
android:inputType="textMultiLine"
android:imeOptions="flagNoFullscreen"
android:lines="5"/>
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/selectWeight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Permitted weight"
android:fontFamily="sans-serif-light"
android:padding="20dp"/>
</RelativeLayout>
<LinearLayout
android:id="#+id/weightTypeRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_quantity_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="visible"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/item_quantity_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/itemQuantity"
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_value_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="visible"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/item_value_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/item_value"
android:inputType="number"
android:imeOptions="flagNoFullscreen"/>
</android.support.design.widget.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose shipping method"
android:fontFamily="sans-serif-light"
android:textColor="#color/textColorPrimary"
android:layout_marginLeft="25dp"
android:layout_marginStart="25dp"
android:layout_marginTop="25dp"/>
<RadioGroup
android:id="#+id/radioGroupShippingMethod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<RadioButton
android:id="#+id/normalDeliveryRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Normal Delivery"
android:checked="true"/>
<RadioButton
android:id="#+id/expressDeliveryRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Express Delivery"/>
</RadioGroup>
</LinearLayout>
</ScrollView>
//This contains the layout for the bottom price bar //
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/textColorPrimary"
android:padding="12dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<TextView
android:id="#+id/priceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:textColor="#color/white"/>
<TextView
android:id="#+id/equals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equals"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textColor="#color/white"/>
<TextView
android:id="#+id/Rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Rs"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:textColor="#color/white"/>
<TextView
android:id="#+id/calculatedPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="550"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:textColor="#color/white"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
do you not just need to repeat the same proccess inside the onCheckChangedListener?
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//Create another radio group here
//then add it to the view
RadioGroup rg2 = new RadioGroup(this); //create the RadioGroup
rg2.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
rg2.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
final Drawable drawableTop = getResources().getDrawable(R.drawable.document_icon);
for (int i = 0; i < itemTypeArrayList.size(); i++) {
if (itemTypeArrayList.get(i).getActive() == 1) {
rb = new RadioButton(this);
rg2.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
rb.setText(itemTypeArrayList.get(i).getCode());
rb.setId(itemTypeArrayList.get(i).getId());
}
}
itemDetailsLinearLayout.addView(rg);
}
});
You may need to declare rg2 public at the top of the class so it can be accessed by the onCheckChangedListener
I'm developing an android application. It is an exam app. When a user clicks an answer, the application changes the layout with $setContentView(); in same activity.
But it gives an error for layout Caused by: java.lang.NumberFormatException: unable to parse '#2131230721' as integer
My layout file is below, if you need I can put my project myserver. And I can paste my activity code, but it's a basic setContentView() only. I guess one of my id's is causing the error but i couldn't find it.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/soruNoIleriVeGeri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:id="#+id/SoruLayout"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/OncekiSoru"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/qIPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/back_button"
android:onClick="qIPrevious"
android:paddingLeft="5dp" />
</LinearLayout>
<LinearLayout
android:layout_width="57dp"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/about_question" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/add_favourite" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/goToQuestion"
android:layout_width="56dp"
android:layout_height="wrap_content"
android:onClick="onshowQuestion"
android:src="#drawable/show_question" />
</LinearLayout>
<LinearLayout
android:layout_width="50dp"
android:layout_height="45dp"
android:layout_weight="0.57" >
<ImageButton
android:id="#+id/homeButton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/tab_home"
android:onClick="goHome" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/next_button"
android:onClick="qINextQuestion" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/resultIconPlain"
android:layout_width="84dp"
android:layout_height="fill_parent"
android:paddingLeft="20dp" >
</LinearLayout>
<LinearLayout
android:layout_width="234dp"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/resultView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.13"
android:gravity="center_horizontal"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="59dp"
android:background="#drawable/question_top_plain" >
<LinearLayout
android:id="#+id/dogruCevap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikDogruCevap"
android:layout_width="126dp"
android:layout_height="wrap_content"
android:text="#string/StatikDogruCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.01" >
<TextView
android:id="#+id/dogruCevapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingRight="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/cevabiniz"
android:layout_width="fill_parent"
android:layout_height="54dp"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/cevabinizView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikCevap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/StatikCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="350px"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/dogruCevapAyrinti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.60"
android:isScrollContainer="true"
android:minHeight="400px"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical" >
<TextView
android:id="#+id/dogruCevapAyrintiView"
android:layout_width="fill_parent"
android:layout_height="324dp"
android:scrollHorizontally="false"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" >
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
Here is error codes and myActivity sorry for Turkish variable names
at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)
java.lang.reflect.InvocationTargetException
at android.widget.TextView.<init>(TextView.java:320)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
at android.view.LayoutInflater.createView(LayoutInflater.java:500)
... 41 more
java.lang.NumberFormatException: unable to parse '#2131230721' as integer
at java.lang.Integer.parse(Integer.java:374)
at java.lang.Integer.parseInt(Integer.java:363)
at com.android.internal.util.XmlUtils.convertValueToInt(XmlUtils.java:121)
at android.content.res.TypedArray.getInt(TypedArray.java:201)
at android.widget.TextView.<init>(TextView.java:647)
package com.eandroid.workingSet;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.eandroid.entity.Question;
public class QuestionInterfaceActivity extends Activity {
LinearLayout layoutForA;
LinearLayout layoutForB;
LinearLayout layoutForC;
LinearLayout layoutForD;
LinearLayout layoutForE;
LinearLayout choiceATotalPlain;
LinearLayout choiceBTotalPlain;
LinearLayout choiceCTotalPlain;
LinearLayout choiceDTotalPlain;
LinearLayout choiceETotalPlain;
LinearLayout allTotalPlain;
List<Question> questionList = new ArrayList<Question>();
Node node = null;
NodeList nodeList = null;
NodeList nodeListForTestInfo = null;
InputStream is = null;
private TextView choiceA;
private TextView choiceB;
private TextView choiceC;
private TextView choiceD;
private TextView choiceE;
private TextView questionText;
private TextView soruIdText;
private TextView soruIdEv;
private TextView soruBilgileriView;
private TextView cevabinizView;
private TextView dogruCevapView;
private TextView dogruCevapAyrintiView;
private TextView resultView;
private int currentQuestionIndex;
Question currentQuestion = null;
private String testName = null;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
HttpResponse response;
InputStream contentStream;
private String rightAnswers = "";
private String userAnswers = "";
private String resultOfAnswers = "";
private String userId = "1";
private static String testRelationId;
private LinearLayout resultIconPlain;
private static String willPostUrl =
"http://balabanhafriyat.com/SchoolProjectWebSide/postFromPhone/SendDataFromPhone";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
}
settleOrientation();
Bundle extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("testName");
}
try {
is = getAssets().open(testName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("question");
nodeListForTestInfo = doc.getElementsByTagName("testInfo");
Node testNode = nodeListForTestInfo.item(0);
testRelationId = parseItToStringByName(testNode, "testRelationId");
} catch (Exception e) {
e.printStackTrace();
}
currentQuestionIndex = 1;
showQuestion();
}
public void settleOrientation() {
int setLayout = getResources().getConfiguration().orientation;
switch (setLayout) {
case 1:
setContentView(R.layout.buttontry);
loadDesign();
break;
case 2:
setContentView(R.layout.buttontry);
break;
default:
break;
}
}
public void callEvaluationActivity(int optionToSeeQuestion,
String userAnswer) {
setContentView(R.layout.evaluation_screen);
// resultView = (TextView) findViewById(R.id.resultView);
cevabinizView = (TextView) findViewById(R.id.cevabiniz);
dogruCevapView = (TextView) findViewById(R.id.rightAnswer);
dogruCevapAyrintiView = (TextView)
findViewById(R.id.dogruCevapAyrintiView);
// soruBilgileriView.setText(currentQuestion.getShortInfo());
dogruCevapAyrintiView.setText(currentQuestion.getRightAnswerDetail());
dogruCevapView.setText(currentQuestion.getRightAnswer());
if (optionToSeeQuestion == 2) {
cevabinizView.setText(userAnswer);
if (currentQuestion.getRightAnswer().equals(userAnswer)) {
resultView.setTextColor(Color.GREEN);
resultView.setText("Doğru Cevap");
resultOfAnswers = resultOfAnswers + "1$";
} else {
resultView.setTextColor(Color.RED);
resultView.setText("Cevap Yanlış !!! ");
resultOfAnswers = resultOfAnswers + "0$";
}
userAnswers = userAnswers + userAnswer + "$";
rightAnswers = rightAnswers + currentQuestion.getRightAnswer()
+ "$";
}
}
public void loadDesign() {
allTotalPlain = (LinearLayout) findViewById(R.id.allTotalPlain);
allTotalPlain.setBackgroundResource(R.drawable.yellow_button);
choiceATotalPlain = (LinearLayout) findViewById(R.id.choiceTotalPlain);
choiceBTotalPlain = (LinearLayout) findViewById(R.id.choiceBTotalPlain);
choiceCTotalPlain = (LinearLayout) findViewById(R.id.choiceCTotalPlain);
choiceDTotalPlain = (LinearLayout) findViewById(R.id.choiceDTotalPlain);
choiceETotalPlain = (LinearLayout) findViewById(R.id.choiceETotalPlain);
layoutForA = (LinearLayout) findViewById(R.id.abuttonLayout);
layoutForB = (LinearLayout) findViewById(R.id.bButtonLayout);
layoutForC = (LinearLayout) findViewById(R.id.cButtonLayout);
layoutForD = (LinearLayout) findViewById(R.id.dButtonLayout);
layoutForE = (LinearLayout) findViewById(R.id.ebuttonLayout);
createButton("A");
createButton("B");
createButton("C");
createButton("D");
createButton("E");
}
private void showQuestion() {
questionText = (TextView) findViewById(R.id.soruTextView);
choiceA = (TextView) findViewById(R.id.choiceA);
choiceB = (TextView) findViewById(R.id.choiceB);
choiceC = (TextView) findViewById(R.id.choiceC);
choiceD = (TextView) findViewById(R.id.choiceD);
choiceE = (TextView) findViewById(R.id.choiceE);
currentQuestion = setQuestionFieldById(currentQuestionIndex);
questionText.setText(currentQuestion.getQuestionText());
choiceA.setText(currentQuestion.getChoiceA());
choiceB.setText(currentQuestion.getChoiceB());
choiceC.setText(currentQuestion.getChoiceC());
choiceD.setText(currentQuestion.getChoiceD());
choiceE.setText(currentQuestion.getChoiceE());
/*
* consumerAnswer .setOnCheckedChangeListener(new
* OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup
* group, int checkedId) { if (choiceA.getId() == checkedId) {
* approveAnswer(2, "A"); } if (choiceB.getId() == checkedId) {
*
* approveAnswer(2, "B"); } if (choiceC.getId() == checkedId) {
*
* approveAnswer(2, "C"); } if (choiceD.getId() == checkedId) {
*
* approveAnswer(2, "D"); } if (choiceE.getId() == checkedId) {
*
* approveAnswer(2, "E"); } } });
*/
}
private void approveAnswer(int optionToSeeQuestion, final String userChoice) {
callEvaluationActivity(optionToSeeQuestion, userChoice);
}
// Eger optionToSeeQuestion 1 ise kullanıcının cevap karsılastırılması
// yapılmamalı 2 ise yapılmalı
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 999) {
if (data.hasExtra("action")) {
String aim = data.getExtras().getString("aim");
Toast.makeText(this, "Ne yapmak istiyorsunuz" + aim,
Toast.LENGTH_LONG).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void qINextQuestion(View view) {
if (currentQuestionIndex == nodeList.getLength() - 1) {
Toast.makeText(QuestionInterfaceActivity.this, "Son Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex++;
settleOrientation();
showQuestion();
}
}
public void qIPrevious(View view) {
if (currentQuestionIndex == 1) {
Toast.makeText(QuestionInterfaceActivity.this, "İlk Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex--;
settleOrientation();
showQuestion();
}
}
public Question setQuestionFieldById(int questionId) {
Question q = new Question();
for (int i = 0; i < nodeList.getLength(); i++) {
node = nodeList.item(i);
int idFromXml = Integer.parseInt(parseItToStringByName(node,
"questionNumber"));
if (questionId == idFromXml) {
q.setQuestionId(questionId);
q.setChoiceA(parseItToStringByName(node, "choiceA"));
q.setChoiceB(parseItToStringByName(node, "choiceB"));
q.setChoiceC(parseItToStringByName(node, "choiceC"));
q.setChoiceD(parseItToStringByName(node, "choiceD"));
q.setChoiceE(parseItToStringByName(node, "choiceE"));
q.setQuestionText(parseItToStringByName(node,
"questionText"));
q.setRightAnswer(parseItToStringByName(node,
"rightAnswer"));
q.setRightAnswerDetail(parseItToStringByName(node,
"answerDetail"));
}
}
return q;
}
public String parseItToStringByName(Node node, String nodeName) {
Element mainELement = (Element) node;
NodeList questionList = mainELement.getElementsByTagName(nodeName);
Element questionElement = (Element) questionList.item(0);
NodeList question = questionElement.getChildNodes();
String result = question.item(0).getNodeValue().replaceAll("\n", "")
.replaceAll("\t", "");
result.trim();
return result;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.landscapequestion);
showQuestion();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.buttontry);
showQuestion();
}
}
#Override
public void onBackPressed() {
beforeQuitProcess();
super.onBackPressed();
}
public void beforeQuitProcess() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("testId", testRelationId));
postParameters
.add(new BasicNameValuePair("rightAnswers", rightAnswers));
postParameters.add(new BasicNameValuePair("userAnswers", userAnswers));
postParameters.add(new BasicNameValuePair("userAnswerAndResult",
resultOfAnswers));
postParameters.add(new BasicNameValuePair("userId", userId));
PostDataToServer postDataToServer = new PostDataToServer();
HttpResponse response = postDataToServer.postData(willPostUrl,
postParameters);
contentStream = postDataToServer.parseHttpResponseToStream(response);
String responseFromServer = postDataToServer
.convertStreamToString(contentStream);
if (responseFromServer != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Kayıt Edildi",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Çıktı Hacı",
Toast.LENGTH_SHORT).show();
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
finish();
}
public void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
#Override
protected void onResume() {
super.onResume();
}
public void onshowAnswer(View v) {
callEvaluationActivity(1, "A");
}
public void onshowQuestion(View view) {
setContentView(R.layout.buttontry);
loadDesign();
showQuestion();
}
public void goHome(View view) {
beforeQuitProcess();
Intent intent = new Intent(QuestionInterfaceActivity.this,
LoginEvaluation.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
public void createButton(final String text) {
Button button = new Button(this);
button.setTextColor(Color.parseColor("#000000"));
button.setBackgroundResource(R.drawable.button_selector);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
clickMeMyFriend(view, text);
}
});
button.setText(text);
if (text.equals("A")) {
layoutForA.addView(button);
}
if (text.equals("B")) {
layoutForB.addView(button);
}
if (text.equals("C")) {
layoutForC.addView(button);
}
if (text.equals("D")) {
layoutForD.addView(button);
}
if (text.equals("E")) {
layoutForE.addView(button);
}
}
private void clickMeMyFriend(View view, String chooice) {
if (chooice.equals("A")) {
approveAnswer(2, "A");
}
if (chooice.equals("B")) {
approveAnswer(2, "B");
}
if (chooice.equals("C")) {
approveAnswer(2, "C");
}
if (chooice.equals("D")) {
approveAnswer(2, "D");
}
if (chooice.equals("E")) {
approveAnswer(2, "E");
}
}
public void onTotalAClick(View view) {
switch (view.getId()) {
case R.id.choiceTotalPlain:
choiceATotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "A");
break;
case R.id.choiceBTotalPlain:
choiceBTotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "B");
break;
case R.id.choiceCTotalPlain:
approveAnswer(2, "C");
choiceCTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceDTotalPlain:
approveAnswer(2, "D");
choiceDTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceETotalPlain:
approveAnswer(2, "E");
choiceETotalPlain.setBackgroundResource(R.drawable.black_button);
break;
default:
break;
}
}
}
Thanks for all help
Thanks too much for your effort Barak , Alex Lockwood and the others too i recode my xml layout upon your advices nothing changed but i could seen an error cant be realize before due to my unnecassary LinearLayout block .Whatever the error is :there is a statement in my layout
android:textStyle="#style/boldText"
in this statement the value can be only bold or normal etc .this statement should be like
style="#style/choiceStyle"
thanks for your help .I decided not to work after 00:00
Are you saying you are trying to use setContentView more than once in an activity?
From everything I have read, that won't work.
If you want to change your UI without switching activities you need to use fragments, or put all of the Views you want into your one layout and hide/show only the relevant ones for each portion of your activity with setVisibility().
The reason why you are getting a NumberFormatException is because #2131230721 is not an integer. Here's what you should do:
Re-do your entire XML layout. I am not kidding... the layout you have posted is an absolute disaster. Sorry if that's mean, but I can't let you go on thinking this is the correct way to make your layouts :).
From what I can tell, you are wrapping every single view in a LinearLayout to achieve some sort of margin/padding effect. This is what the android:margin and android:padding attributes are for. Don't over-complicate things with weird android:layout_weight values, as this will make your app run slower when your layout gets inflated. If you ever find that your XML has more than 3 or 4 LinearLayouts you should take a step back and see if you are missing an easier, more efficient solution. It is frowned upon to have nested LinearLayouts too, as it is expensive to inflate these at runtime and will drain your battery as a result.
Do a Project --> Clean and restart eclipse.
Post more information. For example, your entire logcat output would be nice (not just one line). Posting your code is almost always a good idea too. It is very difficult to understand the problem from the tiny amount of information you have provided. Remember that it is beneficial to you to provide as much information as you can because the more information we have, the more likely it is that we can help answer your question. You should also provide us with line numbers and/or indicate on which lines the errors occur.
Oh yeah, and welcome to StackOverflow... :P
Is it possible that the weights are causing the problems? I've never used weights as decimals before, I thought they had to be real numbers, I mean like 1 or 2 etc. Floor numbers. Just a thought
From what I can see its something to do with a number and a text view, this could either be the text views color, weight, ID or style.
What's in style/boldText and style/rightAnswer?
You layout file does Start with a LinearLayout and defines a xmlns:android="http://schemas.android.com/apk/res/android", but you end up with a closing <ScrollView> Tag? Is there anything missing? Plus, javaCode would be great!
By the way: did u try to "clean" you project in eclipse, using Project->Clean?
This resets the R file and often helps!
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);
}
}