I am new to programming and android. I'm building an app that allows users to upload multiple images by clicking on ImageViews that are displayed in a TableLayout. The problem i am having is how to set the bitmap of each selected image in the onStartActivity method.
I can set a single image to an imageiew by using setImageBitmap but I am unsure how to loop through or programmatically determine which ImageView has been selected in onStartActivity in order to display the image in it. I have created an ImageView array and assigned the ImageViews to it but my attempts to use the array does not display any images. I have also tried to display the ImageView through the setImageBitmap method in each onclicklistener after startActivityForResult - it only displays after the ImageView is selected again, as expected.
How can i make this work? This is my first post. Here is my code:
The XML layout below.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical">
<TextView
android:id="#+id/postAdCommand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="10dp"
android:text="Post An Ad"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title:"
android:textColor="#ffffff" />
<EditText
android:id="#+id/etTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Description:"
android:textColor="#ffffff" />
<EditText
android:id="#+id/etDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvImages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="10dp"
android:text="Upload Images:"
android:textColor="#ffffff" />
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TableRow>
<ImageView
android:id="#+id/imgImages"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:clickable="true"
android:src="#drawable/add_image" />
<ImageView
android:id="#+id/imgImages1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
<ImageView
android:id="#+id/imgImages2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imgImages3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
<ImageView
android:id="#+id/imgImages4"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
<ImageView
android:id="#+id/imgImages5"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imgImages6"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
<ImageView
android:id="#+id/imgImages7"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
<ImageView
android:id="#+id/imgImages8"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#1f1f14" />
</TableRow>
<Button
android:id="#+id/bImages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Upload Images"
android:textColor="#000000" />
</TableLayout>
<TextView
android:id="#+id/tvVideos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Upload Images:"
android:textColor="#ffffff" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal">
<VideoView
android:id="#+id/vidVideo"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#drawable/back_button_gray"
android:clickable="true" />
<VideoView
android:id="#+id/vidVideo1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#drawable/back_button_gray"
android:clickable="true" />
<VideoView
android:id="#+id/vidVideo2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="2dp"
android:background="#drawable/back_button_gray"
android:clickable="true" />
</LinearLayout>
<Button
android:id="#+id/bVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Upload Video"
android:textColor="#000000" />
<TextView
android:id="#+id/tvPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price:"
android:textColor="#ffffff" />
<EditText
android:id="#+id/etPrice"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/bPostAd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Post Your Advertisement" />
</LinearLayout>
</ScrollView>
Then the Java code.
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class PostAd extends AppCompatActivity implements View.OnClickListener {
Button imageUpload;
Button vidUpload;
Button postAd;
ImageView img1, img2, img3, img4, img5, img6, img7, img8, img9;
public static final int SELECT_IMAGE = 1;
private Uri selectedImagePath;
public String selectedFileManager;
public String selectedFilePath;
Bitmap bitmap;
public ImageView[] position = {img1, img2, img3, img4, img5, img6, img7, img8, img9};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_ad);
initializeVariables();
initOnclickListeners();
}
private void initializeVariables() {
imageUpload = (Button) findViewById(R.id.bImages);
vidUpload = (Button) findViewById(R.id.bVideo);
postAd = (Button) findViewById(R.id.bPostAd);
img1 = (ImageView) findViewById(R.id.imgImages);
img2 = (ImageView) findViewById(R.id.imgImages1);
img3 = (ImageView) findViewById(R.id.imgImages2);
img4 = (ImageView) findViewById(R.id.imgImages3);
img5 = (ImageView) findViewById(R.id.imgImages4);
img6 = (ImageView) findViewById(R.id.imgImages5);
img7 = (ImageView) findViewById(R.id.imgImages6);
img8 = (ImageView) findViewById(R.id.imgImages7);
img9 = (ImageView) findViewById(R.id.imgImages8);
}
private void initOnclickListeners() {
imageUpload.setOnClickListener(this);
vidUpload.setOnClickListener(this);
postAd.setOnClickListener(this);
img1.setOnClickListener(this);
img2.setOnClickListener(this);
img3.setOnClickListener(this);
img4.setOnClickListener(this);
img5.setOnClickListener(this);
img6.setOnClickListener(this);
img7.setOnClickListener(this);
img8.setOnClickListener(this);
img9.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bImages:
break;
case R.id.bVideo:
break;
case R.id.bPostAd:
break;
case R.id.imgImages:
Intent image = new Intent();
image.setType("image/*");
image.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image, SELECT_IMAGE);
break;
case R.id.imgImages1:
Intent image1 = new Intent();
image1.setType("image/*");
image1.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image1, SELECT_IMAGE);
break;
case R.id.imgImages2:
Intent image2 = new Intent();
image2.setType("image/*");
image2.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image2, SELECT_IMAGE);
break;
case R.id.imgImages3:
Intent image3 = new Intent();
image3.setType("image/*");
image3.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image3, SELECT_IMAGE);
break;
case R.id.imgImages4:
Intent image4 = new Intent();
image4.setType("image/*");
image4.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image4, SELECT_IMAGE);
break;
case R.id.imgImages5:
Intent image5 = new Intent();
image5.setType("image/*");
image5.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image5, SELECT_IMAGE);
break;
case R.id.imgImages6:
Intent image6 = new Intent();
image6.setType("image/*");
image6.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image6, SELECT_IMAGE);
break;
case R.id.imgImages7:
Intent image7 = new Intent();
image7.setType("image/*");
image7.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image7, SELECT_IMAGE);
break;
case R.id.imgImages8:
Intent image8 = new Intent();
image8.setType("image/*");
image8.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(image8, SELECT_IMAGE);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_IMAGE && resultCode == RESULT_OK) {
try {
selectedImagePath = data.getData();
selectedFileManager = selectedImagePath.getPath();
selectedFilePath = getPath(selectedImagePath);
bitmap = BitmapFactory.decodeFile(selectedFilePath);
if (position.length == 0) {
position[0].setImageBitmap(bitmap);
} else if (position.length == 1) {
position[1].setImageBitmap(bitmap);
} else if (position.length == 2) {
position[2].setImageBitmap(bitmap);
} else if (position.length == 3) {
position[3].setImageBitmap(bitmap);
} else if (position.length == 4) {
position[4].setImageBitmap(bitmap);
} else if (position.length == 5) {
position[5].setImageBitmap(bitmap);
} else if (position.length == 6) {
position[6].setImageBitmap(bitmap);
} else if (position.length == 7) {
position[7].setImageBitmap(bitmap);
} else if (position.length == 8) {
position[8].setImageBitmap(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(uri, projection, null, null, null, null);
if (c != null) {
int column_index = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
c.moveToFirst();
return c.getString(column_index);
} else return null;
}
}
In your case you need to keep track of each of imageview with position rather than using array
imageView.setTag(position)
imageView.getTag(position)
based on it you can set your logic .
Related
I am new to android development.
Following is the code to my android app called "My Fruit List" in which Main Activity shows chosen fruits in "Text Views" arranged in "Linear Layout (vertical orientation)" inside "Scroll Views" that are selected from the second layout by using the "ADD A FRUIT" button at the bottom of the current Main Layout. This program functions as expected but I have two questions:
My first question is that as I have made the Main Activity as the parent activity for the second layout that's working as a child activity. But when I move from child to parent using the left arrow at the top left all the data from Main Activity's Text Views are vanished. I have overridden onSaveInstance and onRestoreInstance for keeping the main activity's data when screen's rotated but when I move from child to parent using the top left arrow it vanishes all the data present in those "Text Views". Why?
My second question is that how can I optimize my code means by making it more shorter and clearer?
Much Thanks!
MainActivity.java:
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Button button_addItem;
private TextView item1;
private TextView item2;
private TextView item3;
private TextView item4;
private TextView item5;
private TextView item6;
private TextView item7;
private TextView item8;
private TextView item9;
private TextView item10;
private static final int CHOSEN_FRUIT = 1;
//string keys for onSaveInstance and onRestoreInstance
private static final String ITEM_1_KEY = "item1key";
private static final String ITEM_2_KEY = "item2key";
private static final String ITEM_3_KEY = "item3key";
private static final String ITEM_4_KEY = "item4key";
private static final String ITEM_5_KEY = "item5key";
private static final String ITEM_6_KEY = "item6key";
private static final String ITEM_7_KEY = "item7key";
private static final String ITEM_8_KEY = "item8key";
private static final String ITEM_9_KEY = "item9key";
private static final String ITEM_10_KEY = "item10key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_addItem = findViewById(R.id.button_addItem);
item1 = findViewById(R.id.textView_item1);
item2 = findViewById(R.id.textView_item2);
item3 = findViewById(R.id.textView_item3);
item4 = findViewById(R.id.textView_item4);
item5 = findViewById(R.id.textView_item5);
item6 = findViewById(R.id.textView_item6);
item7 = findViewById(R.id.textView_item7);
item8 = findViewById(R.id.textView_item8);
item9 = findViewById(R.id.textView_item9);
item10 = findViewById(R.id.textView_item10);
button_addItem.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AvailableItems.class);
startActivityForResult(intent, CHOSEN_FRUIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOSEN_FRUIT) {
if (resultCode == RESULT_OK) {
if (item1.getText().toString().equalsIgnoreCase("empty"))
item1.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item2.getText().toString().equalsIgnoreCase("empty"))
item2.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item3.getText().toString().equalsIgnoreCase("empty"))
item3.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item4.getText().toString().equalsIgnoreCase("empty"))
item4.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item5.getText().toString().equalsIgnoreCase("empty"))
item5.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item6.getText().toString().equalsIgnoreCase("empty"))
item6.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item7.getText().toString().equalsIgnoreCase("empty"))
item7.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item8.getText().toString().equalsIgnoreCase("empty"))
item8.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item9.getText().toString().equalsIgnoreCase("empty"))
item9.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item10.getText().toString().equalsIgnoreCase("empty"))
item10.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else
Toast.makeText(this, "List is full!", Toast.LENGTH_SHORT).show();
// Log.d("TESTMESSAGE", "onActivityResult: " + data.getStringExtra(AvailableItems.FRUIT_ID));
}
}
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString(ITEM_1_KEY, item1.getText().toString());
outState.putString(ITEM_2_KEY, item2.getText().toString());
outState.putString(ITEM_3_KEY, item3.getText().toString());
outState.putString(ITEM_4_KEY, item4.getText().toString());
outState.putString(ITEM_5_KEY, item5.getText().toString());
outState.putString(ITEM_6_KEY, item6.getText().toString());
outState.putString(ITEM_7_KEY, item7.getText().toString());
outState.putString(ITEM_8_KEY, item8.getText().toString());
outState.putString(ITEM_9_KEY, item9.getText().toString());
outState.putString(ITEM_10_KEY, item10.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
item1.setText(savedInstanceState.get(ITEM_1_KEY).toString());
item2.setText(savedInstanceState.get(ITEM_2_KEY).toString());
item3.setText(savedInstanceState.get(ITEM_3_KEY).toString());
item4.setText(savedInstanceState.get(ITEM_4_KEY).toString());
item5.setText(savedInstanceState.get(ITEM_5_KEY).toString());
item6.setText(savedInstanceState.get(ITEM_6_KEY).toString());
item7.setText(savedInstanceState.get(ITEM_7_KEY).toString());
item8.setText(savedInstanceState.get(ITEM_8_KEY).toString());
item9.setText(savedInstanceState.get(ITEM_9_KEY).toString());
item10.setText(savedInstanceState.get(ITEM_10_KEY).toString());
}}
AvailableItems (SecondActivity):
package com.xafak.fruitshoppinglist;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class AvailableItems extends AppCompatActivity {
private Button bananaImage;
private Button grapeImage;
private Button appleImage;
private Button watermelonImage;
private Button pineappleImage;
private Button avocadoImage;
private Button cherryImage;
private Button cirtusImage;
private Button strawberryImage;
private Button pomegranateImage;
public static final String FRUIT_ID = "fruit_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_items);
bananaImage = findViewById(R.id.bananas);
grapeImage = findViewById(R.id.grapes);
appleImage = findViewById(R.id.apple);
watermelonImage = findViewById(R.id.watermelon);
pineappleImage = findViewById(R.id.pineapple);
avocadoImage = findViewById(R.id.avocado);
cherryImage = findViewById(R.id.cherry);
cirtusImage = findViewById(R.id.citrus);
strawberryImage = findViewById(R.id.strawberry);
pomegranateImage = findViewById(R.id.pomegranate);
}
public void addItemToList(View v) {
switch (v.getId()) {
case R.id.bananas:
configureIntent("Bananas");
break;
case R.id.grapes:
configureIntent("Grapes");
break;
case R.id.apple:
configureIntent("Apple");
break;
case R.id.watermelon:
configureIntent("Watermelon");
break;
case R.id.pineapple:
configureIntent("Pineapple");
break;
case R.id.avocado:
configureIntent("Avocado");
break;
case R.id.cherry:
configureIntent("Cherry");
break;
case R.id.citrus:
configureIntent("Citrus");
break;
case R.id.strawberry:
configureIntent("Strawberry");
break;
case R.id.pomegranate:
configureIntent("Pomegranate");
break;
default:
}
}
public void configureIntent(String fruitName) {
Intent replyIntent = new Intent();
replyIntent.putExtra(FRUIT_ID, fruitName);
setResult(RESULT_OK, replyIntent);
finish();
} }
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xafak.fruitshoppinglist">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AvailableItems"
android:label="Available Fruits"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="8dp"
android:foregroundGravity="center_vertical|clip_horizontal|center"
app:layout_constraintBottom_toTopOf="#+id/button_addItem"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView_item1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item9"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item10"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/button_addItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:text="#string/select_fruit"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="213dp"
android:layout_height="61dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/shoppingcart" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_available_items.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AvailableItems">
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline2"
app:layout_constraintHorizontal_bias="0.39"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline3">
<Button
android:id="#+id/bananas"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/bananas"
android:textSize="20sp" />
<Button
android:id="#+id/apple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/apple"
android:textSize="20sp" />
<Button
android:id="#+id/avocado"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/avocado"
android:textSize="20sp" />
<Button
android:id="#+id/cherry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/cherry"
android:textSize="20sp" />
<Button
android:id="#+id/citrus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/citrus"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline2"
app:layout_constraintTop_toTopOf="#+id/guideline3">
<Button
android:id="#+id/grapes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/grapes"
android:textSize="20sp" />
<Button
android:id="#+id/pineapple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/pineapple"
android:textSize="20sp" />
<Button
android:id="#+id/pomegranate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/pomegranate"
android:textSize="20sp" />
<Button
android:id="#+id/strawberry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/strawberry"
android:textSize="20sp" />
<Button
android:id="#+id/watermelon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/watermelon"
android:textSize="20sp" />
</LinearLayout>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="50dp"
android:layout_height="50dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_percent="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline3"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_percent="0.3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="583dp"
android:layout_height="97dp"
android:contentDescription="#string/fruit_image"
app:layout_constraintBottom_toTopOf="#+id/guideline3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/fruitmarket" />
</androidx.constraintlayout.widget.ConstraintLayout>
There is no Need for onSaveInstanceState or onRestoreState.
use an arraylist, which holds the Strings for your TextViews.
private ArrayList<String> arraylist = ArrayList<String>();
This will make sure, that at the beginning you have an empty arraylist.
In OnActivityResult you add the new received String to the arraylist.
if (requestCode == CHOSEN_FRUIT) {
if (resultCode == RESULT_OK) {
arraylist.add(data.getStringExtra(AvailableItems.FRUIT_ID));
}
}
finally you use the Strings in onResume to fill your TextViews with data.
if(arraylist.size==1){
TextView1.setText(arraylist[0];
}
if(arraylist.size==2){
TextView2.setText(arraylist[1];
}
.
.
.
Even when your device is rotated the data inside your ArrayList should be kept and the TextViews gets filled with data in onResume.
This is not the most elegant way to make a list, as it does not increase dynamically in size, but for a dynamic increase in size you could implement a recyclerview for example.
In my application , one Relative Layout has totally three ImageView()'s . I want to save all the three imageviews as a single .png file to the device storage on a single button click.
My code:
Layout XML :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/make" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:layout_above="#+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/am0" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Save Meme"
android:textStyle="bold"
android:textColor="#color/wt" />
<ImageView
android:id="#+id/top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="64dp"
android:src="#drawable/ic_launcher" />
<ImageView
android:id="#+id/down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="74dp"
android:src="#drawable/ic_launcher" />
Activity Code :
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sm);
main1 = (ImageView) findViewById(R.id.imageView1);
top = (ImageView) findViewById(R.id.top);
down = (ImageView) findViewById(R.id.down);
Bundle rec = getIntent().getExtras();
int rec1 = getIntent().getExtras().getInt("ams0");
Bitmap bmp = (Bitmap) rec.getParcelable("bm0");
Bitmap bmp1 = (Bitmap) rec.getParcelable("bm1");
main1.setImageResource(rec1);
top.setImageBitmap(bmp);
down.setImageBitmap(bmp1);
}
How do I save the image views as a file ?
Try using a Сanvas
Bitmap mainBitmap = ((BitmapDrawable)main1.getDrawable()).getBitmap().copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mainBitmap);
canvas.drawBitmap(bmp.copy(Bitmap.Config.ARGB_8888, true), 1, 1, null);
canvas.drawBitmap(bmp1.copy(Bitmap.Config.ARGB_8888, true), 1, 1, null);
OutputStream os = null;
try {
os = new FileOutputStream("/sdcard/DCIM/Camera/myImages.png");
mainBitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
} catch (IOException e) {
e.printStackTrace();
}
I just do my project but when I test my app I found that then I touch the screen by using more than one fingers my app may start two or three different activities.
The activities all go to the back stack. Is this a bug in Android framework? But I can't reappear this condition, it just happened.
So, have you guys ever have this problem? Please come and discuss with me. If you do; Thanks.
Supply:
And here is My xml file , when I click the different RelativeLayout at the same time , it happened.
I tried this afternoon , but this condition is not appear anymore. Now I am confusing.
<LinearLayout android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/appDefaultSingleBlockBackground"
android:layout_height="wrap_content">
<RelativeLayout android:layout_width="match_parent"
android:layout_height="100dp"
android:clickable="true"
android:background="#drawable/mine_bg"
android:id="#+id/mine_goto_personal_info_btn"
>
<TextView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:id="#+id/mine_nick_and_avatar"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextTitle"
android:textColor="#color/appDefaultSingleBlockBackground"
android:text=""/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_interesting_venue"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_attentionbutton"
android:text="#string/myAtentionVenue"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_setting"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_setbutton"
android:text="#string/setting"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_youhuijuan"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_discountbutton"
android:text="#string/youhuijuan"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_my_rest_money"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_balancebutton"
android:text="#string/myRest"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#color/dividerdefault"
/>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/appDefaultSingleBlockBackground"
android:clickable="true"
android:id="#+id/mine_goto_secure"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:drawablePadding="10dp"
android:layout_marginLeft="15dp"
style="#style/TextNomal"
android:drawableLeft="#drawable/information_accountssafebutton"
android:text="#string/secure"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/venue_maxbutton"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/dividerdefault"
/>
</LinearLayout>
and this is my java code .
private void init(View ret) {
final TextView txtAvatar = (TextView) ret.findViewById(R.id.mine_nick_and_avatar);
final RelativeLayout gotoPersonal = (RelativeLayout) ret.findViewById(R.id.mine_goto_personal_info_btn);
RelativeLayout gotoInterest = (RelativeLayout) ret.findViewById(R.id.mine_goto_interesting_venue);
RelativeLayout gotoSetting = (RelativeLayout) ret.findViewById(R.id.mine_goto_setting);
RelativeLayout gotoYouhuijuan = (RelativeLayout) ret.findViewById(R.id.mine_goto_youhuijuan);
RelativeLayout gotoMyRestMoney = (RelativeLayout) ret.findViewById(R.id.mine_goto_my_rest_money);
RelativeLayout gotoSecure = (RelativeLayout) ret.findViewById(R.id.mine_goto_secure);
gotoPersonal.setTag("gotoPersonal");
gotoInterest.setTag("gotoInterest");
gotoSetting.setTag("gotoSetting");
gotoYouhuijuan.setTag("gotoYouhuijuan");
gotoMyRestMoney.setTag("gotoMyRestMoney");
gotoSecure.setTag("gotoSecure");
try {
Object o = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[1]);
if (o != null && !"null".equals(o)) {
txtAvatar.setText((String) o);
} else {
o = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[10]);
if (o != null && !"null".equals(o))
txtAvatar.setText("KD" + o);
}
} catch (Exception e) {
}
Object o1 = SharedPreferenceUtils.readInfo(mActivity, ConstData.UserInfo[2]);
if (o1 != null)
MyApplication.downloader.download("http://" + o1, new ImageDownloadStateListener() {
#Override
public void loading() {
}
#Override
public void loadSuccess(Bitmap bitmap, String url) {
try {
bitmap = Tools.transforCircleBitmap(bitmap);
BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
gotoPersonal.measure(0, 0);
int measuredHeight = gotoPersonal.getMeasuredHeight();
LogHelper.print("==height" + measuredHeight);
drawable.setBounds(0, 0, measuredHeight / 5 * 4, measuredHeight / 5 * 4);
txtAvatar.setCompoundDrawables(drawable, null, null, null);
} catch (Exception e) {
//no nothing
}
}
#Override
public void loadFailed() {
}
});
gotoPersonal.setOnClickListener(this);
gotoInterest.setOnClickListener(this);
gotoSetting.setOnClickListener(this);
gotoYouhuijuan.setOnClickListener(this);
gotoMyRestMoney.setOnClickListener(this);
gotoSecure.setOnClickListener(this);
}
#Override
public void onResume() {
initActionBar();
super.onResume();
MobclickAgent.onPageStart(getClassName()); //统计页面
}
#Override
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd(getClassName());
}
private String getClassName() {
String canonicalName = this.getClass().getCanonicalName();
String[] split = canonicalName.split("\\.");
return split[split.length - 1];
}
private void initActionBar() {
MyActivity activity = (MyActivity) mActivity;
activity.setActionBarLeftImg(new ColorDrawable(Color.TRANSPARENT), false);
activity.setActionBarRightImg(new ColorDrawable(Color.TRANSPARENT));
activity.setOnActionBarLeftClickListener(null);
activity.setOnActionBarRightClickListener(null);
activity.setActionBarTitle("个人中心");
}
#Override
public void onClick(View v) {
Object tag = v.getTag();
if (tag != null) {
String str = (String) tag;
if (mActivity == null) {
return;
}
if (!((MyActivity) (mActivity)).isLogin) {
Intent intent = new Intent(mActivity, LoginActivity.class);
startActivity(intent);
return;
}
if (!TextUtils.isEmpty(str))
if ("gotoPersonal".equals(str)) {
Intent intent = new Intent(mActivity, PersonalInfoActivity.class);
startActivity(intent);
} else if ("gotoInterest".equals(str)) {
Intent intent = new Intent(mActivity, VenueListActivity.class);
intent.putExtra("isInterests", true);
startActivity(intent);
} else if ("gotoSetting".equals(str)) {
Intent intent = new Intent(mActivity, SettingActivity.class);
startActivity(intent);
} else if ("gotoYouhuijuan".equals(str)) {
Intent intent = new Intent(mActivity, FavorableActivity.class);
startActivity(intent);
} else if ("gotoSecure".equals(str)) {
Intent intent = new Intent(mActivity, SecureActivity.class);
startActivity(intent);
} else if ("gotoMyRestMoney".equals(str)) {
Intent intent = new Intent(mActivity, MyRestActivity.class);
startActivity(intent);
}
}
}
You need to define the launch mode. There are at least two ways of solving this by either using the manifest file (hint: singleTop) or by using Intent flags (hint: FLAG_ACTIVITY_SINGLE_TOP).
Good luck!
Simpliest approach would be disable control that starts your Activity (button for example) after 1 click, and enable it later with some condition or action. Try it.
You can use this approach.......
((Button)findViewById(R.id.someButton)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button)findViewById(R.id.someButton)).setEnabled(false);
}
});
Happy coding
i am developing a quiz using mobile application. currently, i am having problems on how to retrieve selected radio button from previous page. i want the selected radio button value to be displayed on the next page. below is my code in xml and java.
question1. java
public class question1 extends Activity {
private Button Button2;
public RadioButton r1,r2,r3;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question1);
r1 = (RadioButton)findViewById(R.id.rb1);
r2 = (RadioButton)findViewById(R.id.rb2);
r3 = (RadioButton)findViewById(R.id.rb3);
//Button2
Button2 = (Button) findViewById(R.id.button1);
Button2.setOnClickListener((new OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(view.getContext(),question2.class);
intent.putExtra("r1",r1.isSelected());
intent.putExtra("r2",r2.isSelected());
intent.putExtra("r3",r3.isSelected());
startActivityForResult(intent,0);
}
}));
}
}
this is my code in question1.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="452dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:src="#drawable/clay" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="YANG MANA SATUKAH DI ANTARA AYAT-AYAT BERIKUT YANG BENAR ?"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/radioButton2"
android:text="A.Tanah liat yang leper lebih berat" />
<RadioButton
android:id="#+id/rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/radioButton3"
android:text=" B. Kedua-dua tanah liat adalah sama berat" />
<RadioButton
android:id="#+id/rb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignLeft="#+id/radioButton2"
android:layout_marginBottom="14dp"
android:text="C.Bola tanah liat lebih berat" />
</RadioGroup>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="right"
android:background="#drawable/nextnext" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
this is my code for the second page that i want the selected radio button value to be displayed.
question2. java
public class question2 extends Activity
{
private Button Button2;
public RadioButton r1,r2,r3,r4,r5;
public RadioGroup rg1,rg2;
public String a2,b2,total;
public TextView output ;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.question2);
output = (TextView)findViewById(R.id.textView5);
r1 = (RadioButton)findViewById(R.id.rb1);
r2 = (RadioButton)findViewById(R.id.rb2);
r3 = (RadioButton)findViewById(R.id.rb3);
r4 = (RadioButton)findViewById(R.id.rb4);
r5 = (RadioButton)findViewById(R.id.rb5);
rg1 = (RadioGroup)findViewById(R.id.radioGroup1);
rg2 = (RadioGroup)findViewById(R.id.radioGroup2);
Object RadioButton;
r1= (RadioButton).getValue();
r2 =(RadioButon).getValue();
r3 =(RadioButon).getValue();
//Button2
Button2 = (Button) findViewById(R.id.button1);
Button2.setOnClickListener((new OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(view.getContext(),question3.class);
startActivityForResult(intent,0);
}
}
));
{
switch(rg2.getCheckedRadioButtonId()){
case R.id.rb4:
if (r4.isChecked()){
//a2 =0;
}
break;
case R.id.rb5:
if (r5.isChecked()){
//b2 = 1;
}
break;
//total = rg1.getCheckedRadioButtonId()+rg2.getCheckedRadioButtonId() ;
}}
//receive the arguments from the previous Activity
Bundle extras = getIntent().getExtras();
if (extras==null) {
return;
}
output = (TextView) findViewById(R.id.textView5);
Bundle data = this.getIntent().getExtras();
r1=data.getValue(r1);
r2=data.getValue(r2);
r3=data.getValue(r3);
double result = 0;
if (r1 == "")
{
result+ = 1;
}
else if (r2 == "true"){
result+ = 0;}
else if (r3=="true")
{
result+ = 0;
}
else {
result + =0;
}
}
}
}
question2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="452dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_weight="0.13"
android:src="#drawable/soklan2" />
<RadioGroup
android:id="#+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/textView4" >
<RadioButton
android:id="#+id/rb4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A. Ya" />
<RadioButton
android:id="#+id/rb5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_below="#+id/radioGroup1"
android:text="B. Tidak" />
</RadioGroup>
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup2"
android:layout_marginTop="20dp"
android:text="Result"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="right"
android:background="#drawable/nextnext" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
I would like to know, how to retrieve the value from question 1 and displayed it on question2 page.
you could use:
r1.setChecked(getIntent().getExtras().getBoolean("r1"));
r2.setChecked(getIntent().getExtras().getBoolean("r2"));
r3.setChecked(getIntent().getExtras().getBoolean("r3"));
You may also need to change the code where you put the values:
intent.putExtra("r1",r1.isChecked());
intent.putExtra("r2",r2.isChecked());
intent.putExtra("r3",r3.isChecked());
You should also probably look at this code:
Object RadioButton;
r1 = (RadioButton).getValue();
r2 = (RadioButon).getValue();
r3 = (RadioButon).getValue();
I have no idea what you are trying to accomplish here. And it should probably be removed to keep the refferences to your RadioButton Objects
In you second activity , get the values from intent extras:
Intent intent = getIntent();
boolean r1Value = intent.getBooleanExtra("r1",false);
r1.setChecked(r1Value );
so if the title sounds confusig, this is what actually happens. In the Activity I have a ImageView and it has a defalut picture. This defalut picture should be shown as long as the user picks another picture from gallery. When he does that, the picture which he picked should be shown as long as he doesn't delete it or picks another one. If he deletes it, the default picture should be shown again until he picks new picture from the gallery.
I have successfuly loaded the picture from the gallery but it stays in the imageview only until the applications restarts. After which the default picture will be shown again. Is there any way to fix this?
This is my code
package com.pumperlgsund.activities;
imports...
public class MainActivity extends FragmentActivity implements
OnHeadlineSelectedListener, View.OnClickListener {
private static int LOAD_IMAGE = 1;
private String selectedImagePath;
private ImageView imgUser;
private TextView txtName;
private TextView txtScore;
private TextView txtValue;
private UserDataController controller;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/ComicNeueSansID.ttf");
controller = new UserDataController(this);
imgUser = (ImageView) findViewById(R.id.imgUser);
imgUser.setOnClickListener(this);
txtName = (TextView) findViewById(R.id.txtUserName);
txtName.setTypeface(tf);
txtName.setText(controller.getUserName());
txtScore = (TextView) findViewById(R.id.txtScore);
txtScore.setTypeface(tf);
txtValue = (TextView) findViewById(R.id.txtValue);
txtValue.setTypeface(tf);
txtValue.setText("" + controller.getScore());
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imgUser:
onImageClicked(v);
break;
default:
break;
}
}
private void onImageClicked(View view) {
showPopupMenu(view);
}
private void showPopupMenu(View view) {
PopupMenu popupMenu = new PopupMenu(this, view);
popupMenu.getMenuInflater().inflate(R.menu.popupmenu,
popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.item1) {
//TODO: ...
return true;
} else if (item.getItemId() == R.id.item2) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Load Image"), LOAD_IMAGE);
return true;
} else {
return false;
}
}
});
popupMenu.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == LOAD_IMAGE) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imgUser.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
layout
ImageView has id imgUser, located in RelativLayout user_area_content
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_frame"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="#color/backgroundColor"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<LinearLayout
android:id="#+id/static_area"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/user_area"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:background="#color/white" >
<RelativeLayout
android:id="#+id/user_area_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
<ImageView
android:id="#+id/imgUser"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_marginLeft="8dip"
android:layout_marginTop="8dip"
android:src="#drawable/ic_img_user" />
<TextView
android:id="#+id/txtUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dip"
android:layout_marginTop="8dip"
android:layout_toRightOf="#id/imgUser"
android:text="#string/placeholder"
android:textColor="#color/blue"
android:textSize="16sp" />
<TextView
android:id="#+id/txtScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/txtUserName"
android:layout_marginLeft="8dip"
android:layout_marginTop="8dip"
android:layout_toRightOf="#id/imgUser"
android:text="#string/score"
android:textColor="#color/blue"
android:textSize="16sp" />
<TextView
android:id="#+id/txtValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/txtUserName"
android:layout_marginLeft="8dip"
android:layout_marginTop="8dip"
android:layout_toRightOf="#id/txtScore"
android:text="#string/placeholder"
android:textColor="#color/blue"
android:textSize="16sp" />
</RelativeLayout>
</RelativeLayout>
<fragment
android:id="#+id/headlines_fragment"
android:name="com.pumperlgsund.fragments.HeadlinesFragment"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_marginTop="16dip"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:id="#+id/dynamic_frame"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_marginLeft="16dip"
android:layout_weight="2"
android:orientation="horizontal" />
Thx for help!
The default image is 'shown again' every time the view are (re)built i.e. every time the Activity is created, when the application is started, but also on device rotation. You should save the path to the selected image (in onActivityResult()) and retrieve it in onCreate(). The simplest way to save the path is probably to use a SharedPreferences.
If you want to restrict the selection to local images, add the EXTRA_LOCAL_ONLY extra to the intent.