• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • About
  • Life
  • Tech
  • Travel
  • Work
  • Questions
  • Contact

Welcome

.

Passing data between two fragments whrough asynctask

April 10, 2020 by

Questions › Passing data between two fragments whrough asynctask
0
Vote Up
Vote Down
Garmaine asked 3 years ago

I have just started out with Java development(android app) and I stumbled upon a problem I don't know how to solve.

So I have two fragments: 1) Fragment with barcode scanner 2) Fragment with just a simple textview

The app should be able to scan barcode, get API response based on the scan result, deserialize it into a Java object and then show value of one variable in the textview located in the second fragment.

I have already implemented the barcode scanner and class to get data from API and turn it into a Java object. The problem is that I can't find a way to send the barcode result to the class that handles the API data retrieval and also how to send the object to the second fragment.

Can someone please direct me in the right way on how to implement it correctly?

1)Barcode fragment

public class BarcodeFragment extends Fragment  {
private CodeScanner mCodeScanner;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {

    final Activity activity = getActivity();
    View root = inflater.inflate(R.layout.barcode_fragment, container, false);
    CodeScannerView scannerView = root.findViewById(R.id.scanner_view);
    mCodeScanner = new CodeScanner(activity, scannerView);
    mCodeScanner.setDecodeCallback(new DecodeCallback() {
        @Override
        public void onDecoded(@NonNull final Result result) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(activity.getApplicationContext(), result.getText(), Toast.LENGTH_SHORT).show();

                }
            });

        }

    });

    scannerView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mCodeScanner.startPreview();

        }
    });
    return root;
}


@Override
public void onResume() {
    super.onResume();
    mCodeScanner.startPreview();
}

@Override
public void onPause() {
    mCodeScanner.releaseResources();
    super.onPause();
}

}

2) Class to get data from API and turn it into JAVA object

public class RetrieveFeedTask extends AsyncTask<Void, Void, String> {

Product productFromDatabase;
String resultString;

public RetrieveFeedTask(String barcodeResult){
    resultString = barcodeResult;
}

protected void onPreExecute() {

}

protected String doInBackground(Void... urls) {

    try {
        URL url = new URL("https://api.appery.io/rest/1/apiexpress/api/example/Products?apiKey=12345678&Barcode=" + resultString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            bufferedReader.close();

            return stringBuilder.toString();
        }
        finally{
            urlConnection.disconnect();
        }
    }
    catch(Exception e) {
        Log.e("ERROR", e.getMessage(), e);
        return null;
    }
}

protected void onPostExecute(String response) {


    if(response == null) {
        response = "THERE WAS AN ERROR";
    }

    Log.i("INFO", response);

     deSerializeProduct(response);

}

public void deSerializeProduct(String response){
    response = response.substring(1,response.length() - 3);

    StringBuilder stringBuilder = new StringBuilder(response);

    stringBuilder.append(",\"productId\":\"23323123sdasd\"}"); // for testing
    String responseToDeSerialize = stringBuilder.toString();


    ObjectMapper mapper = new ObjectMapper();

    try {

        productFromDatabase = mapper.readValue(responseToDeSerialize, Product.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

3) Cart fragment class where to name of the object should appear in the textview

public class CartFragment extends Fragment  {

static TextView showReceivedData;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    // Defines the xml file for the fragment
    View view = inflater.inflate(R.layout.cart_fragment, parent, false);
    showReceivedData = (TextView) view.findViewById(R.id.resultCode);
    return view;

}

}

Are you looking for the answer?
Original Question and Possible Answers can be found on `http://stackoverflow.com`

Question Tags: android, android-fragments, android-studio, java

Please login or Register to submit your answer




Primary Sidebar

Tags

Advancements architecture beautiful life best building calling city commercial convenience employment Finances Cognitive decline Future gadgets Hidden Gems highway Home houses hydration Impact Innovations lamp lighting Mental health military tech Must-See New York City occupation Productivity recreation romance sepia shopping sippy cups smartphones social Technological breakthroughs technology toddlers Treasures turns Uncover Well-being Wonders Work Young onset dementia

Newsletter

Complete the form below, and we'll send you all the latest news.

Footer

Footer Funnies

Who knew that reading the footer could be such a hilarious adventure? As we navigate websites, books, and documents, we often stumble upon the unassuming space at the bottom, only to discover a treasure trove of amusement. In this side-splitting compilation, we present 100 jokes that celebrate the unsung hero of content – the footer. Get ready to chuckle, giggle, and maybe even snort as we dive into the world of footnotes, disclaimers, and hidden comedic gems. Brace yourself for a wild ride through the footer!

Recent

  • Unveiling the Enigma: Almost-Magical Lamp Lights Highway Turns
  • The Impact of Young Onset Dementia on Employment and Finances: Optimizing Post-Diagnostic Approaches
  • 11 Wonders of 2023 Technological Breakthrough – Unveiling the Future
  • Work from Home and Stay Mentally Sane – Achieve Productivity and Well-being
  • Hidden Gems of New York City – Uncover the Must-See Treasures!

Search

Tags

Advancements architecture beautiful life best building calling city commercial convenience employment Finances Cognitive decline Future gadgets Hidden Gems highway Home houses hydration Impact Innovations lamp lighting Mental health military tech Must-See New York City occupation Productivity recreation romance sepia shopping sippy cups smartphones social Technological breakthroughs technology toddlers Treasures turns Uncover Well-being Wonders Work Young onset dementia

Copyright © 2023