I want to get Fragment data in MainActivity calling fragment method - java

I want to show current weather data in fragment on search CityName base. Mean if I entered any city name in searchbox it show me the current weather of that city. All work was performing correctly if I give static City name, but I want that which city I select it give me this current data.
The SearchBox (EditText) is on Main Activity and currentweather data Method where I want to show my currentweather data is in Fragment. How it is possible to search on Main Activity and show currentweather data in fragment layout.
MainActivity
package com.deitel.apiretrofitfragmentweatherapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.deitel.apiretrofitfragmentweatherapp.Adapter.FragementViewAdapter;
import com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
private static FragmentManager fragmentManager;
public static String BaseUrl = "http://api.openweathermap.org/";
public static String AppId = "08fd7374790f2ccee9f1f1dbfae38fdf";
/* public static String lat = "33.69";
public static String lon = "73.06";*/
ViewPager viewPager;
FragementViewAdapter fragementViewAdapter;
TabLayout tabLayout;
EditText text_search;
ImageButton btn_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
text_search = findViewById(R.id.text_search_city);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.fragment_container);
btn_search = findViewById(R.id.btn_search);
final currentweather currentweather = new currentweather();
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager=getSupportFragmentManager();
currentweather weather= (currentweather) manager.findFragmentById(R.id.current_weather);
assert weather != null;
weather.getCurrentData();
String City= text_search.getText().toString().trim();
Bundle bundle = new Bundle();
bundle.putString("search_city", City);
currentweather.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.fragment_container, currentweather).commit();
currentweather.getCurrentData();
if (TextUtils.isEmpty(City)) {
text_search.setError("Enter City Name");
return;
}
}
});
fragementViewAdapter = new FragementViewAdapter(getSupportFragmentManager());
viewPager.setAdapter(fragementViewAdapter);
tabLayout.setupWithViewPager(viewPager);
fragmentManager = getSupportFragmentManager();
}
}
CurrentWeatherFragment
package com.deitel.apiretrofitfragmentweatherapp.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.deitel.apiretrofitfragmentweatherapp.CurrentWeather.WeatherResponse;
import com.deitel.apiretrofitfragmentweatherapp.R;
import com.deitel.apiretrofitfragmentweatherapp.Retrofit.WeatherService;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.AppId;
import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.BaseUrl;
public class currentweather extends Fragment {
public TextView text_country,text_city,text_pressure,text_humidity,text_temp;
public TextView textView_country, textView_city, textView_temp,
textView_pressure, textView_humidity, textview_date;
/*public TextView text_view;*/
public currentweather() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View itemview=inflater.inflate(R.layout.fragment_currentweather, container, false);
textView_country = itemview.findViewById(R.id.textView_country);
textView_city =itemview.findViewById(R.id.textView_city);
textView_temp =itemview.findViewById(R.id.textview_temp);
textView_pressure =itemview.findViewById(R.id.textView_pressure);
textView_humidity =itemview.findViewById(R.id.textView_humidity);
textview_date =itemview.findViewById(R.id.textView_date);
text_country= itemview.findViewById(R.id.text_country);
text_city=itemview. findViewById(R.id.text_city);
/*text_view=itemview.findViewById(R.id.text_view);*/
text_pressure=itemview. findViewById(R.id.text_pressure);
text_humidity=itemview.findViewById(R.id.text_humidity);
text_temp=itemview.findViewById(R.id.text_temp);
/* Bundle bundle=getArguments();
if (bundle!=null)
{
city=bundle.getString("search_city");
textView_country.setText(city);
Log.d("ass",""+city);
}*/
text_country.setVisibility(View.GONE);
text_city.setVisibility(View.GONE);
text_pressure.setVisibility(View.GONE);
text_humidity.setVisibility(View.GONE);
text_temp.setVisibility(View.GONE);
return itemview;
}
public void getCurrentData() {
String City1 = null;
if (getArguments() != null){
City1=getArguments().getString("search_city");
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService weatherService = retrofit.create(WeatherService.class);
Call<WeatherResponse> call = weatherService.getCurrentWeatherDataCityName(City1, AppId);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = (WeatherResponse) response.body();
assert weatherResponse != null;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE-dd-MM");
String formatedate = simpleDateFormat.format(calendar.getTime());
/* String stringbuilder= "Country : " +
weatherResponse.sys.country +
"\n" +
"City : " +weatherResponse.name +
"\n" +
"Tempreture : " + weatherResponse.main.temp +
"\n" +
"Tempreture(Min) : " +
weatherResponse.main.temp_min +
"\n" +
"Tempreture(Max) : " +
weatherResponse.main.temp_max +
"\n" +
"Humidity : " +
weatherResponse.main.humidity +
"\n" +
"Pressure : " +
weatherResponse.main.pressure;*/
String Country = weatherResponse.sys.country;
String City = weatherResponse.name;
String Temp = String.valueOf(weatherResponse.main.temp);
Double calcius = Double.parseDouble(Temp) - 273.0;
Integer i = calcius.intValue();
String Pressure = String.valueOf(weatherResponse.main.pressure);
String Humidity = String.valueOf(weatherResponse.main.humidity);
textView_country.setText(Country);
textView_city.setText(City);
textView_temp.setText(String.valueOf(i));
textView_pressure.setText(Pressure);
textView_humidity.setText(Humidity);
textview_date.setText(formatedate);
text_country.setVisibility(View.VISIBLE);
text_city.setVisibility(View.VISIBLE);
text_pressure.setVisibility(View.VISIBLE);
text_humidity.setVisibility(View.VISIBLE);
text_temp.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Successfully", Toast.LENGTH_SHORT).show();
}
if (response.code()==404)
{
Toast.makeText(getContext(), "City Not Founded", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call call, Throwable t) {
textView_country.setText(t.getMessage());
textView_city.setText(t.getMessage());
textView_temp.setText(t.getMessage());
textView_pressure.setText(t.getMessage());
textView_humidity.setText(t.getMessage());
textview_date.setText(t.getMessage());
}
});
}
}
Currentweatherframent.XML File
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/current_weather"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Country"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_date" />
<TextView
android:id="#+id/textView_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_country" />
<TextView
android:id="#+id/text_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:text="City"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_date" />
<TextView
android:id="#+id/textView_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_city" />
<TextView
android:id="#+id/text_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:text="Temperature"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/textView_country"
app:layout_constraintTop_toBottomOf="#id/textView_date" />
<TextView
android:id="#+id/textview_temp"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="40dp"
android:gravity="center"
android:text=""
android:textColor="#000"
android:textSize="40dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/text_temp" />
<TextView
android:id="#+id/text_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Pressure"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textview_temp" />
<TextView
android:id="#+id/textView_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_pressure" />
<TextView
android:id="#+id/text_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Humidity"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_pressure" />
<TextView
android:id="#+id/textView_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_humidity" />-->
<TextView
android:id="#+id/textView_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Error
1-03 19:35:10.586 1428-1428/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 1428
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:107)
at android.widget.Toast.makeText(Toast.java:264)
at com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather$1.onResponse(currentweather.java:129)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
01-03 21:43:00.695 10885-10885/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 10885
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.deitel.apiretrofitfragmentweatherapp/com.deitel.apiretrofitfragmentweatherapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at com.deitel.apiretrofitfragmentweatherapp.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6301)

Related

Why my recyclerview just don't show anything?

I'm using a recyclerview to show restaurants that are previously saved in a database, and I'm using volley to get their information, but it is not working, I suspect that is a problem with volley code, can you guys help me at this point? I will be very happy!
I've discovered that if I start another activity then I go back to home, it returns the recyclerview again, but if I change the fragment it disapears.
Here is how the app is working for now: Result
Fragment Home code:
package com.example.techtable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
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.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Home extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private ArrayList<restaurantes> restaurantesArrayList;
private static final String url = "https://cybersquare.dev.br/php/obterRestaurantes.php";
TextView txterro;
private RecyclerView recyclerview;
public Home() {
// Required empty public constructor
}
public static Pedidos newInstance(String param1, String param2) {
Pedidos fragment = new Pedidos();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedIntanceState){
super.onViewCreated(view, savedIntanceState);
dataInitialize();
recyclerview = view.findViewById(R.id.recyclerView);
recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerview.setHasFixedSize(true);
adapterRestaurante myAdapter = new adapterRestaurante(getContext(),restaurantesArrayList);
recyclerview.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
private void dataInitialize() {
restaurantesArrayList = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
response -> {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String titulo = object.getString("nome");
String descricao = object.getString("descricao");
int avaliacao = object.getInt("avaliacao");
int valor = object.getInt("valor");
String fotoResto = object.getString("fotoRestaurante");
restaurantesArrayList.add(new restaurantes(titulo, descricao, avaliacao, valor, fotoResto));
}
}catch (Exception e){
}
}, error -> Toast.makeText(getActivity(), error.toString(),Toast.LENGTH_LONG).show());
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
}
Recyclerview adapter:
package com.example.techtable;
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.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class adapterRestaurante extends RecyclerView.Adapter<adapterRestaurante.MyViewHolder>{
Context context;
ArrayList<restaurantes> restaurantesArrayList;
public adapterRestaurante(Context context, ArrayList<restaurantes> restaurantesArrayList) {
this.context = context;
this.restaurantesArrayList = restaurantesArrayList;
}
#NonNull
#Override
public adapterRestaurante.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.layout_linha_pesquisa, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull adapterRestaurante.MyViewHolder holder, int position) {
restaurantes restaurantes = restaurantesArrayList.get(position);
holder.titResto.setText(restaurantes.titResto);
holder.descResto.setText(restaurantes.descResto);
Picasso.get().load("fotoPerfil").into(holder.fotoResto);
}
#Override
public int getItemCount() {
return restaurantesArrayList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
ImageView fotoResto;
ImageView primeiraEstrela;
ImageView segundaEstrela;
ImageView terceiraEstrela;
ImageView primeiroDolar;
ImageView segundoDolar;
ImageView terceiroDolar;
TextView titResto;
TextView descResto;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
titResto = itemView.findViewById(R.id.titResto01);
descResto = itemView.findViewById(R.id.descResto01);
fotoResto = itemView.findViewById(R.id.fotoResto01);
primeiraEstrela = itemView.findViewById(R.id.estrela11);
segundaEstrela = itemView.findViewById(R.id.estrela12);
terceiraEstrela = itemView.findViewById(R.id.estrela13);
primeiroDolar = itemView.findViewById(R.id.valor11);
segundoDolar = itemView.findViewById(R.id.valor12);
terceiroDolar = itemView.findViewById(R.id.valor13);
}
}
}
Arraylist restaurantes
package com.example.techtable;
import android.net.Uri;
import android.widget.ImageView;
public class restaurantes {
String titResto;
String descResto;
int avaliacaoResto;
int valorResto;
String fotoResto;
public restaurantes(String titResto, String descResto, int avaliacaoResto, int valorResto, String fotoResto) {
this.titResto = titResto;
this.valorResto = valorResto;
this.avaliacaoResto = avaliacaoResto;
this.fotoResto = fotoResto;
this.descResto = descResto;
}
}
MyViewHolder layout
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/ConstainerResto01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="15dp"
android:background="#drawable/botaoresto"
android:onClick="teste"
android:paddingTop="20dp"
android:paddingBottom="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/fotoResto01"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginStart="20dp"
android:scaleType="centerInside"
android:src="#drawable/botaoredondo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginStart="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/fotoResto01"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout7"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_marginEnd="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/estrela11"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ic_posticestrelacheia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/estrela12"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="25dp"
android:src="#drawable/ic_posticestrelameia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/estrela13"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="50dp"
android:src="#drawable/ic_posticestrelavazia"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/valor11"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="#drawable/ic_posticdolarcheio"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/valor12"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="25dp"
android:src="#drawable/ic_posticdolarcheio"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/valor13"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginStart="50dp"
android:src="#drawable/ic_posticdolarmeia"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginEnd="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/constraintLayout7"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/descResto01"
android:layout_width="118dp"
android:layout_height="49dp"
android:fontFamily="#font/roboto_thin"
android:text="Lorem Ipsum Dolor Sit Amet Lorem Ipsum Dolor Sit Amet"
android:textColor="#color/cinza_medio"
android:textSize="15sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/titResto01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_black"
android:text="Restaurante 01"
android:textColor="#color/laranja"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment Home layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FFFFFF"
tools:context=".Home">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="25dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="25dp"
android:layout_marginBottom="1dp"
app:layout_constraintBottom_toTopOf="#+id/recyclerView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/txtUsuario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:fontFamily="#font/roboto_medium"
android:text="Olá usuário!"
android:textColor="#color/black"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/textView29"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView20" />
<ImageView
android:id="#+id/imageView20"
android:layout_width="200dp"
android:layout_height="80dp"
android:src="#drawable/logotechtablecolorida"
app:layout_constraintBottom_toTopOf="#+id/txtUsuario"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView29"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:fontFamily="#font/roboto_light"
android:text="Escolha seu restaurante e faça seu pedido"
android:textAlignment="viewStart"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtUsuario" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout8" />
</androidx.constraintlayout.widget.ConstraintLayout>
JSON file:
<?php
header('content-type: application/json');
$con = mysqli_connect("localhost","cyber536_admin","mJEn#*a]0Jc*","cyber536_techtable");
mysqli_set_charset($con,'utf-8');
$query = "select nome, avaliacao, descricao, fotoRestaurante, valor from restaurantes;";
$res = mysqli_query($con,$query);
$json_data = array();
while($row = mysqli_fetch_assoc($res)){
$json_data[] = $row;
}
echo json_encode($json_data);
?>

RecyclerView throws null pointer for setAdapter even though the adapter is defined

I have a null pointer exception but I can't see where I am going wrong. I have been trying to fix this error for 2 days.
Here is the activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
and the Code for the class MainActivity
package com.example.servicestest1;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
private static final String TAG = "MainActivity";
private ArrayList<String> mDescriptions = new ArrayList<>();
private ArrayList<String> mStartDates = new ArrayList<>();
private ArrayList<String> mEndDates = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private ArrayList<String> mTopicList = new ArrayList<>();
RecyclerView recyclerView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
initRecyclerViewItems();
}
private void initRecyclerViewItems() {
Log.d(TAG, "initRecyclerViewItems: preparing items");
addRecyclerViewItem("https://i.redd.it/3p6500yf3he41.jpg","Hogwarts Express","Working for the soviet union"
,"20/01/1968","20/10/1984");
addRecyclerViewItem("https://i.redd.it/s8bmctrhdxd41.jpg","Some scene about Nature","Some title",
"20/09/1897","20/03/1989");
addRecyclerViewItem("https://i.redd.it/lrbmhm707rd41.jpg","Boating","Boating in a pristine location",
"30/09/1998","31/09/1998");
initRecyclerView();
}
private void addRecyclerViewItem(String imageUrl, String topic, String description, String startDate, String endDate){
Log.w(TAG, "addRecyclerViewItem: called", null);
mImageUrls.add(imageUrl);
mTopicList.add(topic);
mStartDates.add(startDate);
mEndDates.add(endDate);
mDescriptions.add(description);
}
private void initRecyclerView(){
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this,mTopicList,mDescriptions,
mStartDates,mEndDates,mImageUrls);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
The recyclerView.setAdapter returns a NullPointer exeception even though I have defined the adapter.
and the code for the RecyclerView adapter
package com.example.servicestest1;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mTopicListOfTheEvent;
private ArrayList<String> mDescriptionListOfTheEvent;
private ArrayList<String> mStartDateListOfTheEvent;
private ArrayList<String> mEndDateListOfTheEvent;
private ArrayList<String> mImageListDescribingTheEvent;
private Context mContext;
RecyclerViewAdapter(Context context,
ArrayList<String> topicListOfTheEvent,
ArrayList<String> descriptionListOfTheEvent,
ArrayList<String> startDateListOfTheEvent,
ArrayList<String> endDateListOfTheEvent,
ArrayList<String> imageListDescribingTheEvent){
this.mContext = context;
this.mTopicListOfTheEvent = topicListOfTheEvent;
this.mDescriptionListOfTheEvent = descriptionListOfTheEvent;
this.mStartDateListOfTheEvent = startDateListOfTheEvent;
this.mEndDateListOfTheEvent = endDateListOfTheEvent;
this.mImageListDescribingTheEvent = imageListDescribingTheEvent;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_recycler_view_layout,parent,true);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called");
holder.descriptionOfTheEvent.setText(mDescriptionListOfTheEvent.get(position));
holder.imageDescribingTheEvent.setImageURI(Uri.parse(mImageListDescribingTheEvent.get(position)));
holder.startDateOfTheEvent.setText(mStartDateListOfTheEvent.get(position));
holder.endDateOfTheEvent.setText(mEndDateListOfTheEvent.get(position));
holder.topicListOfTheEvent.setText(mTopicListOfTheEvent.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Clicked on");
Toast.makeText(mContext,"You pressed me",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mTopicListOfTheEvent.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView descriptionOfTheEvent;
TextView topicListOfTheEvent;
TextView startDateOfTheEvent;
TextView endDateOfTheEvent;
ImageView imageDescribingTheEvent;
LinearLayout parentLayout;
ViewHolder(#NonNull View itemView) {
super(itemView);
parentLayout = itemView.findViewById(R.id.recycler_view_item);
}
}
}
and the code for the activity_recycler_view_layout.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:id="#+id/recycler_view_item">
<!-- The code for the AppBar -->
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="44dp"
android:background="#FFFEFE"
android:elevation="5dp"
tools:targetApi="lollipop">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="8dp"
android:src="#drawable/bottom_lotus"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="11dp"
android:layout_height="44dp"
android:layout_marginStart="18dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="17dp"
android:layout_marginBottom="10dp"
android:src="#drawable/arrow"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/textView"
android:layout_width="66dp"
android:layout_height="44dp"
android:layout_marginStart="49dp"
android:layout_marginLeft="49dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="10dp"
android:lineHeight="21sp"
android:text="Services"
android:textColor="#403E42"
android:textSize="16sp"
app:fontFamily="#font/roboto_condensed_regular"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_picture"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:src="#drawable/ic_launcher_background"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
<RelativeLayout
android:layout_width="348dp"
android:layout_height="296dp"
android:layout_margin="6dp">
<ImageView
android:layout_width="348dp"
android:layout_height="296dp"
android:src="#drawable/images" />
<TextView
android:id="#+id/topic_text_view"
android:layout_width="wrap_content"
android:layout_height="28dp"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp"
android:alpha="0.41"
android:text="It's His Birthday"
android:textColor="#f93f3f"
android:textSize="21sp"
app:fontFamily="#font/roboto_condensed_bold" />
<!--This LinearLayout is used for drawing the text inside the rectangle -->
<LinearLayout
android:layout_width="242dp"
android:layout_height="51dp"
android:layout_marginLeft="26dp"
android:layout_marginTop="64dp"
android:background="#drawable/rectangle"
android:orientation="vertical"
android:layout_marginStart="26dp">
<TextView
android:layout_width="198dp"
android:layout_height="32dp"
android:gravity="center"
android:lineHeight="16dp"
android:text="This is Sample Text"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto_bold" />
</LinearLayout>
<TextView
android:layout_width="37dp"
android:layout_height="19dp"
android:layout_marginStart="26dp"
android:layout_marginLeft="26dp"
android:layout_marginTop="142dp"
android:lineHeight="19dp"
android:text="Dates"
android:textColor="#FFFFFF"
android:textSize="14sp"
app:fontFamily="#font/roboto_condensed_bold" />
<LinearLayout
android:layout_width="86dp"
android:layout_height="35dp"
android:layout_marginStart="62dp"
android:layout_marginLeft="62dp"
android:layout_marginTop="142dp"
android:orientation="vertical">
<TextView
android:id="#+id/start_date_of_the_event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineHeight="16dp"
android:text="12 June 2019"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto" />
<TextView
android:id="#+id/end_date_of_the_event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineHeight="16dp"
android:text="13 June 2019"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto" />
</LinearLayout>
</RelativeLayout>
<TextView
android:id="#+id/reject_button"
android:layout_width="35dp"
android:layout_height="16dp"
android:layout_marginStart="160dp"
android:layout_marginLeft="160dp"
android:layout_marginTop="15dp"
android:clickable="true"
android:text="REJECT"
android:textColor="#4B0082"
android:textStyle="bold"
tools:ignore="KeyboardInaccessibleWidget" />
<Button
android:id="#+id/accept_button"
android:layout_width="103dp"
android:layout_height="37dp"
android:layout_marginStart="248dp"
android:layout_marginLeft="248dp"
android:background="#4B0082"
android:text="ACCEPT"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
And the here are the errors
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.servicestest1/com.example.servicestest1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.example.servicestest1.MainActivity.initRecyclerView(MainActivity.java:53)
at com.example.servicestest1.MainActivity.initRecyclerViewItems(MainActivity.java:38)
at com.example.servicestest1.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
recyclerView variable is set after its usage, so it's null when you try to set adapter.
Assign recyclerView before setting the adapter
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
initRecyclerViewItems();
}
in Java, calling findViewById(...) initializes the view variable. The variable is usually null when findViewById(..) hasn't been called yet or has been called with an id from a layout which hasn't been inflated yet. In your case. You can fix the error simply by changing your onCreate method.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view); //recyclerView gets initialized here
initRecyclerViewItems();
}
Google docs on findViewById
It takes some time to inflate recycler view. Try to add waiting cycle:
recyclerView = findViewById(R.id.recycler_view);
while (recyclerView == null){
Thread.sleep(1);
}
init();

onclick listener not working in surfaceview of swipe layout

I am trying to call constructor on onClick listener of getSurfaceView for swipe layout but it is not happening.
RideAdapter.java
#Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view;
if (viewType == RIDE_ITEM_TYPE) {
view = inflater.inflate(R.layout.item_upcoming_share_ride, parent, false);
swipeLayout = (SwipeLayout) view.findViewById(R.id.sample2);
swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
swipeLayout.addDrag(SwipeLayout.DragEdge.Right, swipeLayout.findViewWithTag("Bottom2"));
// sample2.setShowMode(SwipeLayout.ShowMode.PullOut);
swipeLayout.findViewById(R.id.edit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Star", Toast.LENGTH_SHORT).show();
}
});`
swipeLayout.findViewById(R.id.delete).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Magnifier", Toast.LENGTH_SHORT).show();
}
});
swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v = inflater.inflate(R.layout.item_upcoming_share_ride, parent, false);
new OfferedRideCardViewHolder(v);
}
});
return new OfferedRideCardViewHolder(view);
and OfferedRideCardViewHolder class:
class OfferedRideCardViewHolder extends BaseRideViewHolder {
#BindView(R.id.imgVechicleImage) ImageView imgVechicle;
#BindView(R.id.imgRideIcon) ImageView imgRideIcon;
#BindView(R.id.fromTextView) TextView txtFromLocation;
#BindView(R.id.toTextView) TextView txtToLocation;
#BindView(R.id.txtVichecleModel) TextView txtVichecleModel;
#BindView(R.id.txtRegisterationNo) TextView txtRegisterationNo;
#BindView(R.id.txtDateTime) TextView txtDateTime;
#BindView(R.id.buttonStartEnd) Button startEndRideButton;
#BindView(R.id.matchCountTextView) TextView matchCountTextView;
#BindView(R.id.matchesTextView) TextView matchesTextView;
#BindView(R.id.vehicleContainer) LinearLayout vehicleContainer;
OfferedRideCardViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
item_upcoming_share_ride.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 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/cv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="4dp"
app:cardCornerRadius="4dp">
<com.daimajia.swipe.SwipeLayout
android:id="#+id/sample2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:tag="Bottom2"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/edit"
android:src="#drawable/edit"
android:layout_width="70dp"
android:background="#00FF00"
android:paddingLeft="25dp"
android:paddingRight="25dp"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/delete"
android:src="#drawable/delete_grey"
android:layout_width="70dp"
android:background="#FF0000"
android:paddingLeft="25dp"
android:paddingRight="25dp"
android:layout_height="match_parent" />
</LinearLayout>
<LinearLayout
android:id="#+id/llMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
>
<View
android:id="#+id/view"
android:layout_width="16dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:background="#drawable/vetical_rounded_corner_orange_background"
app:layout_constraintBottom_toBottomOf="#+id/toTextView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/fromTextView"
/>
<TextView
android:id="#+id/fromTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="12dp"
android:layout_marginTop="16dp"
android:ellipsize="end"
android:fontFamily="#font/lato_regular"
android:maxLines="1"
android:text="Sector 39A, Sector 32, Sector 39, Noida, Uttar Pradesh 201303"
android:textColor="#color/secondary_text"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/view"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="#+id/toTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ellipsize="end"
android:fontFamily="#font/lato_regular"
android:maxLines="1"
android:text="Sector 39A, Sector 32, Sector 39, Noida, Uttar Pradesh 201303"
android:textColor="#color/secondary_text"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="#+id/fromTextView"
app:layout_constraintStart_toStartOf="#+id/fromTextView"
app:layout_constraintTop_toBottomOf="#+id/fromTextView"
/>
<ImageView
android:id="#+id/from_dot_view"
android:layout_width="8dp"
android:layout_height="8dp"
android:src="#drawable/current_location"
android:tint="#color/white"
app:layout_constraintBottom_toBottomOf="#+id/fromTextView"
app:layout_constraintEnd_toEndOf="#+id/view"
app:layout_constraintStart_toStartOf="#+id/view"
app:layout_constraintTop_toTopOf="#+id/fromTextView"
/>
<ImageView
android:id="#+id/to_dot_view"
android:layout_width="8dp"
android:layout_height="wrap_content"
android:src="#drawable/pin_red"
android:tint="#color/white"
app:layout_constraintBottom_toBottomOf="#+id/toTextView"
app:layout_constraintEnd_toEndOf="#+id/view"
app:layout_constraintStart_toStartOf="#+id/view"
app:layout_constraintTop_toTopOf="#+id/toTextView"
/>
<TextView
android:id="#+id/txtDateTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/montserrat_regular"
android:gravity="center_vertical"
android:text="23rd jan,2016 2.30 pm"
android:textColor="#color/secondary_text"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/toTextView"
app:layout_constraintStart_toStartOf="#+id/toTextView"
app:layout_constraintTop_toBottomOf="#+id/view"
/>
<ImageView
android:id="#+id/imageView11"
android:layout_width="16dp"
android:layout_height="16dp"
android:layout_marginTop="8dp"
android:adjustViewBounds="true"
android:tint="#color/colorPrimaryLight"
app:layout_constraintBottom_toBottomOf="#+id/txtDateTime"
app:layout_constraintEnd_toEndOf="#+id/view"
app:layout_constraintStart_toStartOf="#+id/view"
app:layout_constraintTop_toBottomOf="#+id/view"
app:srcCompat="#drawable/ic_clock_white_24dp"
/>
</android.support.constraint.ConstraintLayout>
<LinearLayout
android:id="#+id/vehicleContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dp_10"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="#dimen/dp_5"
android:paddingLeft="#dimen/dp_10"
android:paddingRight="#dimen/sp_10"
android:paddingTop="#dimen/dp_5"
>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/imgVechicleImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="#drawable/imgcar_fullsize"
tools:layout_editor_absoluteX="18dp"
tools:layout_editor_absoluteY="38dp"
/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="vertical"
>
<TextView
android:id="#+id/txtVichecleModel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:layout_marginStart="8dp"
android:fontFamily="#font/montserrat_regular"
android:text="Camaro 45"
android:textColor="#color/secondary_text"
android:textSize="12sp"
/>
<TextView
android:id="#+id/txtRegisterationNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="2dp"
android:fontFamily="#font/lato_regular"
android:text="Reg no. 1234"
android:textColor="#color/secondary_text"
android:textSize="12sp"
/>
</LinearLayout>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:padding="#dimen/dp_5"
>
<ImageView
android:id="#+id/imgRideIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="0dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="0dp"
android:padding="#dimen/dp_5"
android:src="#drawable/driver"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<TextView
android:id="#+id/matchCountTextView"
android:layout_width="18dp"
android:layout_height="18dp"
android:layout_marginBottom="4dp"
android:layout_marginTop="8dp"
android:background="#drawable/fill_circle_red"
android:fontFamily="#font/lato_regular"
android:gravity="center"
android:text="5"
android:textColor="#color/white"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="#+id/guideline3"
app:layout_constraintRight_toRightOf="#+id/imgRideIcon"
app:layout_constraintTop_toTopOf="parent"
/>
<android.support.constraint.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"
/>
</android.support.constraint.ConstraintLayout>
</LinearLayout>
<TextView
android:id="#+id/matchesTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:fontFamily="#font/montserrat_regular"
android:padding="4dp"
android:text="You have 12 matches available"
android:textColor="#color/colorAccent"
android:textSize="14sp"
android:visibility="visible"
/>
<!--<Button
android:id="#+id/button_invite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Invite"
app:font="MontserratRegular"
android:textColor="#color/white"
android:background="#color/colorAccent"
android:layout_marginTop="8dp"
/>-->
<android.support.v7.widget.AppCompatButton
android:id="#+id/buttonStartEnd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginTop="8dp"
android:background="#FF8A65"
android:fontFamily="#font/montserrat_regular"
android:text="Start Ride"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="16sp"
android:visibility="visible"
/>
</LinearLayout>
</com.daimajia.swipe.SwipeLayout>
</android.support.v7.widget.CardView>
DisplayMyRideFragmentViewHolder
package com.techugo.buno.fragments;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.swipe.SwipeLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.techugo.buno.ActivityNavigator;
import com.techugo.buno.R;
import com.techugo.buno.activities.NewRideActivity;
import com.techugo.buno.activities.RatePassengersActivity;
import com.techugo.buno.app.MyApplication;
import com.techugo.buno.callbacks.RetrofitCallback;
import com.techugo.buno.common.BaseViewHolder;
import com.techugo.buno.common.events.HideLoadingEvent;
import com.techugo.buno.common.events.RefreshDependenciesEvent;
import com.techugo.buno.common.events.ShowLoadingEvent;
import com.techugo.buno.constant.AppConstant;
import com.techugo.buno.constant.ServerConstants;
import com.techugo.buno.dialog.RateDriverDialog;
import com.techugo.buno.helpers.AppUtilis;
import com.techugo.buno.home.events.ShowAddNameDialogEvent;
import com.techugo.buno.home.searchrides.SearchRideFragmentViewHolder;
import com.techugo.buno.home.sharerides.RidesAdapter;
import com.techugo.buno.loginsignup.models.User;
import com.techugo.buno.modals.NotificationResponseModel;
import com.techugo.buno.modals.UpcomingPromoModel;
import com.techugo.buno.modals.UpcomingResultModel;
import com.techugo.buno.networkInterFace.RetrofitApiService;
import com.techugo.buno.offers.OffersActivity;
import com.techugo.buno.ridedetail.Ride;
import com.techugo.buno.ridedetail.events.RideDetailEvents;
import com.techugo.framework.helper.TUGPrefs;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.OnClick;
public class DisplayMyRideFragmentViewHolder extends BaseViewHolder<List<Ride>> {
#Inject
RetrofitApiService retrofitApiService;
#Inject #Named("currentLoggedInUser")
User user;
#Inject
ActivityNavigator activityNavigator;
#BindView(R.id.upcomingRidesRecyclerView)
RecyclerView recyclerView;
#BindView(R.id.emptyLayout)
LinearLayout emptyLayout;
#BindView(R.id.text_no_internet_connection)
TextView noInternetTextView;
#BindView(R.id.loading_layout) LinearLayout progressBar;
#BindView(R.id.promo_card_view)
CardView promoCard;
#BindView(R.id.promo_title) TextView promoTitle;
private RidesAdapter ridesAdapter;
private List<Ride> myRidesModels;
private UpcomingPromoModel myPromoModel;
public DisplayMyRideFragmentViewHolder(View view, List<Ride> data, Context context) {
super(view,data,context);
this.myRidesModels = data;
this.context = context;
setUpRecyclerView();
setData(myRidesModels);
}
private void getUpComingRides() {
HashMap<String, Object> params = new HashMap<>();
params.put("method", ServerConstants.ALL_UPCOMING_RIDES);
params.put("user_id", user.getUser_id());
params.put("offset", "0");
params.put("limit", "20");
emptyLayout.setVisibility(View.GONE);
//progressBar.setVisibility(View.VISIBLE);
EventBus.getDefault().post(new ShowLoadingEvent(DisplayMyRideFragmentViewHolder.this.getClass().getSimpleName()));
//DisplayUtils.disableUserInteraction((Activity)context);
retrofitApiService.getUpComingRides(params)
.enqueue(new RetrofitCallback<UpcomingResultModel>() {
#Override protected void onSuccess(UpcomingResultModel upcomingResultModel) {
//progressBar.setVisibility(View.GONE);
EventBus.getDefault()
.post(new HideLoadingEvent(
DisplayMyRideFragmentViewHolder.this.getClass().getSimpleName()));
//DisplayUtils.enableUserInteraction((Activity)context);
myRidesModels.clear();
myRidesModels.addAll(upcomingResultModel.getData());
if(upcomingResultModel.getOffers() != null && upcomingResultModel.getOffers().size() > 0) {
myPromoModel = upcomingResultModel.getOffers().get(0);
promoCard.setVisibility(View.VISIBLE);
promoTitle.setText(myPromoModel.getPromo_title());
} else {
promoCard.setVisibility(View.GONE);
}
TUGPrefs.putString(AppConstant.IS_ANY_ACTIVE,
upcomingResultModel.getActive_ride_status());
initializeView(myRidesModels);
}
#Override protected void onError(String errorMessage) {
//progressBar.setVisibility(View.GONE);
//DisplayUtils.enableUserInteraction((Activity)context);
EventBus.getDefault()
.post(new HideLoadingEvent(
DisplayMyRideFragmentViewHolder.this.getClass().getSimpleName()));
Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
if (!AppUtilis.isNetworkAvailable(context)) {
emptyLayout.setVisibility(View.GONE);
noInternetTextView.setVisibility(View.VISIBLE);
}
}
});
}
private void setUpRecyclerView() {
ridesAdapter = new RidesAdapter(myRidesModels, context);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
recyclerView.setAdapter(ridesAdapter);
// ridesAdapter.notifyDataSetChanged();
}
#Override
protected void attachListeners(List<Ride> data) {
}
#Override
protected void initializeView(#NonNull List<Ride> data) {
if (ridesAdapter != null && data.size() != 0) {
emptyLayout.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
ridesAdapter.setData(data);
} else {
recyclerView.setVisibility(View.GONE);
emptyLayout.setVisibility(View.VISIBLE);
}
noInternetTextView.setVisibility(View.GONE);
}
public void refreshView() {
MyApplication.getInstance().getNetComponent().inject(this);
getUpComingRides();
}
#OnClick(R.id.fab_search_ride) void onShareRideFabClick() {
//Intent intent = new Intent(context, FindRideActivity.class);
//context.startActivity(intent);
//if (user.getSignin_type().equals("1") && user.getReg_process().equals("0")) {
// AppUtilis.goToActivity(context, PhoneVerifyActivity.class);
// TUGPrefs.putString("ISFINDRIDE", "yes");
//} else {
//
//}
if (user.getFull_name() == null || user.getFull_name().isEmpty()) {
EventBus.getDefault().post(new ShowAddNameDialogEvent());
return;
}
activityNavigator.startActivity(context, NewRideActivity.class);
}
#OnClick(R.id.promo_card_view) void onPromoCardClick() {
activityNavigator.startActivity(context, OffersActivity.class);
}
#Override public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
refreshView();
}
#Override public void onResume() {
super.onResume();
}
#Override public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onReloadComponents(RefreshDependenciesEvent event) {
MyApplication.getInstance().getNetComponent().inject(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onRideRefresh(RideDetailEvents.RefreshRideDetailEvent event) {
refreshView();
String noty_retrieve = TUGPrefs.getString(AppConstant.IS_RATE_HAS_VALUE, "");
if (noty_retrieve.length() > 0) {
Gson gson = new Gson();
Type type = new TypeToken<NotificationResponseModel>() {
}.getType();
NotificationResponseModel notificationResponseModel = gson.fromJson(noty_retrieve, type);
if (notificationResponseModel != null) {
if (notificationResponseModel.getUser_type() != null
&& notificationResponseModel.getUser_type().equalsIgnoreCase("Driver")) {
Intent intent =
activityNavigator.getIntent(context, RatePassengersActivity.class);
intent.putExtra(AppConstant.NOTY_PASSANGER_DATA, noty_retrieve);
context.startActivity(intent);
} else {
new RateDriverDialog(context, notificationResponseModel).show();
}
}
}
}
}
Toast is working but constructor is not doing anything

My app keeps on crashing and I am not able to see what the problem is [duplicate]

This question already has answers here:
Unable to start activity ComponentInfo.....java.lang.IllegalStateException: Already attached
(2 answers)
Closed 3 years ago.
This is my code. Please check.. When I execute it the app crashes. So app was fine before, but I added validation to the form and since then as soon as the app run it crashes. I have used https://www.simplifiedcoding.net/android-form-validation-tutorial/ for adding awsomeform and so I have also made some changes to the strings.xml file. Please check this once too. It was fine before and I could access the file pretty easily.
This is the error I get on Android studio when I try to run the app and the app installs, launches and then crashes.
This is my mainactivity code. I believe something is going on with the implements part and the code i.e. import.com.google.common.collect.range is also unused
MainActivity.java
import android.Manifest;
import android.net.sip.SipSession;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.Toast;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import android.util.Patterns;
import android.widget.EditText;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
import com.google.common.collect.Range;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
public Button btn;
public ImageView imageview;
public static final String IMAGE_DIRECTORY = "/demonuts";
public int GALLERY = 1, CAMERA = 2;
public EditText r_name_fill, r_email_fill, r_edit_phone, r_cardetails, r_pass_fill;
public RadioButton r_male, r_female;
public Button r_submit;
public AwesomeValidation awesomeValidation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestMultiplePermissions();
btn = (Button) findViewById(R.id.btn);
imageview = (ImageView) findViewById(R.id.iv);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing awesomevalidation object
/*
* The library provides 3 types of validation
* BASIC
* COLORATION
* UNDERLABEL
* */
awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);
//initializing view objects
r_name_fill = (EditText) findViewById(R.id.r_name_fill);
r_email_fill = (EditText) findViewById(R.id.r_email_fill);
r_edit_phone = (EditText) findViewById(R.id.r_edit_phone);
r_cardetails = (EditText) findViewById(R.id.r_cardetails);
r_pass_fill = (EditText) findViewById(R.id.r_pass_fill);
r_male = (RadioButton) findViewById(R.id.r_male);
r_female = (RadioButton) findViewById(R.id.r_female);
r_submit = (Button) findViewById(R.id.r_submit);
//adding validation to edittexts
awesomeValidation.addValidation(this, R.id.r_name_fill, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);
awesomeValidation.addValidation(this, R.id.r_email_fill, Patterns.EMAIL_ADDRESS, R.string.emailerror);
awesomeValidation.addValidation(this, R.id.r_pass_fill, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.passworderror);
awesomeValidation.addValidation(this, R.id.r_edit_phone, "^[2-9]{2}[0-9]{8}$", R.string.mobileerror);
awesomeValidation.addValidation(this, R.id.r_name_fill, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.carerror);
r_submit.setOnClickListener(this);
btn.setOnClickListener(this);
}
#Override
public void onClick(View V) {
if (V== r_submit) {
submitForm();
}
showPictureDialog();
}
public void submitForm() {
//first validate the form then move ahead
//if this becomes true that means validation is successfull
if (awesomeValidation.validate()) {
Toast.makeText(this, "Validation Successful", Toast.LENGTH_LONG).show();
//process the data further
}
}
public void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
public void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
public void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView3"
android:layout_width="383dp"
android:layout_height="563dp"
android:contentDescription="#string/todo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#drawable/ic_launcher_foreground" />
<TextView
android:id="#+id/r_name"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginLeft="17dp"
android:layout_marginStart="17dp"
android:layout_marginTop="16dp"
android:text="Name"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/r_name_fill"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginEnd="36dp"
android:layout_marginRight="36dp"
android:ems="10"
android:hint="John Doe"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintEnd_toStartOf="#+id/imageView3"
app:layout_constraintHorizontal_bias="0.362"
app:layout_constraintStart_toEndOf="#+id/imageView3"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.003" />
<TextView
android:id="#+id/r_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:text="Email"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.11" />
<EditText
android:id="#+id/r_email_fill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:hint="email#techmahindra.com"
android:inputType="textEmailAddress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.092" />
<TextView
android:id="#+id/r_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone No."
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.05"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.191" />
<EditText
android:id="#+id/r_edit_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="+91-XXXXXX"
android:inputType="phone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.174" />
<TextView
android:id="#+id/r_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.051"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.256" />
<RadioButton
android:id="#+id/r_male"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="400dp"
android:text="Male"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.476"
app:layout_constraintStart_toStartOf="parent" />
<RadioButton
android:id="#+id/r_female"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
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.315" />
<TextView
android:id="#+id/r_car"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Details"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.059"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.375" />
<EditText
android:id="#+id/r_cardetails"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Car Details"
android:inputType="text|textMultiLine|textLongMessage"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.385" />
<TextView
android:id="#+id/r_dl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Driving Licence"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.071"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.476" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="223dp"
android:layout_marginEnd="16dp"
android:text="Select or Capture Image"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/iv"
android:layout_width="154dp"
android:layout_height="86dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="126dp"
android:scaleType="fitXY"
android:src="#mipmap/ic_launcher" />
</RelativeLayout>
<TextView
android:id="#+id/r_password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.003"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.844" />
<EditText
android:id="#+id/r_pass_fill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.867" />
<Button
android:id="#+id/r_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.432"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.969" />
</android.support.constraint.ConstraintLayout>
You are calling super.onCreate(savedInstanceState); andsetContentView(R.layout.activity_main); 2 times unser on creat lifecycle , delete one of them and it should fix your problem.

How can call to refresh my fragment class in another method (I Tried all the solution on stackoverflow)

I have a void method synchronizeNum(String String String) Which will be trigger in onViewCreated , This Line.
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName).execute();
It will get data from database and finally pass back and set the data into this method synchronizeNum (String String String).After i set the data i wish to display it using TextView. I think the only way is execute again onViewCreated method, since we cannot setText inside synchronizeNum method.I have tried many detach and attach method inside the method but the problem is it get NullPointer i donno how to solve i have been looking around for 1 day just for this little problem. I need you guys help please.
CurrentDepartmentView FragmentClass
package com.example.cheng.freequeue.DisplayDepartmentStatus;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.cheng.freequeue.R;
/**
* Created by cheng on 11/4/2018.
*/
public class CurrentStatusView extends Fragment {
DisDepartmentList disDepartmentList=new DisDepartmentList();
final static String urlAddress = "https://kokcheng95.000webhostapp.com/departmentStatus.php";
private String CompanyName, accountEmail, departmentName, imageUrl;
private String num1room1, num2room2, num3room3, num1, num2, num3, room1, room2, room3;
private final Handler handler = new Handler();
View myView;
Context c;
ViewGroup container;
private LayoutInflater inflater;
TextView company_name, department_name, num_1, num_2, num_3, room_1, room_2, room_3;
de.hdodenhof.circleimageview.CircleImageView image_department;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.current_department_view, container, false);
this.container=container;
company_name = (TextView) myView.findViewById(R.id.company_name);
department_name = (TextView) myView.findViewById(R.id.department_name);
image_department = (de.hdodenhof.circleimageview.CircleImageView) myView.findViewById(R.id.image_department);
num_1 = (TextView) myView.findViewById(R.id.number1);
num_1 = (TextView) myView.findViewById(R.id.number1);
num_2 = (TextView) myView.findViewById(R.id.number2);
num_3 = (TextView) myView.findViewById(R.id.number3);
room_1 = (TextView) myView.findViewById(R.id.room1);
room_2 = (TextView) myView.findViewById(R.id.room2);
room_3 = (TextView) myView.findViewById(R.id.room3);
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName).execute();
//Set data
company_name.setText("Company Name : " + CompanyName);
department_name.setText("Department : " + departmentName);
PicassoClientDepartment.dowloadImage(myView.getContext(), imageUrl, image_department);
//Set Data
num_1.setText(num1);
num_2.setText(num1);
num_3.setText(num1);
room_1.setText(room1);
room_2.setText(room2);
room_3.setText(room3);
return myView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
CompanyName = bundle.getString("CompanyName", "noText");
accountEmail = bundle.getString("accountEmail", "noText");
departmentName = bundle.getString("departmentName", "noText");
imageUrl = bundle.getString("imageUrl", "noText");
}
}
public void synchronizeNum(String num1room1, String num2room2, String num3room3) {
String path1[] = num1room1.split("_");
String path2[] = num2room2.split("_");
String path3[] = num3room3.split("_");
num1 = path1[0];
room1 = path1[1];
num2 = path2[0];
room2 = path2[1];
num3 = path3[0];
room3 = path3[1];
/* Fragment currentFragment = getActivity().getFragmentManager().findFragmentByTag("CurrentStatusView");
FragmentTransaction fragTransaction = (getActivity()).getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();*/
}
public void setNum1room1(String num1room1) {
this.num1room1 = num1room1;
}
public String getNum1room1() {
return num1room1;
}
public void setNum2room2(String num2room2) {
this.num2room2 = num2room2;
}
public String getNum2room2() {
return num2room2;
}
public void setNum3room3(String num3room3) {
this.num3room3 = num3room3;
}
public String getNum3room3() {
return num3room3;
}
}
current_department_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.cheng.freequeue.LoginPage">
<TextView
android:id="#+id/department_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:text="Department : Orthopedic"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.163" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.515"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.458">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/textView6"
android:layout_width="200dp"
android:layout_height="80dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape"
android:text="Number"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="40dp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView5"
android:layout_width="150dp"
android:layout_height="80dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape"
android:text="Room"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="40dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number1"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1001"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room1"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number2"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1002"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room2"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number3"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1003"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room3"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/btn_booking"
android:layout_width="350dp"
android:layout_height="50dp"
android:background="#d7b9b9b9"
android:text="BOOKING"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold"
android:visibility="visible"
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.965" />
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/image_department"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.015"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.048"
app:civ_border_color="#ffffff"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/company_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Company Name: TNB"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.064" />
</android.support.constraint.ConstraintLayout>
This Line Error ,NullPointer
Fragment currentFragment=getActivity().getFragmentManager().findFragmentByTag("CurrentStatusView");
Logcat error
04-12 20:52:13.112 3021-3021/com.example.cheng.freequeue E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.cheng.freequeue.DisplayDepartmentStatus.CurrentStatusView.synchronizeNum(CurrentStatusView.java:104)
at com.example.cheng.freequeue.DisplayDepartmentStatus.DisDepartmentParse.onPostExecute(DisDepartmentParse.java:64)
at com.example.cheng.freequeue.DisplayDepartmentStatus.DisDepartmentParse.onPostExecute(DisDepartmentParse.java:18)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5166)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:561)
at dalvik.system.NativeStart.main(Native Method)
I recommend to create an interface for updating data.
public interface SynchronizeCallback {
void synchronizeNum(String num1room1, String num2room2, String num3room3);
}
Your fragment should implement this interface.
Also set the text to the TextViews inside synchronizeNum():
num_1.setText(num1);
num_2.setText(num1);
num_3.setText(num1);
room_1.setText(room1);
room_2.setText(room2);
room_3.setText(room3);
Pass the interface to your task when you create it:
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName, this).execute();
In onPostExecute of your AsyncTask call
syncronizeCallback.updateValues(newNum1room1, newNum2room2, newNum3room3);
Then you should see the new data.

Categories