Cannot find method on Onclick property - java

I'm trying to call postannonce method, but it doesn't show on Onclick method list. Here's my SecondeFrament.java code:
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
public class SecondeFragment extends Fragment {
public static final String TAG = "seconde";
ProgressBar prog;
Button post;
EditText titre;
EditText text;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondefragment, container, false);
post = (Button) view.findViewById(R.id.ressayer);
titre = (EditText) view.findViewById(R.id.titreannonce);
text = (EditText) view.findViewById(R.id.textannonce);
prog = (ProgressBar) view.findViewById(R.id.progressBar2);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void postannonce(View view){
prog.setVisibility(View.VISIBLE);
String titreannonce = titre.getText().toString();
String textannonce= text.getText().toString();
if((!titreannonce.trim().equals(""))&&(!textannonce.trim().equals(""))){
new PostActivity(getActivity(),prog).execute(titreannonce, textannonce);
}
else{
Toast.makeText(getActivity(), "Veuillez remplir tout les champs svp", Toast.LENGTH_SHORT).show();
prog.setVisibility(View.INVISIBLE);
}
}
}
And secondeFragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lay1">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:indeterminate="false"
android:visibility="invisible" />
<EditText
android:layout_width="260dp"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/titreannonce"
android:textColor="#000000"
android:maxLength="30"
android:background="#drawable/edittxt"
android:layout_marginBottom="70dp"
android:textColorHint="#ffb5b5b5"
android:hint="Donnez un titre a votre annonce .."
android:layout_above="#+id/progressBar2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="260dp"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/textannonce"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:textColor="#000000"
android:background="#drawable/textarea"
android:gravity="left|top"
android:maxLength="150"
android:hint="Votre annonce ici .."
android:textColorHint="#ffb5b5b5"
android:layout_alignBottom="#+id/post"
android:layout_alignLeft="#+id/titreannonce"
android:layout_alignStart="#+id/titreannonce"
android:layout_below="#+id/titreannonce"
android:layout_marginBottom="70dp"/>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/post"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_margin="16dp"
android:background="#drawable/floating_button"
android:src="#mipmap/ic_check"
android:padding="16dp"
android:onClick="postannonce"
android:scaleType="center" />
</RelativeLayout>
I'm still new to Android and I will be gratefull if someone can tell me what I'm missing in my code.

Your postannonce method needs to be inside your SecondeFragment class. Change this part:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void postannonce(View view){
prog.setVisibility(View.VISIBLE);
String titreannonce = titre.getText().toString();
String textannonce= text.getText().toString();
if((!titreannonce.trim().equals(""))&&(!textannonce.trim().equals(""))){
new PostActivity(getActivity(),prog).execute(titreannonce, textannonce);
}
else{
Toast.makeText(getActivity(), "Veuillez remplir tout les champs svp", Toast.LENGTH_SHORT).show();
prog.setVisibility(View.INVISIBLE);
}
}
}
to look like this:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
public void postannonce(View view){
prog.setVisibility(View.VISIBLE);
String titreannonce = titre.getText().toString();
String textannonce= text.getText().toString();
if((!titreannonce.trim().equals(""))&&(!textannonce.trim().equals(""))){
new PostActivity(getActivity(),prog).execute(titreannonce, textannonce);
}
else{
Toast.makeText(getActivity(), "Veuillez remplir tout les champs svp", Toast.LENGTH_SHORT).show();
prog.setVisibility(View.INVISIBLE);
}
}
}
}

Related

Fetching and retrieving data from realtime database Android studio

I encountered a problem while retrieving specific data from the firebase database, however, I was able to retrieve other data and view it using RecyclerView. The address and contact number is not showing. Here is my code and snippet of the output.
lopdetails_items.xml
Emulator Output
LopDetailsAdapter.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
public class LoPdetailsAdapter extends
FirebaseRecyclerAdapter<RegisterParking,LoPdetailsAdapter.myViewHolder> {
/**
* Initialize a {#link RecyclerView.Adapter} that listens to a Firebase query. See
* {#link FirebaseRecyclerOptions} for configuration options.
*
* #param options
*/
public LoPdetailsAdapter(#NonNull FirebaseRecyclerOptions<RegisterParking> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull LoPdetailsAdapter.myViewHolder holder, int position, #NonNull RegisterParking model) {
holder.loparkingname.setText(model.getLoparkingname());
holder.lofullname.setText(model.getLofullname());
holder.lorates.setText(model.getLorates());
holder.lovtypes.setText(model.getLovtypes());
holder.loallowed.setText(model.getLoallowed());
holder.loparkingtype.setText(model.getLoparkingtype());
holder.lopenalty.setText(model.getLopenalty());
holder.lonumber.setText(model.getLonumber());
holder.loaddress.setText(model.getLoaddress());
}
#NonNull
#Override
public LoPdetailsAdapter.myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lopdetails_items,parent,false);
return new LoPdetailsAdapter.myViewHolder(view);
}
class myViewHolder extends RecyclerView.ViewHolder{
TextView loparkingname, lofullname, lorates, lovtypes, loallowed, loparkingtype, lopenalty, lonumber, loaddress;
public myViewHolder(#NonNull View itemView) {
super(itemView);
loparkingname = (TextView) itemView.findViewById(R.id.Pname);
lofullname = (TextView) itemView.findViewById(R.id.fullNamelo);
lonumber = (TextView) itemView.findViewById(R.id.contactnoLO);
loaddress = (TextView) itemView.findViewById(R.id.randomAddress);
lorates = (TextView) itemView.findViewById(R.id.Ratelo);
lovtypes = (TextView) itemView.findViewById(R.id.Typeslo);
loallowed = (TextView) itemView.findViewById(R.id.Numberlo);
loparkingtype = (TextView) itemView.findViewById(R.id.Ptypeslo);
lopenalty = (TextView) itemView.findViewById(R.id.PRateslo);
}
}
}
LoParkingDetails.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class LoParkingDetails extends AppCompatActivity {
Toolbar toolbar;
private FirebaseAuth mAuth;
//parkingDetails
RecyclerView recyclerView;
LoPdetailsAdapter loPdetailsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lo_parking_details);
toolbar =(Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
//ParkingDetails
recyclerView = (RecyclerView) findViewById(R.id.loD);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<RegisterParking> options =
new FirebaseRecyclerOptions.Builder<RegisterParking>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("RegParkingArea"), RegisterParking.class)
.build();
loPdetailsAdapter = new LoPdetailsAdapter(options);
recyclerView.setAdapter(loPdetailsAdapter);
}
//ParkingDetails
#Override
protected void onStart() {
super.onStart();
loPdetailsAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
loPdetailsAdapter.stopListening();
}
//Endpoint
lopdetails_items.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="6dp"
android:elevation="6dp"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="412dp"
android:layout_height="360dp"
android:padding="15dp">
<TextView
android:id="#+id/Pname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Parking Name:"
android:textSize="25dp"
android:textStyle="bold" />
<TextView
android:id="#+id/fullNamelo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Pname"
android:text="Landowner Fullname:"
android:textSize="25dp" />
<TextView
android:id="#+id/contactnoLO"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/fullNamelo"
android:text="Phone Number:"
android:textSize="25dp" />
<TextView
android:id="#+id/randomAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/contactnoLO"
android:text="Complete Address:"
android:textSize="25dp" />
<TextView
android:id="#+id/Ratelo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/randomAddress"
android:text="Parking Rates:"
android:textSize="25dp" />
<TextView
android:id="#+id/Typeslo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Ratelo"
android:text="Types of vehicle allowed:"
android:textSize="25dp" />
<TextView
android:id="#+id/Numberlo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Typeslo"
android:text="Number of allowed Vehicle:"
android:textSize="25dp" />
<TextView
android:id="#+id/Ptypeslo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Numberlo"
android:text="Type Parking type:"
android:textSize="25dp" />
<TextView
android:id="#+id/PRateslo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Ptypeslo"
android:text="Penalty Rates:"
android:textSize="25dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>

ScrollView not scroll smoothly

I am developing online store application, i used bottom navigation menu and fragments to separate the pages of my online store , in my main fragment i have one scrollview that contains one image slider and two horizontal recycler views that used to show newest and special products.
every thing id good but
my really strange problem is that when i run application in my android phone the scrollview has really really bad performance, it scrolls really slowly and not smoothly.
i tried many ways to solve this problem ( but unfortunately none of them could solve my problem ) :
- i tried to remove image slider library
- i taught maybe images and bitmaps are the main cause of this bad performance but after i removed all images nothing changed !!!
and here is my code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f6f6f6"
android:layoutDirection="rtl"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/slider_container"
android:layout_width="wrap_content"
android:layout_height="180dp">
<com.daimajia.slider.library.SliderLayout
android:id="#+id/slider"
android:layout_width="match_parent"
android:layout_height="180dp" />
<com.daimajia.slider.library.Indicators.PagerIndicator
android:id="#+id/custom_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<com.rd.PageIndicatorView
android:id="#+id/pageIndicatorView"
app:piv_animationType="worm"
app:piv_dynamicCount="true"
app:piv_interactiveAnimation="true"
app:piv_padding="8dp"
app:piv_radius="4dp"
app:piv_selectedColor="#color/golden_vip"
app:piv_unselectedColor="#d1d1d1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/special_products_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_margin="10dp"
android:background="#f1f1f1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="10dp"
android:text="محصولات ویژه وی آی پی"
android:textColor="#444444"
android:textSize="11sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/volleyball" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/special_products_horizontal_recyclerview"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_below="#+id/special_products_title"
android:isScrollContainer="false"
android:nestedScrollingEnabled="false" />
<RelativeLayout
android:id="#+id/new_products_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/special_products_horizontal_recyclerview"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_margin="10dp"
android:background="#f1f1f1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="10dp"
android:text="محصولات جدید وی آی پی"
android:textColor="#444444"
android:textSize="11sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/volleyball" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/new_products_horizontal_recyclerview"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_marginBottom="700dp"
android:layout_below="#+id/new_products_title"
android:isScrollContainer="false"
android:nestedScrollingEnabled="false" />
</LinearLayout>
</ScrollView>
<RelativeLayout
android:id="#+id/loader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.3"
android:background="#222222"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_load_categories"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminate="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progress_load_categories"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="لطفا منتظر بمانید ..."
android:textColor="#ffffff"
android:textStyle="bold" />
</RelativeLayout>
and here is my fragment :
package com.gladcherry.vipiranian.activityformain;
import android.app.Dialog;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.github.amlcurran.showcaseview.OnShowcaseEventListener;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.gladcherry.vipiranian.Adapter.CategoriesDataAdapter;
import com.gladcherry.vipiranian.Adapter.ProductsDataAdapter;
import com.gladcherry.vipiranian.MaterialSearchViewPersian;
import com.gladcherry.vipiranian.Model.CategoryModel;
import com.gladcherry.vipiranian.Model.DetailsProjectData;
import com.gladcherry.vipiranian.R;
import com.rd.PageIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by gladcherry on 9/30/17.
*/
public class MainViPFragment extends Fragment
implements OnShowcaseEventListener {
ViewPagerEx.OnPageChangeListener
Toolbar mToolbar;
int level = 0;
GridView gridView;
private Button inviteButton;
private static String getCategoriesApiUrl;
private Dialog loader;
private Button ChangeCity, EditProfile;
private ShowcaseView sv;
private FragmentDrawer drawerFragment;
private MaterialSearchViewPersian searchView;
private ProgressBar loadCategories;
RequestQueue queue;
TextView textView;
List<CategoryModel> SliderImages;
//private PageIndicatorView pageIndicatorView;
//private SliderLayout sliderLayout;
private RelativeLayout Loader;
private List<DetailsProjectData> specialProducts = new ArrayList<>();
private List<DetailsProjectData> newProducts = new ArrayList<>();
private ProductsDataAdapter SpecialDataAdapter;
private ProductsDataAdapter NewDataAdapter;
private RecyclerView specialRecyclerView; private RecyclerView newRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.activity_store_categories, container, false);
makeJsonArrayRequest();
return layout;
}
public void createValidation(String title, String msg) {
final Dialog builder = new Dialog(getActivity(), R.style.PauseDialog);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.setTitle(title);
builder.setContentView(R.layout.dialogforvalidations);
TextView text = (TextView) builder.findViewById(R.id.error_msg);
text.setText(msg);
Button close_dialog = (Button) builder.findViewById(R.id.close_btn_dialog);
close_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder.dismiss();
}
});
// display dialog
builder.show();
}
private void makeJsonArrayRequest() {
// Get UserId if current user has been registered or logged in
String UserIdSplash = "";
SharedPreferences prefs = getActivity().getSharedPreferences("Authentication", MODE_PRIVATE);
String userId = prefs.getString("UserName", null);
if (userId != null) {
UserIdSplash = userId;
}
// Get UserId if current user has been registered or logged in
// Get Guest Guid if Guest has been logged in as guest before
String GuidSplash = "";
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Authentication", MODE_PRIVATE);
final String Guid = sharedPreferences.getString("Guid", null);
if (Guid != null) {
GuidSplash = Guid;
}
// Get Guest Guid if Guest has been logged in as guest before
//OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
getCategoriesApiUrl = getResources().getString(R.string.base_url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getCategoriesApiUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String State = response.get("Status").toString();
if (!State.equals("1")) {
Loader.animate().alpha(0.0f).setDuration(500);
createValidation(" خطای سیستم ", response.get("Text").toString());
} else {
Loader.animate().alpha(0.0f).setDuration(500);
SliderImages = new ArrayList<>();
//pageIndicatorView.setCount(response.getJSONArray("Sliders").length());
for (int i = 0; i < response.getJSONArray("Sliders").length(); i++) {
SliderImages.add(
new CategoryModel(
response.getJSONArray("Sliders").getJSONObject(i).get("Image").toString(),
" وی آی پی | ViP ",
response.getJSONArray("Sliders").getJSONObject(i).get("Id").toString())
);
}
JSONArray SpecialProducts = response.getJSONArray("SpecialProducts");
for (int i = 0; i < SpecialProducts.length(); i++) {
JSONObject currentProduct = SpecialProducts.getJSONObject(i);
specialProducts.add(new DetailsProjectData(currentProduct.getString("Id"), currentProduct.getString("PersianName"), currentProduct.getString("Image"), currentProduct.get("UnitPrice").toString(), currentProduct.get("PriceWithDiscount").toString(), currentProduct.get("Discount").toString(), "", "", "", ""));
}
SpecialDataAdapter = new ProductsDataAdapter(getActivity(), specialProducts);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
specialRecyclerView = (RecyclerView) getActivity().findViewById(R.id.special_products_horizontal_recyclerview);
specialRecyclerView.setLayoutManager(layoutManager);
specialRecyclerView.setAdapter(SpecialDataAdapter);
specialRecyclerView.setNestedScrollingEnabled(false);
JSONArray NewProducts = response.getJSONArray("NewestProducts");
for (int i = 0; i < NewProducts.length(); i++) {
JSONObject currentProduct = NewProducts.getJSONObject(i);
newProducts.add(new DetailsProjectData(currentProduct.getString("Id"), currentProduct.getString("PersianName"), currentProduct.getString("Image"), currentProduct.get("UnitPrice").toString(), currentProduct.get("PriceWithDiscount").toString(), currentProduct.get("Discount").toString(), "", "", "", ""));
}
NewDataAdapter = new ProductsDataAdapter(getActivity(), newProducts);
LinearLayoutManager newlayoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
newRecyclerView = (RecyclerView) getActivity().findViewById(R.id.new_products_horizontal_recyclerview);
newRecyclerView.setLayoutManager(newlayoutManager);
newRecyclerView.setAdapter(NewDataAdapter);
newRecyclerView.setNestedScrollingEnabled(false);
}
}
catch (Exception ex)
{
if (ex.getMessage() != null) {
Log.d("exception", ex.getMessage());
}
Loader.animate().alpha(0.0f).setDuration(500);
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
if (error != null && error.getMessage() != null) {
Log.w("VolleyError", error.getMessage());
VolleyLog.d(this.getClass().getSimpleName(), "Error: " + error.getMessage());
}
//loadCategories.setVisibility(View.GONE);
createValidation("پیام سیستم", "لطفا اتصال اینترنت خود را بررسی نمایید .");
}
});
request.setRetryPolicy(new
DefaultRetryPolicy(10000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(request);
}
#Override
public void onShowcaseViewHide(ShowcaseView showcaseView) {
}
#Override
public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
}
#Override
public void onShowcaseViewShow(ShowcaseView showcaseView) {
}
#Override
public void onShowcaseViewTouchBlocked(MotionEvent motionEvent) {
}
}
the problem was because of 2 lines that i was added to the manifest to prevent from android out of memory exception ...
remove these two lines and every thing well be ok :
android:largeHeap="true"
android:hardwareAccelerated="false"
i hope this answer going to help you ...
do the height of relative layout ="wrap_content" instead of match parent , also of scrollview.

Android Fragments - Edit Text Of Another Fragment

So I have made a simple heating text control app and it all works with permissions and all of that but it uses 2 fragments and inside them are two textboxes which I want to have the same text in -- phone number. I cannot get the edittext in rel2 to be changed by rel1.
Rel 1:
package com.danielkern.relswitcher;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.SmsManager;
import static android.content.SharedPreferences.*;
/**
* Created by Daniel Kern on 03/01/2018.
*/
public class Rel1 extends Fragment{
Button BtnHOFF, BtnHON, BtnHST, saveB;
EditText txtPhoneNo;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rel1, container, false);
final View view2 = inflater.inflate(R.layout.rel2, container, false);
final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
String savedNo = sharedPref.getString("phoneNo", "07599070551");
BtnHOFF = (Button) view.findViewById(R.id.Hoff);
BtnHON = (Button) view.findViewById(R.id.Hon);
BtnHST = (Button) view.findViewById(R.id.Hstatus);
txtPhoneNo = (EditText) view.findViewById(R.id.editText);
saveB = (Button) view.findViewById(R.id.saveB);
((EditText) view.findViewById(R.id.editText)).setText(savedNo);
Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
BtnHOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL1=ON", txtPhoneNo.getText().toString());
}
});
BtnHON.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL1=OFF", txtPhoneNo.getText().toString());
Log.i(getActivity().toString(), "Done!");
}
});
BtnHST.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#STATUS", txtPhoneNo.getText().toString());
}
});
saveB.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
Log.i("me", "Saved!");
Toast.makeText(getActivity().getApplicationContext(),
"Saved!",
Toast.LENGTH_LONG).show();
((EditText) view2.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
}
});
return view;
}
public void sendMsg(String msg, String num){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, msg, null, null);
Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(),
"SMS failed, contact administrator!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
}
}
Rel 2:
package com.danielkern.relswitcher;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Daniel Kern on 03/01/2018.
*/
public class Rel2 extends Fragment {
Button BtnWOFF, BtnWON, BtnWST, saveB;
EditText txtPhoneNo;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rel2, container, false);
final View view1 = inflater.inflate(R.layout.rel1, container, false);
final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
String savedNo = sharedPref.getString("phoneNo", "07599070551");
BtnWOFF = (Button) view.findViewById(R.id.Woff);
BtnWON = (Button) view.findViewById(R.id.Won);
BtnWST = (Button) view.findViewById(R.id.Wstatus);
saveB = (Button) view.findViewById(R.id.saveB);
txtPhoneNo = (EditText) view.findViewById(R.id.editText);
((EditText) view.findViewById(R.id.editText)).setText(savedNo);
Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
BtnWOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL2=ON", txtPhoneNo.getText().toString());
}
});
BtnWON.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#REL2=OFF", txtPhoneNo.getText().toString());
}
});
BtnWST.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sendMsg("#STATUS", txtPhoneNo.getText().toString());
}
});
saveB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
((EditText) view1.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
Log.d("me", "Saved!");
}
});
return view;
}
public void sendMsg(String msg, String num){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, msg, null, null);
Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(),
"SMS failed, contact administrator!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
}
}
Rel 1 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/Hon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:text="Heating ON (REL1 OFF)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Hoff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Hon"
android:layout_marginTop="13dp"
android:text="Heating OFF (REL1 ON)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Hstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Hoff"
android:layout_marginTop="15dp"
android:text="STATUS"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texts"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp"
android:text="Coming Soon!"
android:textSize="24sp" />
<EditText
android:id="#+id/editText"
android:text="07599070551"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/saveB"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/editText"
android:layout_alignBottom="#+id/editText"
android:layout_alignParentEnd="true"
android:text="Save" />
</RelativeLayout>
Rel 2 XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="#+id/Won"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="44dp"
android:text="Water ON (REL2 OFF)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Woff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Won"
android:layout_marginTop="13dp"
android:text="Water OFF (Rel2 On)"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/Wstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/Woff"
android:layout_marginTop="15dp"
android:text="STATUS"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texts"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="46dp"
android:text="Coming Soon!"
android:textSize="24sp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/saveB"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/editText"
android:layout_alignBottom="#+id/editText"
android:layout_alignParentEnd="true"
android:text="Save" />
</RelativeLayout>
EDIT:
I would like the edit text in Rel2 to change when I press save in rel1 therefore the phone number boxes will always be the same.
rel1
EDIT 2:
I have fixed the shared prefs issue but I would still like to know if anyone can make the textboxes the same wherether that is on text update or on save button press.
There are two ways you can do this.
Using Interface
Create an interface with a method something like TextChangeListener and declare a method onTextChange(String text).
interface TextChangeListener{
void onTextChange(String number);
}
Implement the interface in the HostActivity
class HostActivity extends Activity implements TextChangeListener{
...
void onTextChange(String number){
secondFragment.updateNumber(number)
}
...
}
In FirstFragment call the activity using the implmented interface in the afterTextChanged() listener of TextWatcher
class FirstFragment extends Fragment{
private TextChangeListener activity;
#Override
public onAttach(Context context){
if(context instanceof TextChangeListener){
activity = (TextChangeListener) context;
}
}
phNumEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
activity.onTextChange(s.toString);
}
...
);
...
}
In SecondFragment on receiving the call from activity, update the EditText with new data.
class SecondFragment extends Fragment{
...
public void updateNumber(String number){
editText.setText(number);
}
}
Using EventBus
Use EventBus to post an event from FirstFragment. The event will contain the data to be populated in SecondFragment. The SecondFragment will Subscribe to the event and on receiving the event the data will be populate into the EditText.

XML files contain code, but preview is blank

so i have a project where im implementing a google sign in, i followed this tutorial on how to do that, but when i did, all my XML files appear blank. i made changes to the original MainActivity.java and the activity_main.xml file. i woudl think that only the activity_main.xml would be affected, but all of my XML files appear blank. when i try to run the app, i get
"Error:Content is not allowed in prolog.
" and
"Execution failed for task '.app:builderInfoDebugLoader'"
this is my activity main where i implement the google sign in:
package com.example.mayankthakur.personalprojecttrial2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.api.signin.SignInAccount;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private LinearLayout prof_section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Picture;
private Button continueBut;
private static final int REQ_CODE = 9001;
String name;
Intent nameSave;
private GoogleApiClient mGoogleApiClient;
public static final String prefsName = "com.example.mayankthakur.personalprojecttrial2";
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
prof_section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.logoutBtn);
SignIn = (SignInButton) findViewById(R.id.gSignIn);
Name = (TextView) findViewById(R.id.nameSpace);
Email = (TextView) findViewById(R.id.emailSpace);
Prof_Picture = (ImageView) findViewById(R.id.profilePicture);
continueBut = (Button) findViewById(R.id.button2);
continueBut.setOnClickListener(this);
SignOut.setOnClickListener(this);
SignIn.setOnClickListener(this) ;
prof_section.setVisibility(View.GONE);
continueBut.setVisibility(View.GONE);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
#Override
public void onClick (View v) {
switch (v.getId()) {
case R.id.gSignIn:
signIn();
break;
case R.id.logoutBtn:
signOut();
break;
/*// This is the shared preference
SharedPreferences.Editor prefs = getSharedPreferences(prefsName, MODE_PRIVATE).edit();
//adding a value to the preference
prefs.putString("name", name);
prefs.apply();
nameSave = new Intent(MainActivity.this, Activity2.class);
MainActivity.this.startActivity(nameSave);
*/
}
}
#Override
public void onConnectionFailed (#NonNull ConnectionResult connectionResult){
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, REQ_CODE );
}
private void signOut(){
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void handleReuslt(GoogleSignInResult result){
if(result.isSuccess())
{
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
String imgUrl = acct.getPhotoUrl().toString();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Name.setText(personName);
Email.setText(personEmail);
Glide.with(this).load(imgUrl).into(Prof_Picture);
updateUI(true);
}
else
{
updateUI(false);
}
}
private void updateUI(boolean isLogin){
if(isLogin)
{
prof_section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
}
else
{
prof_section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleReuslt(result);
}
}
}
this is my XML file where i added the buttons and stuff for the google sign in:\
<?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:id="#+id/activity_main"
android:orientation="vertical"
tools:context="com.example.mayankthakur.personalprojecttrial2.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/prof_section"
android:layout_marginLeft="20dp"
android:layout_marginTop = "50dp"
android:weightSum="1">
<ImageView
android:id="#+id/profilePicture"
android:layout_width="90dp"
android:layout_height="100dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:src="#drawable/photo"
android:layout_weight="0.25" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp">
<TextView
android:id="#+id/nameSpace"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name Display"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/emailSpace"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Email Display"
android:textSize="14dp"
android:textStyle="bold" />
<Button
android:id="#+id/logoutBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/gSignIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp">
</com.google.android.gms.common.SignInButton>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please Sign in in order to make use of all of the features of the app"
android:textAlignment="center"
android:textSize="20dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Continue"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"/>
</LinearLayout>
any help would be greatly appreciated, and if any of you require any more code please do ask
thanks in advance!

onActivityResult in fragment doesn't update edittext

I have a sample barcode scanner app using this library.
onActivityResult does not update the textView nor editText.
I did some search around and noticed that this is a common problem.
onActivityResult i get my value that i pass through, i can log and toast the value but does not work on setText() method.
Edit: I'm using fragments.
Fragment A is where the button, edit & textview are, Fragment B is the barcode scanner and i use popBackStack() to return to fragment A(received data from Fragment B);
Here is my code:
package com.gilbert.apptastic.barcodefragment;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public static final int DIALOG_FRAGMENT = 1;
public TextView textView;
public TextView textView2;
public TextView textView3;
public TextView textView4;
public EditText editText;
public Button button;
public String barcode;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
textView = (TextView)rootView.findViewById(R.id.textView);
textView2 = (TextView)rootView.findViewById(R.id.textView2);
textView3 = (TextView)rootView.findViewById(R.id.textView3);
textView4 = (TextView)rootView.findViewById(R.id.textView4);
editText = (EditText)rootView.findViewById(R.id.editText);
button = (Button)rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBarcode();
}
});
// setText();
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_FRAGMENT && resultCode == Activity.RESULT_OK) {
// System.out.println("ok");
barcode = data.getExtras().getString("barcode");
// edit_barcode.setText(value);
setText();
Toast.makeText(getActivity(), barcode, Toast.LENGTH_SHORT).show();
// System.out.println(barcode);
// edit_barcode.setText(barcode);
}
}
public void setText() {
System.out.println(barcode);
textView.setText(barcode);
textView2.setText(barcode);
textView3.setText(barcode);
textView4.setText(barcode);
editText.setText(barcode);
}
public void scanBarcode(){
Barcode barcode = new Barcode();
barcode.setTargetFragment(PlaceholderFragment.this, DIALOG_FRAGMENT);
FragmentTransaction fragmentTransaction =
getActivity().getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, barcode);
fragmentTransaction.addToBackStack("VIEW");
fragmentTransaction.commit();
}
}
Barcode Class:
package com.gilbert.apptastic.barcodefragment;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
public class Barcode extends Fragment implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mScannerView = new ZBarScannerView(getActivity());
return mScannerView;
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void handleResult(Result rawResult) {
if(!rawResult.getContents().isEmpty()){
mScannerView.startCamera();
// Toast.makeText(getActivity(),"Success",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("barcode", rawResult.getContents());
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
getFragmentManager().popBackStack();
}else {
// Toast.makeText(getActivity(),"Fail",Toast.LENGTH_SHORT).show();
getFragmentManager().popBackStack();
mScannerView.startCamera();
}
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera();
}
}
my layout file:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Scan"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_above="#+id/button">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView4"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:hint="Barcode"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Try these
1 ) Instead of
barcode = data.getExtras
try
barcode = data.getStringExtra("barcode")
2) Instead of initiating barcode
String barcode;
Try doing this in your onActivityResult,
String barcode = data.getExtras().getString("barcode");
3 ) Instead of putting data directly into intent, use a bundle.
Bundle b = new Bundle();
b.putString ("barcode", rawResult.getContent());
Intent i = new intent();
i.putExtras (b);
In your onActivityResult
Bundle b = getIntent.getExtras();
String s = b.getString("barcode");
Then use s where you need it.

Categories