This is a pretty big question, I tried a lot to do it, but I just didn't get it and im failing pretty hard. So I made an application with an menu with 2buttons. If you click the button "addpic" it goes to the class "FotoMaker" and you can make a picture there if you click the button "make_pic". Now I want to save this picture if a user presses the button "save_pic". Then after when you click on "watch_your_picture" in the MenuScreen.java it should call the watch_pic.xml which is getting called in the ShowPhoto.java file. And you should see the photo(s) in here. This is what I get already:
PhotoMaker.java:
package com.example.random;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class FotoMaker extends Activity
{
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addpic);
iv = (ImageView) findViewById(R.id.imageView);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick (View v){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == 0)
{
Bitmap theImage = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(theImage);
}
}
}
ShowPhoto.java:
package com.example.random;
import android.app.Activity;
import android.os.Bundle;
public class ShowPhoto extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.watch_pic);
}
}
addpic.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|center_horizontal|center_vertical"
android:layout_marginTop="0dp"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="make a picture here"
android:textSize="20sp" />
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.45"
android:src="#drawable/ic_launcher" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/make_pic" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/save_pic" />
</TableRow>
</TableLayout>
</LinearLayout>
watch_pic.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="imageViewer1"
android:src="#drawable/ic_launcher" />
</LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">random</string>
<string name="action_settings">Settings</string>
<string name="watch_your_picture">watch your picture here</string>
<string name="nothing_here_yet">will add something here later</string>
<string name="addpic">make picture here</string>
<string name="verlaat_app">Verlaat de app</string>
<string name="make_pic">make picture</string>
<string name="save_pic">SAVE</string>
<string name="imageView1">test is a generic contect</string>
</resources>
hello you can recover the uri of image in the onActivityResult and when you click to watch_your_picture you send the Uri of the picture to the next activity you can modify your code as above :
`
package com.example.random;
import android.app.Activity;
import android.contect.ContectValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore
import android.util.Log;
import android.net.Uri;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class FotoMaker extends Activity
{
ImageView iv;
Uri uriOfPicture;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.addpic);
iv = (ImageView) findViewById(R.id.imageView);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick (View v){
takeImageFromCamera();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == 0)
{
Bitmap image=createBitmapFromURI(uriOfPicture);
iv.setImageBitmap(image);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (currImageURI != null) {
outState.putString("cameraImageUri", uriOfPicture.toString());
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
uriOfPicture = Uri.parse(savedInstanceState.getString("cameraImageUri"));
}
}
/*********************************** method to take URI of the picture *******************/
public void takeImageFromCamera(){
String fileName = "new-photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image captured by camera");
uriOfPicture = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Log.i("uri",currImageURI.toString());
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriOfPicture);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent,
0);
}
public Bitmap createBitmapFromURI(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getApplicationContext()
.getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (bitmap != null)
/*********dimention**********************/
return Bitmap.createScaledBitmap(bitmap, 100, 100, true);
else {
return null;
}
}
}
`
Related
I am using the following code to select the image from gallery and display them into a single activity (the layout need to consists with six images). What could I make the changes in the following code?
XML code activity_second_3.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".Second_Activity3">
<TextView
android:id="#+id/text_view_show_uploads"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginStart="30dp"
android:layout_marginLeft="30dp"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
android:gravity="center"
android:text="Upload Products Images"
android:textColor="#f00fff"
android:textSize="25sp" />
<Button
android:id="#+id/button_choose_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text_view_show_uploads"
android:layout_marginTop="50dp"
android:text="Choose file" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="231dp"
android:layout_height="45dp"
android:layout_below="#id/text_view_show_uploads"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="50dp"
android:layout_toEndOf="#+id/button_choose_image"
android:layout_toRightOf="#+id/button_choose_image" />
<ImageView
android:id="#+id/image_view1"
android:layout_width="180dp"
android:layout_height="160dp"
android:layout_above="#id/progress_bar"
android:layout_below="#id/spinner2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="210dp"
android:layout_marginRight="210dp"
android:layout_marginBottom="331dp" />
<ImageView
android:id="#+id/image_view2"
android:layout_width="180dp"
android:layout_height="160dp"
android:layout_above="#id/progress_bar"
android:layout_below="#id/spinner2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="172dp"
android:layout_marginEnd="210dp"
android:layout_marginRight="210dp"
android:layout_marginBottom="168dp" />
<ImageView
android:id="#+id/image_view3"
android:layout_width="180dp"
android:layout_height="160dp"
android:layout_above="#id/progress_bar"
android:layout_below="#id/spinner2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="335dp"
android:layout_marginEnd="210dp"
android:layout_marginRight="210dp"
android:layout_marginBottom="5dp" />
<ImageView
android:id="#+id/image_view4"
android:layout_width="180dp"
android:layout_height="160dp"
android:layout_above="#id/progress_bar"
android:layout_below="#id/spinner2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="12dp"
android:layout_marginEnd="-2dp"
android:layout_marginRight="-2dp"
android:layout_marginBottom="331dp" />
<ImageView
android:id="#+id/image_view5"
android:layout_width="180dp"
android:layout_height="160dp"
android:layout_above="#id/progress_bar"
android:layout_below="#id/spinner2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="172dp"
android:layout_marginEnd="-2dp"
android:layout_marginRight="-2dp"
android:layout_marginBottom="168dp" />
<ImageView
android:id="#+id/image_view6"
android:layout_width="180dp"
android:layout_height="160dp"
android:layout_above="#id/progress_bar"
android:layout_below="#id/spinner2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="335dp"
android:layout_marginEnd="-2dp"
android:layout_marginRight="-2dp"
android:layout_marginBottom="5dp" />
<ProgressBar
android:id="#+id/progress_bar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button_upload"
android:layout_marginBottom="16dp" />
<Button
android:id="#+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Upload" />
</RelativeLayout>
Second_Activity3.java:
package com.example.project1;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.util.List;
public class Second_Activity3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Button mButtonChooseImage;
List <String> list_of_products;
Spinner spino;
ImageView mImageView1;
ImageView mImageView2;
ImageView mImageView3;
ImageView mImageView4;
ImageView mImageView5;
ImageView mImageView6;
ProgressBar mProgressBar;
Uri mImageUri;
Button mButtonUpload;
StorageReference mStorageRef;
DatabaseReference mDatabaseRef;
private static final String TAG = "MainActivity";
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_3);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mImageView1 = findViewById(R.id.image_view1);
mImageView2 = findViewById(R.id.image_view2);
mImageView3 = findViewById(R.id.image_view3);
mImageView4 = findViewById(R.id.image_view4);
mImageView5 = findViewById(R.id.image_view5);
mImageView6 = findViewById(R.id.image_view6);
mButtonUpload = findViewById(R.id.button_upload);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("products");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("products");
} // Performing action when ItemSelected // from spinner, Overriding onItemSelected method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // On selecting a spinner item
String item = parent.getItemAtPosition(position).toString(); // Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Uri> uris = null;
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null) {
ClipData clipdata = data.getClipData();
for (int i=0; i<clipdata.getItemCount();i++)
{
uris.add(clipdata.getItemAt(i).getUri());
}
// mImageUri = data.getData();
Picasso.with(this).load(uris.get(0)).into(mImageView1);
Picasso.with(this).load(uris.get(1)).into(mImageView2);
Picasso.with(this).load(uris.get(2)).into(mImageView3);
Picasso.with(this).load(uris.get(3)).into(mImageView4);
Picasso.with(this).load(uris.get(4)).into(mImageView5);
Picasso.with(this).load(uris.get(5)).into(mImageView6);
}
}
}
Currently, the above code is able to select multiple images since I used intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); line in android code. Here, only six images need to select.
How could I select and display multiple images?
I am very thankful to you that you suggested me to get multiple Uri of selected images.
The uris object was not created it was just declared in the above code as:
uris = new ArrayList<Uri>();
I didn't understand what was the exact problem but the following code able to fulfil my requirement:
package com.example.project1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class Second_Activity3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
Button mButtonChooseImage;
List <String> list_of_products;
Spinner spino;
ImageView mImageView1;
ImageView mImageView2;
ImageView mImageView3;
ImageView mImageView4;
ImageView mImageView5;
ImageView mImageView6;
ProgressBar mProgressBar;
Uri mImageUri;
List<Uri> uris = null;
Button mButtonUpload;
StorageReference mStorageRef;
DatabaseReference mDatabaseRef;
private static final String TAG = "MainActivity";
private static final int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_3);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
mButtonChooseImage = findViewById(R.id.button_choose_image);
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
uris = new ArrayList<Uri>();
mImageView1 = findViewById(R.id.image_view1);
mImageView2 = findViewById(R.id.image_view2);
mImageView3 = findViewById(R.id.image_view3);
mImageView4 = findViewById(R.id.image_view4);
mImageView5 = findViewById(R.id.image_view5);
mImageView6 = findViewById(R.id.image_view6);
mButtonUpload = findViewById(R.id.button_upload);
mProgressBar = findViewById(R.id.progress_bar);
mStorageRef = FirebaseStorage.getInstance().getReference("products");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("products");
} // Performing action when ItemSelected // from spinner, Overriding onItemSelected method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // On selecting a spinner item
String item = parent.getItemAtPosition(position).toString(); // Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
// #RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if (data.getClipData() != null) {
ClipData clipdata = data.getClipData();
for (int i=0; i<clipdata.getItemCount();i++)
{
uris.add(clipdata.getItemAt(i).getUri());
System.out.println("URL: "+clipdata.getItemAt(i).getUri());
}
// mImageUri = data.getData();
Picasso.with(this).load(uris.get(0)).into(mImageView1);
Picasso.with(this).load(uris.get(1)).into(mImageView2);
Picasso.with(this).load(uris.get(2)).into(mImageView3);
Picasso.with(this).load(uris.get(3)).into(mImageView4);
Picasso.with(this).load(uris.get(4)).into(mImageView5);
Picasso.with(this).load(uris.get(5)).into(mImageView6);
// }
}
}
I am new to android programming and have ran into a problem. I am trying to create a voting app where when a user opens up the application and the MainActivity is shown, from here they press a button to go into the second Screen (Screen2) which shows images of people and their names as buttons. When a persons name (in a button on Screen2) is pressed , a text field shows the number of times the button is pressed in an another activity (Screen4) . The problem here is that when i try to show this (Screen4), the app crashes. I am quite new to this so if you didn't understand my issue or need more information please let me know. Any help is appreciated. Thank you.
EDIT : After some help I used Intent to try send the data across but now when when the button in screen2 is pressed the app refreshes and then takes me back to the mainActivity and when this process is tried again the app crashes.
This is the new Screen2 :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Screen2 extends AppCompatActivity {
TextView showValue;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen2);
showValue = findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the On click for the Textview in a different activity.
}
public void AnCount(View v) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
public void ButtonToGoToTheOtherActivity(View v) {
Intent intent = new Intent(this, Screen4.class);
intent.putExtra("valueOfCounter", counter); //the code for sending data to the other activity.
startActivity(intent);
}
}
This is the XML for screen 2 :
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Screen2">
<Button
android:id="#+id/AnnieBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:text="#string/annie_liou"
android:onClick="AnCount"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView5"
/>
This is my Screen4:
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Screen4 extends AppCompatActivity {
private Button Button3;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen4);
Button3 = (Button) findViewById(R.id.Button3);
Button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) { openActivity4();
}
}
);
counter = getIntent().getIntExtra("valueOfCounter", 0); // 0 is default value
}
public void openActivity4() {
Intent intent = new Intent(Screen4.this, MainActivity.class);
startActivity(intent);
}
}
Here is the XML for screen4:
<?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:id="#+id/MainScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Screen4">
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="193dp"
android:layout_marginLeft="193dp"
android:layout_marginEnd="109dp"
android:layout_marginRight="109dp"
android:layout_marginBottom="660dp"
android:text="This is 4th screen"
android:textSize="32sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.664"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/Button3" // return to main screen
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="532dp"
android:text="Return"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
<TextView
android:id="#+id/VoteCountAnnie" // textview where i want the increment to show
android:layout_width="121dp"
android:gravity="center"
android:layout_height="52dp"
android:layout_marginStart="116dp"
android:layout_marginLeft="116dp"
android:layout_marginTop="82dp"
android:layout_marginEnd="174dp"
android:layout_marginRight="174dp"
android:text="0"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my main Activity Screen (not used for the clicking but if there is something wrong in this that could affect the other Screens please let me know) :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button button;
private Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openActivity3();
}
}
);
}
public void openActivity2() {
Intent intent = new Intent(this, Screen2.class);
startActivity(intent);
}
public void openActivity3() {
Intent intent = new Intent(this, Screen3.class);
startActivity(intent);
}
}
Here is the XML for screen 4:
This works same using intent .
Main Class :
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
count = savedInstanceState.getInt(EXTRA_VOTE_KEY);
}
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
/* Intent intent = new Intent(this,DisplayCount.class);
//intent.putExtras(intent);
startActivity(intent,bundle);*/
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
public void go(){
Intent intent = new Intent(this,DisplayCount.class);
intent.putExtra(EXTRA_VOTE_KEY,count);
startActivity(intent);
}
}
Activity of Main Class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout
Display Class :
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView;
private int count;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
Intent intent = getIntent();
count = intent.getIntExtra(MainActivity.EXTRA_VOTE_KEY,0);
textView.setText(Integer.toString(count));
}
}
Activity of display class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
Manifest :
include following in your manifest file :
<activity android: name =".DisplayCount"></activity>
add following to manifest :
// Main Activity //
- List item
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
}
public void go(){
DisplayCount.setVoteCount(count);
Intent intent = new Intent(this, DisplayCount.class);
startActivity(intent);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
}
/** Class to display: **/
- List item
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView ;
private static int count ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
textView.setText(Integer.toString(count));`enter code here`
}
public static void setVoteCount(int c){
count = c;
}
}
/***** Activity files *****/
- List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
/**** Activity That display's ****/
-List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout>
As Mike M. said you are using id of a textview which is in a different activity. In android we cannot access ids of views in a different activity. We can only access ids of view in the same activity in which we are.
So that is for the error you are getting.
For accessing Data from another activity you can pass the data like this:
public class Screen2 extends AppCompatActivity {
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen1);
showValue = (TextView) findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the Id for the Textview in a different activity.
}
public void AnnieCountInc (View view) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
//make another button with a method like
public void ButtonToGoToTheOtherActivity(View view){
Intent intent =new Intent(this,Screen4.class);
intent.putExtra("valueOfCounter",counter); //the code for sending data to the other activity.
startActivity(intent);
}
Then in your Screen4 activity you can get the value of "counter" in the onCreate method by:
counter = getIntent().getIntExtra("valueOfCounter",0); // 0 is default value
This is one method.
You can also use a static variable to pass on data easily by defining your counter varaible as
public static int counter;
Then you can access it directly and it will show you the value.
I'm using a SlidingSplashScreen library by #Chabbal to slide between images and to show small dots below the images to keep track of the image I am showing. And using a fullScreenActivity to show the image in full screen. I want to show the pressed image in full screen but what happens that the fullScreenActivity starts from the first image not the one i pressed on it. here is my code the
MainActivity.java
package com.hodhod.testproject;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.chabbal.slidingdotsplash.OnItemClickListener;
import com.chabbal.slidingdotsplash.SlidingSplashView;
public class MainActivity extends AppCompatActivity {
private int[] images = {
R.drawable.heart,
R.drawable.pexels,
R.drawable.download
};
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SlidingSplashView slidingSplashView = findViewById(R.id.sliding_splash_view);
slidingSplashView.setImageResources(images);
slidingSplashView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onPagerItemClick(View view, int position) {
Intent myIntent = new Intent(MainActivity.this, FullScreenActivity.class);
myIntent.putExtra("imagesId", images);
myIntent.putExtra("position", position);
startActivity(myIntent);
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<com.chabbal.slidingdotsplash.SlidingSplashView
android:id="#+id/sliding_splash_view"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentTop="true">
</com.chabbal.slidingdotsplash.SlidingSplashView>
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="150dp"
/>
</RelativeLayout>
FullScreenActivity.java
package com.hodhod.testproject;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.chabbal.slidingdotsplash.SlidingSplashView;
public class FullScreenActivity extends AppCompatActivity {
int[] imageId;
int position1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullscreen);
final SlidingSplashView slidingSplashViewFull = findViewById(R.id.sliding_splash_view_full);
Intent myIntent = getIntent();
Bundle bundle = myIntent.getExtras();
if(bundle != null){
imageId = bundle.getIntArray("imagesId");
position1 = bundle.getInt("position");
if(position1 == 0){
Toast.makeText(getApplicationContext(), "image1", Toast.LENGTH_SHORT).show();
}
if(position1 == 1){
Toast.makeText(getApplicationContext(), "image2", Toast.LENGTH_SHORT).show();
}
if(position1 == 2){
Toast.makeText(getApplicationContext(), "image3", Toast.LENGTH_SHORT).show();
}
slidingSplashViewFull.setImageResources(imageId);
}
}
}
fullscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.chabbal.slidingdotsplash.SlidingSplashView
android:id="#+id/sliding_splash_view_full"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.chabbal.slidingdotsplash.SlidingSplashView>
</LinearLayout>
I'm new at coding so I might be not very good at explaining. I'm trying to build chat app with Firebase.
Here is my code for Main activity:
Mpackage com.example.otto.myfirstapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.text.format.DateFormat;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private static int SIGN_IN_REQUEST_CODE = 1;
private FirebaseListAdapter<ChatClass> adapter;
RelativeLayout activity_main;
FloatingActionButton fab;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menu_sign_out)
{
AuthUI.getInstance().signOut(this).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Snackbar.make(activity_main,"You have been signed out.", Snackbar.LENGTH_SHORT).show();
finish();
}
});
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == SIGN_IN_REQUEST_CODE)
{
if(resultCode == RESULT_OK)
{
Snackbar.make(activity_main,"Successfully sighned in.Welcome!", Snackbar.LENGTH_SHORT).show();
displayChatMessage();
}
else{
Snackbar.make(activity_main,"Error 1", Snackbar.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText input = (EditText)findViewById(R.id.input);
FirebaseDatabase.getInstance().getReference().push().setValue(new ChatClass(input.getText().toString(),FirebaseAuth.getInstance().getCurrentUser().getEmail()));
input.setText("");
}
});
if(FirebaseAuth.getInstance().getCurrentUser() == null)
{
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(),SIGN_IN_REQUEST_CODE);
}
else
{
Snackbar.make(activity_main,"Welcome " +FirebaseAuth.getInstance().getCurrentUser().getEmail(),Snackbar.LENGTH_SHORT).show();
}
displayChatMessage();
}
private void displayChatMessage() {
ListView listOfMessage = (ListView)findViewById(R.id.list_of_message);
adapter = new FirebaseListAdapter<ChatClass>(this,ChatClass.class,R.layout.list_item,FirebaseDatabase.getInstance().getReference()) {
#Override
protected void populateView(View v, ChatClass model, int position) {
TextView messageText,messageUser,messageTime;
messageText = (TextView)findViewById(R.id.message_text);
messageUser = (TextView)findViewById(R.id.message_user);
messageTime = (TextView)findViewById(R.id.message_time);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
messageTime.setText(DateFormat.format("dd-mm-yy (HH:mm:ss)",model.getMessageTime()));
}
};
listOfMessage.setAdapter(adapter);
}
}
And code for acitivty_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/c_send"
android:id="#+id/fab"
android:tint="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
app:fabSize="mini"
/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message..."
android:id="#+id/input"
/>
</android.support.design.widget.TextInputLayout>
<ListView
android:id="#+id/list_of_message"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/fab"
android:dividerHeight="16dp"
android:divider="#android:color/transparent"
android:layout_marginBottom="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
Error code from the logcat while app says that it keeps stopping tells me that problem is in the snackbar:
Caused by: java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
at android.support.design.widget.Snackbar.make(Snackbar.java:181)
at com.example.otto.myfirstapplication.MainActivity.onCreate(MainActivity.java:97)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
I updated all dependencies to the latest versions. I was thinking maybe I have to downgrade to solve a problem but I'm not sure.
Anyway I'm super stuck and hope you can help me. Thanks in advance.
Change at all places,
Snackbar.make(activity_main,...
to
Snackbar.make(findViewById(android.R.id.content),...
Cause
You did not initialize activity_main. So it is null when you use it. findViewById(android.R.id.content) gives you root view of current Activity.
First of All you have to create coordinator layout to appear your snackbar. so change your main relativelayout to coordinator layout .
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
//YOUR CURRENT CODE
</android.support.design.widget.CoordinatorLayout>
after that in your activity .
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
and make your Snackbar layout like this
Snackbar snackbar = Snackbar.make(coordinatorLayout, "Welcome to AndroidHive", Snackbar.LENGTH_LONG);
snackbar.show();
As in your code,
RelativeLayout activity_main;
you haven't initialized the activity_main, use findviewbyid in onCreate of activity
In xml change the below code, add the id in xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/container"
tools:context=".MainActivity">
and in the code fetch the id in onCreate method of Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main=findViewById(R.id.container);
}
and now use this view(activity_main) in snack bar.
I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.