Can anyone please help me out here???
Problem statement: I am making a chat application that is almost ready in ChatActivity. Functionality is the user can send images and text together but while sending text it's fine. The problem starts when I am sending images. And after sending when I scroll up to my all the texts start to change into the recently sent image.
ChatActivity.xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/bg_light"
tools:context=".ChatActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/backArrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_back_arrow"
app:tint="#color/white" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_image"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginStart="5dp"
android:padding="5dp"
android:src="#drawable/avatar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/backArrow"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/userName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="13dp"
android:fontFamily="#font/roboto"
android:text=""
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageView7"
app:layout_constraintStart_toEndOf="#+id/profile_image"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/lastSeen"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="2dp"
android:fontFamily="#font/roboto_light"
android:text=""
android:textColor="#color/white"
android:textSize="12sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageView7"
app:layout_constraintStart_toEndOf="#+id/profile_image"
app:layout_constraintTop_toBottomOf="#+id/userName" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="-22dp" />
<androidx.constraintlayout.widget.Barrier
android:id="#+id/barrier2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="left"
tools:layout_editor_absoluteX="395dp" />
<ImageView
android:id="#+id/imageView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_more"
app:tint="#color/white" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/chatRecyclerView"
android:layout_width="match_parent"
android:layout_height="611dp"
android:nestedScrollingEnabled="false">
</androidx.recyclerview.widget.RecyclerView>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="4dp">
<View
android:id="#+id/view14"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:background="#drawable/follow_active_btn"
app:layout_constraintBottom_toBottomOf="#+id/etMessage"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/etMessage" />
<EditText
android:id="#+id/etMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginBottom="4dp"
android:background="#color/transparent"
android:ems="10"
android:hint="Message"
android:inputType="textMultiLine"
android:maxLines="4"
android:minHeight="48dp"
android:paddingStart="4dp"
android:paddingLeft="4dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/sendMessageImage"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/sendMessage"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_marginEnd="8dp"
android:padding="4dp"
app:layout_constraintBottom_toBottomOf="#+id/etMessage"
app:layout_constraintEnd_toEndOf="#+id/view14"
app:layout_constraintTop_toTopOf="#+id/etMessage"
app:srcCompat="#drawable/comment"
app:tint="#color/purple_500" />
<ImageView
android:id="#+id/sendMessageImage"
android:layout_width="36dp"
android:layout_height="36dp"
android:padding="4dp"
app:layout_constraintBottom_toBottomOf="#+id/sendMessage"
app:layout_constraintEnd_toStartOf="#+id/sendMessage"
app:layout_constraintTop_toTopOf="#+id/sendMessage"
app:srcCompat="#drawable/clip"
app:tint="#color/black" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
ChatAdapter.java -
package com.codinggeekers.lmsbeta.Adapter;
import android.content.Context;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.codinggeekers.lmsbeta.Models.MessageModel;
import com.codinggeekers.lmsbeta.R;
import com.google.firebase.auth.FirebaseAuth;
import com.squareup.picasso.Picasso;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class ChatAdapter extends RecyclerView.Adapter {
ArrayList<MessageModel> list;
Context context;
int SENDER_VIEW_TYPE = 1;
int RECEIVER_VIEW_TYPE = 2;
public ChatAdapter(ArrayList<MessageModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == SENDER_VIEW_TYPE) {
View view = LayoutInflater.from(context).inflate(R.layout.sample_sender, parent, false);
return new SenderViewHolder(view);
}
else {
View view = LayoutInflater.from(context).inflate(R.layout.sample_receiver, parent, false);
return new ReceiverViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
MessageModel message = list.get(position);
Timestamp ts = new Timestamp(message.getTimestamp());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
String time = simpleDateFormat.format(ts.getTime());
RequestOptions requestOptions = new RequestOptions();
requestOptions = requestOptions.transforms(new CenterCrop(), new RoundedCorners(10));
if(holder.getClass() == SenderViewHolder.class) {
if (message.getMsgImg()!=null) {
((SenderViewHolder)holder).senderImageLayout.setVisibility(View.VISIBLE);
((SenderViewHolder)holder).senderTextLayout.setVisibility(View.GONE);
// Picasso.get().load(message.getMsgImg()).placeholder(R.drawable.placeholder).into(((SenderViewHolder)holder).senderImage);
Glide.with(((SenderViewHolder)holder).itemView.getContext()).load(message.getMsgImg()).apply(requestOptions)
.placeholder(R.drawable.placeholder).into(((SenderViewHolder)holder).senderImage);
} else {
((SenderViewHolder)holder).senderMsg.setText(message.getMessage());
((SenderViewHolder)holder).senderTime.setText(time);
}
}
else {
if (message.getMsgImg()!=null) {
((ReceiverViewHolder)holder).receiverImageLayout.setVisibility(View.VISIBLE);
// Picasso.get().load(message.getMsgImg()).placeholder(R.drawable.placeholder).into(((ReceiverViewHolder)holder).receiverImage);
Glide.with(((ReceiverViewHolder)holder).itemView.getContext()).load(message.getMsgImg()).apply(requestOptions)
.placeholder(R.drawable.placeholder).into(((ReceiverViewHolder)holder).receiverImage);
} else {
((ReceiverViewHolder)holder).receiverMsg.setText(message.getMessage());
((ReceiverViewHolder)holder).receiverTime.setText(time);
}
}
}
#Override
public int getItemViewType(int position) {
if(list.get(position).getuId().equals(FirebaseAuth.getInstance().getUid())) {
return SENDER_VIEW_TYPE;
}
else {
return RECEIVER_VIEW_TYPE;
}
}
#Override
public int getItemCount() {
return list.size();
}
public class ReceiverViewHolder extends RecyclerView.ViewHolder {
TextView receiverMsg, receiverTime;
ImageView receiverImage;
ConstraintLayout receiverImageLayout;
public ReceiverViewHolder(#NonNull View itemView) {
super(itemView);
receiverMsg = itemView.findViewById(R.id.receiverText);
receiverTime = itemView.findViewById(R.id.receiverTime);
receiverImage = itemView.findViewById(R.id.receiverImage);
receiverImageLayout = itemView.findViewById(R.id.imageConstraintLayoutReceiver);
}
}
public class SenderViewHolder extends RecyclerView.ViewHolder {
TextView senderMsg, senderTime;
ImageView senderImage;
ConstraintLayout senderImageLayout;
ConstraintLayout senderTextLayout;
public SenderViewHolder(#NonNull View itemView) {
super(itemView);
senderMsg = itemView.findViewById(R.id.senderText);
senderTime = itemView.findViewById(R.id.senderTime);
senderImage = itemView.findViewById(R.id.senderImage);
senderImageLayout = itemView.findViewById(R.id.imageConstraintLayoutSender);
senderTextLayout = itemView.findViewById(R.id.textConstraintLayoutSender);
}
}
}
ChatActivity.java -
package com.codinggeekers.lmsbeta;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import com.codinggeekers.lmsbeta.Adapter.ChatAdapter;
import com.codinggeekers.lmsbeta.Models.MessageModel;
import com.codinggeekers.lmsbeta.databinding.ActivityChatBinding;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.Date;
public class ChatActivity extends AppCompatActivity {
ActivityChatBinding binding;
ProgressDialog dialog;
FirebaseAuth auth;
FirebaseDatabase database;
FirebaseStorage storage;
ActivityResultLauncher<String> galleryLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityChatBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
storage = FirebaseStorage.getInstance();
dialog = new ProgressDialog(this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setTitle("Sending Image...");
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
// Sender and Receiver Ids
final String senderId = auth.getUid();
String receiveId = getIntent().getStringExtra("userId");
String userName = getIntent().getStringExtra("userName");
String profilePic = getIntent().getStringExtra("profilePic");
binding.userName.setText(userName);
Picasso.get().load(profilePic).placeholder(R.drawable.avatar).into(binding.profileImage);
binding.backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatActivity.this, UsersChatActivity.class);
startActivity(intent);
}
});
final ArrayList<MessageModel> messageModels = new ArrayList<MessageModel>();
final ChatAdapter chatAdapter = new ChatAdapter(messageModels, this);
binding.chatRecyclerView.setAdapter(chatAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
binding.chatRecyclerView.setHasFixedSize(true);
binding.chatRecyclerView.setLayoutManager(layoutManager);
final String senderRoom = senderId + receiveId;
final String receiverRoom = receiveId + senderId;
database.getReference().child("Chats")
.child(senderRoom)
.addValueEventListener(new ValueEventListener() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
messageModels.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
MessageModel model = snapshot1.getValue(MessageModel.class);
messageModels.add(model);
}
chatAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
binding.sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = binding.etMessage.getText().toString();
if (message.matches("")) {
} else {
final MessageModel model = new MessageModel(senderId, message, "text");
model.setTimestamp(new Date().getTime());
binding.etMessage.setText("");
database.getReference().child("Chats")
.child(senderRoom)
.push()
.setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(#NonNull Void unused) {
database.getReference().child("Chats").child(receiverRoom).push().setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(#NonNull Void unused) {
}
});
}
});
}
}
});
binding.sendMessageImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryLauncher.launch("image/*");
}
});
galleryLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
dialog.show();
final StorageReference reference = storage.getReference().child("chats")
.child(senderRoom).child(new Date().getTime() + "");
reference.putFile(result).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
final MessageModel model = new MessageModel(senderId, new Date().getTime(), uri.toString(), "image");
database.getReference()
.child("Chats")
.child(senderRoom)
.push()
.setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
database.getReference().child("Chats").child(receiverRoom).push().setValue(model).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
dialog.dismiss();
binding.sendMessageImage.setImageURI(Uri.EMPTY);
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
});
}
});
}
});
}
});
binding.userName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatActivity.this, FriendsProfileActivity.class);
intent.putExtra("userName", userName);
intent.putExtra("userId", receiveId);
intent.putExtra("profilePic", profilePic);
startActivity(intent);
}
});
}
}
ItemViewType should start at 0.
Try to change them to this:
int SENDER_VIEW_TYPE = 0;
int RECEIVER_VIEW_TYPE = 1;
Related
I am trying to develop an application in android with the help of Geeks for Geeks tutorials. I am still learning how to develop android apps. It is a simple weather app where I need to display forecast in recycler view with the help of card view. The code is as shown from the video, but still the recycler view is not getting displayed. API url is also working. There is no error shown.
App Permissions - Location and Internet (Added in Manifest)
It was a request to please help me out with this issue.
Please do reply.
Main_Activity.java file is just a splash screen.
Main_Activity2.java
package com.androidp.wheatherapp;
import androidx.annotation.NonNull;
import androidx.appcompat.
app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.VoiceInteractor;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private RelativeLayout rlayout;
private ProgressBar pbar;
private TextView cityNameiv;
private TextView temp;
private TextView condi;
private EditText editCity;
private ImageView IVsearch,ivicon,backIV;
private RecyclerView recyclerWeather;
private ArrayList<WeatherModal> weatherModalArrayList;
private weatherAdapter adapter;
private String cityName;
private LocationManager locationManager;
private int PERMISSION_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
rlayout = findViewById(R.id.rlayout);
pbar = findViewById(R.id.pbar);
cityNameiv = findViewById(R.id.cityName);
temp = findViewById(R.id.temp);
condi = findViewById(R.id.condi);
editCity = findViewById(R.id.editCity);
ivicon = findViewById(R.id.ivicon);
IVsearch = findViewById(R.id.IVsearch);
recyclerWeather = findViewById(R.id.recyclerWeather);
backIV = findViewById(R.id.backIV);
weatherModalArrayList = new ArrayList<>();
adapter = new weatherAdapter(this,weatherModalArrayList);
recyclerWeather.setAdapter(adapter);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity2.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},PERMISSION_CODE);
}
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
cityName = getCityName(location.getLongitude(), location.getLatitude());
getweatherInfo(cityName);
IVsearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city = editCity.getText().toString();
if(city.isEmpty()){
Toast.makeText(MainActivity2.this,"Please Enter City Name",Toast.LENGTH_SHORT).show();
}
else {
cityNameiv.setText(cityName);
getweatherInfo(city);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == PERMISSION_CODE){
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this,"Allow Permissions",Toast.LENGTH_SHORT).show();
finish();
}
}
}
private String getCityName(double longitude, double latitude){
String cityName = "Not Found";
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(latitude,longitude,10);
for (Address adr : addresses){
if(adr!= null){
String city = adr.getLocality();
if(city!= null && !city.equals("")){
cityName = city;
}
else {
Log.d("TAG","User City not found");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
private void getweatherInfo(String cityName){
String url="https://api.weatherapi.com/v1/forecast.json?key=deadad1688ef46f8929170126213010&q="+ cityName+"&days=1&aqi=no&alerts=no";
//cityNameiv.setText(cityName);
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity2.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pbar.setVisibility(View.GONE);
rlayout.setVisibility(View.VISIBLE);
//weatherModalArrayList.clear();
try {
String temperature = response.getJSONObject("current").getString("temp_c");
temp.setText(temperature + " °c");
int isDay = response.getJSONObject("current").getInt("is_day");
String condition = response.getJSONObject("current").getJSONObject("condition").getString("text");
String condiicon = response.getJSONObject("current").getJSONObject("condition").getString("icon");
Picasso.get().load("https:".concat(condiicon)).into(ivicon);
condi.setText(condition);
if(isDay==1){
Picasso.get().load("https://wallpaperaccess.com/full/929229.jpg").into(backIV);
}
else {
Picasso.get().load("https://wallpaperaccess.com/full/929229.jpg").into(backIV);
}
JSONObject forecastObj = response.getJSONObject("forecast");
JSONObject forecast0 = forecastObj.getJSONArray("forecastday").getJSONObject(0);
JSONArray hourarray = forecast0.getJSONArray("hour");
for(int i=0; i < hourarray.length();i++){
JSONObject hourobj = hourarray.getJSONObject(i);
String time = hourobj.getString("time");
String temp1 = hourobj.getString("temp_c");
String img = hourobj.getJSONObject("time").getString("icon");
String wind = hourobj.getString("wind_kph");
weatherModalArrayList.add(new WeatherModal(time,temp1,img,wind));
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity2.this,"Please enter valid city Name",Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest);
}
}
activity_main2.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=".MainActivity2">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pbar"
android:layout_centerInParent="true"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rlayout"
android:visibility="visible"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:id="#+id/backIV"
android:src="#color/black"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:gravity="center"
android:textColor="#color/white"
android:padding="20sp"
android:layout_marginTop="30dp"
android:textSize="18sp"
android:id="#+id/cityName"
android:text="City Name"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/idlin"
android:layout_below="#+id/cityName"
android:weightSum="5">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/editCity"
android:layout_margin="10sp"
android:layout_weight="4.5"
android:background="#color/white"
android:hint="Enter City"
android:padding="10dp"
app:hintTextColor="#color/purple_200"
/>
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:layout_margin="10dp"
android:tint="#color/white"
android:layout_gravity="center"
android:id="#+id/IVsearch"
android:src="#drawable/search"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/temp"
android:layout_margin="10dp"
android:gravity="center_horizontal"
android:padding="5dp"
android:textSize="70dp"
android:text="23"
android:textColor="#color/white"
android:layout_below="#id/idlin"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivicon"
android:layout_below="#id/temp"
android:src="#mipmap/ic_launcher"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/condi"
android:layout_margin="10dp"
android:gravity="center"
android:text="Condition"
android:textColor="#color/white"
android:textAlignment="center"
android:layout_below="#id/ivicon"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginBottom="10dp"
android:text="Today's Wheather Forecast"
android:layout_above="#id/recyclerWeather"
android:textColor="#color/white"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerWeather"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</RelativeLayout>
</RelativeLayout>
weatherAdapter.java
package com.androidp.wheatherapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class weatherAdapter extends RecyclerView.Adapter<weatherAdapter.ViewHolder> {
private Context context;
private ArrayList<WeatherModal> weatherModalArrayList;
public weatherAdapter(Context context, ArrayList<WeatherModal> weatherModalArrayList) {
this.context = context;
this.weatherModalArrayList = weatherModalArrayList;
}
#NonNull
#Override
public weatherAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.weather_rv,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull weatherAdapter.ViewHolder holder, int position) {
WeatherModal modal = weatherModalArrayList.get(position);
holder.idTemperature.setText(modal.getTemperature() + "°c");
Picasso.get().load("https:".concat(modal.getIcon())).into(holder.idCondition);
holder.wind.setText(modal.getWindSpeed()+"km/hr");
SimpleDateFormat input = new SimpleDateFormat("yyyy-mm-dd hh:mm");
SimpleDateFormat output = new SimpleDateFormat("hh:min aa");
try {
Date t = input.parse(modal.getTime());
holder.idTime.setText(output.format(t));
}catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return weatherModalArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView idTemperature, idTime, wind;
private ImageView idCondition;
public ViewHolder(#NonNull View itemView) {
super(itemView);
idCondition = itemView.findViewById(R.id.idCondition);
idTemperature = itemView.findViewById(R.id.idTemperature);
wind = itemView.findViewById(R.id.idTextview);
idTime = itemView.findViewById(R.id.idTime);
}
}
}
WeatherModal.java
package com.androidp.wheatherapp;
public class WeatherModal {
private String Time;
private String Temperature;
private String icon;
private String windSpeed;
public WeatherModal(String time, String temperature, String icon, String windSpeed) {
Time = time;
Temperature = temperature;
this.icon = icon;
this.windSpeed = windSpeed;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getTemperature() {
return Temperature;
}
public void setTemperature(String temperature) {
Temperature = temperature;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getWindSpeed() {
return windSpeed;
}
public void setWindSpeed(String windSpeed) {
this.windSpeed = windSpeed;
}
}
weather_rv.xml - Card View
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_gravity="center"
app:cardElevation="6dp"
app:cardCornerRadius="10dp"
android:layout_margin="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/card_bag"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idTime"
android:gravity="center"
android:padding="4dp"
android:text="TIME"
android:textColor="#color/black"
android:textAlignment="center"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/idTemperature"
android:gravity="center"
android:textSize="20sp"
android:text="20"
android:textAlignment="center"
android:layout_below="#+id/idTime"
android:textColor="#color/white"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#+id/idTemperature"
android:id="#+id/idCondition"
android:layout_centerHorizontal="true"
android:layout_margin="5dp"
android:padding="4dp"
android:src="#drawable/ic_launcher_foreground"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:layout_below="#id/idCondition"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/idTextview"
android:textColor="#color/white"
android:padding="3dp"
android:layout_margin="4dp"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
ScreenShot Of App
The recycler view is to be displayed below Today's Weather Forecast
I have checked several times the name of my layout RecyclerView as I show on other StackOverflow questions but it is correct. The error of the logcat is this:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.selfcial/com.example.selfcial.Models.MessageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.LinearLayoutManager.setStackFromEnd(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3457)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.LinearLayoutManager.setStackFromEnd(boolean)' on a null object reference
at com.example.selfcial.Models.MessageActivity.onCreate(MessageActivity.java:69)
at android.app.Activity.performCreate(Activity.java:7893)
at android.app.Activity.performCreate(Activity.java:7880)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3283)
This is my my MessageActivity:
package com.example.selfcial.Models;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.selfcial.Adapters.MessageAdapter;
import com.example.selfcial.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MessageActivity extends AppCompatActivity {
TextView username;
ImageView profile;
RecyclerView recyclerViewy;
EditText sendMsg;
ImageButton sendBtn;
FirebaseUser firebaseUser;
DatabaseReference reference;
Intent intent;
MessageAdapter messageAdapter;
List<Chat> chats;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
profile = findViewById(R.id.imageview_profile);
username = findViewById(R.id.usernameLogin);
sendMsg = findViewById(R.id.writeMsg);
sendBtn = findViewById(R.id.sendBtn);
//RecyclerViewChat
recyclerView.findViewById(R.id.recycler_view_chat);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
intent = getIntent();
String id = intent.getStringExtra("id");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users").child(id);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Convert edittext to string
String msg = sendMsg.getText().toString();
//Send message
if (!msg.equals("")) {
sendMessage(firebaseUser.getUid(), id, msg);
} else {
Toast.makeText(MessageActivity.this, "It's an empty message", Toast.LENGTH_SHORT).show();
}
sendMsg.setText("");
}
});
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Users user = snapshot.getValue(Users.class);
username.setText(user.getUsername());
if (user.getImageUrl().equals("default")) {
profile.setImageResource(R.drawable.avatar);
} else {
Glide.with(MessageActivity.this)
.load(user.getImageUrl())
.into(profile);
}
readMessages(firebaseUser.getUid(), id, user.getImageUrl());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void sendMessage(String sender, String receiver, String message) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("sender", sender);
hashMap.put("receiver", receiver);
hashMap.put("message", message);
reference.child("chats").push().setValue(hashMap);
}
private void readMessages(String myid, String id, String imgUrl) {
chats = new ArrayList<>();
reference = FirebaseDatabase.getInstance().getReference("chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
chats.clear();
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
Chat chat = snapshot1.getValue(Chat.class);
if (chat.getReceiver().equals(myid) && chat.getSender().equals(id) ||
chat.getReceiver().equals(id) && chat.getSender().equals(myid)) {
chats.add(chat);
}
messageAdapter = new MessageAdapter(MessageActivity.this, chats, imgUrl);
recyclerView.setAdapter(messageAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is the MessageAdapter:
ackage com.example.selfcial.Adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.selfcial.Models.Chat;
import com.example.selfcial.Models.MessageActivity;
import com.example.selfcial.Models.Users;
import com.example.selfcial.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.List;
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
private Context context;
private List<Chat> mChat;
private String imgUrl;
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
//Firebase
FirebaseUser firebaseUser;
//Constructor
public MessageAdapter(Context context, List<Chat> mChat, String imgUrl) {
this.context = context;
this.mChat = mChat;
this.imgUrl = imgUrl;
}
#NonNull
#Override
public MessageAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == MSG_TYPE_RIGHT) {
view = LayoutInflater.from(context).inflate(R.layout.item_sent,
parent,
false);
}else {
view = LayoutInflater.from(context).inflate(R.layout.item_received,
parent,
false);
}
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
holder.show_message.setText(chat.getMessage());
if (imgUrl.equals("default")) {
holder.profile_image.setImageResource(R.drawable.avatar);
}else {
Glide.with(context)
.load(imgUrl)
.into(holder.profile_image);
}
}
#Override
public int getItemCount() {
return mChat.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView show_message;
private ImageView profile_image;
public ViewHolder(#NonNull View itemView) {
super(itemView);
show_message = itemView.findViewById(R.id.message);
profile_image = itemView.findViewById(R.id.profileImgReceive);
}
}
#Override
public int getItemViewType(int position) {
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (mChat.get(position).getSender().equals(firebaseUser.getUid())) {
return MSG_TYPE_RIGHT;
} else {
return MSG_TYPE_LEFT;
}
}
}
And this is the activity_message.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:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Models.MessageActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imageview_profile"
android:layout_width="40dp"
android:layout_height="40dp"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="28dp"
tools:srcCompat="#drawable/avatar" />
<TextView
android:id="#+id/usernameLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:textColor="#color/white"
android:layout_marginLeft="23dp" />
</androidx.appcompat.widget.Toolbar>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_chat"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#F8E1E1"
app:layout_constraintBottom_toTopOf="#+id/cardView5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
<androidx.cardview.widget.CardView
android:id="#+id/cardView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="#+id/sendVoice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_weight="1"
android:background="#android:color/transparent"
android:contentDescription="TODO"
app:srcCompat="#drawable/ic_mic" />
<ImageButton
android:id="#+id/photoBtn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#00FFFFFF"
android:scrollbarThumbHorizontal="#color/black"
android:scrollbarThumbVertical="#color/black"
app:srcCompat="#drawable/ic_baseline_camera_alt_24" />
<ImageButton
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#android:color/transparent"
app:srcCompat="#drawable/ic_gallery" />
<EditText
android:id="#+id/writeMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginBottom="0dp"
android:layout_weight="1"
android:background="#drawable/msg_shape"
android:ems="10"
android:hint="Bb"
android:inputType="textCapSentences"
android:padding="5dp" />
<ImageButton
android:id="#+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#00FFFFFF"
android:scrollbarThumbHorizontal="#color/black"
android:scrollbarThumbVertical="#color/black"
app:srcCompat="#drawable/ic_send" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
Is the error occured by a mistake on the MessageAdapter or is it a bug somewhere else? I also tried to change LinearLayoutManager line to LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); but this didn't work too.
You call findViewById() here:
recyclerView.findViewById(R.id.recycler_view_chat);
But you are calling the findViewById() method on your recyclerView variable, not assigning the result of your Activity's findViewById() to your variable, so your variable is always null.
recyclerView = findViewById(R.id.recycler_view_chat);
I have a screen that shows my movie names and their pictures which are in my Firebase. It shows them with the pictures.
My database's structure is like this. name is the string which is the name of my movie. profilePic is the string that contains the picture link from Firebase storage.
What I want is, when I click on any picture which are listed, I want to display it on another activity with bigger size (like opening someone's WhatsApp or Facebook profile picture)
These are my classes that works perfectly. How can I do this?
Movies.java
package com.example.XXXX;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Movies extends AppCompatActivity {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Profile> list;
MyAdapter adapter;
private String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_films);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
reference = FirebaseDatabase.getInstance().getReference().child("Films");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<Profile>();
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
Profile p = dataSnapshot1.getValue(Profile.class);
list.add(p);
}
adapter = new MyAdapter(Movies.this,list);
recyclerView.setAdapter(adapter);
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Movies.this,"Ooops... Something is wrong.",Toast.LENGTH_SHORT).show();
}
});
Intent intent = getIntent();
message = intent.getStringExtra("EXTRA_MESSAGE");
ImageButton backButton = (ImageButton) findViewById(R.id.imageButton13);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Movies.this, Menu.class);
i.putExtra("EXTRA_MESSAGE",message);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(Movies.this, Menu.class);
i.putExtra("EXTRA_MESSAGE",message);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
}
MyAdapter.java
package com.example.XXXX;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<Profile> profiles;
public MyAdapter(Context c, ArrayList<Profile> p){
context = c;
profiles = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview,viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.name.setText(profiles.get(i).getName());
Picasso.get().load(profiles.get(i).getProfilePic()).into(myViewHolder.profilePic);
}
#Override
public int getItemCount() {
return profiles.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView name;
ImageView profilePic;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.film_name);
profilePic = (ImageView) itemView.findViewById(R.id.filmProfile);
}
}
}
Profile.java
package com.example.XXXX;
public class Profile {
private String name;
private String profilePic;
public Profile() {
}
public Profile(String name, String profilePic) {
this.name = name;
this.profilePic = profilePic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
}
activity_movies.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Movies"
android:background="#drawable/background">
<include
android:id="#+id/toolbar_movies"
layout="#layout/toolbar_movies" />
<RelativeLayout
android:id="#+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="88dp"
android:layout_marginBottom="10dp">
<LinearLayout
android:id="#+id/layoutoffilms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview_films"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
</LinearLayout>
cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/border"
android:layout_marginTop="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/filmProfile"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/film_name"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:layout_gravity="center_vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.08"
android:textSize="20sp"/>
</LinearLayout>
</LinearLayout>
Modify view holder with view as
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView name;
ImageView profilePic;
View mView;
public MyViewHolder(#NonNull View itemView)
{
super(itemView);
mView = itemView;
name = (TextView) itemView.findViewById(R.id.film_name);
profilePic = (ImageView) itemView.findViewById(R.id.filmProfile);
}
}
Implement on click listener of view holder in adapter, then start the activity with image url.
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.name.setText(profiles.get(i).getName());
Picasso.get().load(profiles.get(i).getProfilePic()).into(myViewHolder.profilePic);
mViewHolder.mView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startImageActivity(profiles.get(i).getProfilePic());
}
});
}
3.Create activity and start with image view of required dimension.
void startImageActivity(String imgUrl)
{
Intent intent = new Intent(context,ViewImage.class);
intent.putExtra("profilePic",imgUrl);
context.startActivity(intent);
}
Or to open image in an external application try
void startImageActivity(String imgUrl)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(imgUrl));
context.startActivity(intent);
}
Resize your bitmap:
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
originalBitmap, newWidth, newHeight, false);
You can use this library for the zoom in and zoom out functionality like this is the link Zoom library
You need to add this gradle in your project
implementation 'com.otaliastudios:zoomlayout:1.6.1'
Check this example layout below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dark_grey"
android:orientation="vertical"
android:weightSum="13">
<ImageView
android:id="#+id/iv_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_margin="#dimen/margin_small"
android:padding="#dimen/margin_small"
android:src="#drawable/ic_skip" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="6" />
<com.otaliastudios.zoom.ZoomImageView
android:id="#+id/zoom_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:scrollbars="vertical|horizontal"
app:alignment="center"
app:animationDuration="280"
app:flingEnabled="true"
app:horizontalPanEnabled="true"
app:maxZoom="2.5"
app:maxZoomType="zoom"
app:minZoom="0.7"
app:minZoomType="zoom"
app:overPinchable="true"
app:overScrollHorizontal="true"
app:overScrollVertical="true"
app:transformation="centerInside"
app:transformationGravity="auto"
app:verticalPanEnabled="true"
app:zoomEnabled="true" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5" />
</LinearLayout>
And in the JAVA class you need to load the image like below, I am using the Glide for the image loading like below
GlideApp.with(this)
.asBitmap()
.load(YOUR_IMAGE_URL)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
YOUR_IMAGEVIEW.setImageBitmap(resource);
}
});
Check the ZoomActivity.java for the demo purpose like below
public class ZoomActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_zoom);
// ActivityZoomBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_zoom);
ImageView zoomImage = findViewById(R.id.zoom_image);
///GETTING INTENT DATA
Intent intent = getIntent();
if (intent.hasExtra("ZOOM_IMAGE")) {
String imageUrl = intent.getStringExtra("ZOOM_IMAGE");
GlideApp.with(this)
.asBitmap()
.load(imageUrl)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
zoomImage.setImageBitmap(resource);
}
});
}
}
}
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.
My program is a barcode scanner that takes a value(string) and searches the database for the description of the project.
I cannot connect to the database, I am unable to copy the value that I get in activity_main.xml in the text field in activity_second.xml(where the database search should happen).
Activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:onClick="callZXing"
android:id="#+id/Button" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#ddd" />
<TextView
android:id="#+id/txResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Rezultat:"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Is this the correct code?"
android:id="#+id/textView"
android:layout_marginTop="70dp"
android:layout_gravity="center_horizontal" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="Yes"
android:layout_marginTop="30dp"
android:id="#+id/button2"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="sendSecond" />
<Button
style="#style/CaptureTheme"
android:layout_width="112dp"
android:layout_height="68dp"
android:text="No"
android:layout_marginTop="10dp"
android:id="#+id/button1"
android:layout_weight="0.10"
android:layout_gravity="center_horizontal"
android:onClick="callZXing" />
</LinearLayout>
activity_second.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editTextId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/buttonGet"
android:text="Get"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
SecondActivity.java
package br.exemplozxingintegration;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editTextId = (EditText) findViewById(R.id.editTextId);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editTextId.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nDescriere:\t" +address+ "\nImagine:\t"+ vc);
}
#Override
public void onClick(View v) {
getData();
}
}
// #Override
//protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_second);
// }
//}
MainActivity.java
package br.exemplozxingintegration;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final int REQUEST_CODE = 0;
private TextView txResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txResult = (TextView) findViewById(R.id.txResult);
}
public void sendSecond(View view) {
Intent StartNewActivity = new Intent(this,SecondActivity.class);
startActivity(StartNewActivity);
}
public void callZXing(View view){
Intent it = new Intent(MainActivity.this, com.google.zxing.client.android.CaptureActivity.class);
startActivityForResult(it, REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(REQUEST_CODE == requestCode && RESULT_OK == resultCode){
txResult.setText("REZULTAT: "+data.getStringExtra("SCAN_RESULT")+" ");
}
}
public class FirstActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView = (TextView) findViewById(R.id.txResult);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("textViewText", textView.getText().toString());
startActivity(intent);
}
});
}}
}
Config.java
package br.exemplozxingintegration;
/**
* Created by Boghy on 10.02.2016.
*/
public class Config {
public static final String DATA_URL = "http://192.168.94.1/Android/College/getData.php?id=";
public static final String KEY_NAME = "title";
public static final String KEY_ADDRESS = "desc";
public static final String KEY_VC = "image";
public static final String JSON_ARRAY = "result";
}