0

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;

}

}
Anil Nivargi
  • 1,473
  • 3
  • 27
  • 34

2 Answers2

0

The asynctask shouldn't outlive the lifecycle of the activity or fragment that starts it. I'm assuming you probably will display some sort of loading status while the network request happens. Here are some options:

  • If the two fragments are in the same activity, you could pass the result of the scan to the activity, kick off the network request, swap fragments, and send the request result to the second fragment.

  • The scanner fragment can get the barcode data, kick off the request, show the loading state, and when the result returns, package in the bundle, which the second fragment can read.

  • Invert the previous model, if it fits your app better, and send just the barcode result in the bundle, and have the second fragment kick off the request while displaying the loading status.

The exact choice will depend on the flow and structure of your app. Additionally, you may want to look into using another multithreading option instead of asynctask, as it has been deprecated and Google is trying to move developers away from it. Some alternatives are the Java concurrency library, RxJava, or if you are willing to use Kotlin in your project, Kotlin coroutines.

RedBassett
  • 3,469
  • 3
  • 32
  • 56
0

Use Bundle to add pass data between Activity and fragments

try This code to Pass data between two fragments

      Bundle bundle=new Bundle();
            bundle.putString("scanner_data","myData");
            Fragment fragment=new HomeFragment();
            fragment.setArguments(bundle);
            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
            ft.add(R.id.framContainer, fragment, "TAg");
            ft.commit();

How to get data

Bundle bundle=getArguments();
Android Geek
  • 8,956
  • 2
  • 21
  • 35