Cannot transfer downloaded data from activity to fragment using bundle in android - android

I have been trying to pass some downloaded content from my activity to fragment in vain. I've broken up the steps to see where the error pops up and have made a few conclusions: (i) switching between fragment and activity and vice versa works fine.
(ii) Problem arises only when I enter some data and try to pass it to the fragment from the activity using a bundle.
Here is my fragment code:
package com.antojoh.bottomnavig;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link ShopFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link ShopFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ShopFragment 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";
static ArrayList<String> arrayList = new ArrayList<String>();
static ArrayAdapter<String> arrayAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public ShopFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ShopFragment.
*/
// TODO: Rename and change types and number of parameters
public static ShopFragment newInstance(String param1, String param2) {
ShopFragment fragment = new ShopFragment();
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) {
View view = inflater.inflate(R.layout.fragment_shop, container, false);
ListView listView = (ListView) view.findViewById(R.id.list);
arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_checked, arrayList);
listView.setAdapter(arrayAdapter);
CardView cardView = (CardView) view.findViewById(R.id.cardView);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), BarcodeActivity.class);
startActivity(intent);
}
});
Bundle bundle = this.getArguments();
if (bundle != null){
String value = bundle.getString("coder");
arrayList.add(value);
arrayAdapter.notifyDataSetChanged();
}
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context, "Shop Fragment", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Here is my Activity Code :
package com.antojoh.bottomnavig;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BarcodeActivity extends AppCompatActivity {
SurfaceView cameraPreview;
private EditText editText;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestCameraPermissionID: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
editText = (EditText) findViewById(R.id.editText);
cameraPreview = (SurfaceView) findViewById(R.id.cameraPreview);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.UPC_A | Barcode.UPC_E | Barcode.EAN_8 | Barcode.EAN_13 | Barcode.CODE_128 | Barcode.CODE_39 | Barcode.CODE_93 | Barcode.ISBN | Barcode.ITF)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.setAutoFocusEnabled(true)
.build();
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(BarcodeActivity.this, new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
}catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0){
update(qrcodes.valueAt(0).rawValue);
}
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result="";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
public void update(String string) {
String result = "";
DownloadTask task = new DownloadTask();
try {
result = task.execute("https://www.barcodable.com/ean/" + string).get();
} catch (Exception e) {
e.printStackTrace();
}
Pattern p = Pattern.compile("<title>UPC (.*?)</title>");
Matcher m = p.matcher(result);
while (m.find()) {
if (m.group(1) != null) {
Bundle bundle = new Bundle();
bundle.putString("coder", m.group(1));
ShopFragment shopFragment = new ShopFragment();
shopFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.cont, shopFragment).commit();
}
}
}
public void enter(View view){
update(editText.getText().toString());
}
}
And the Logcat :
08-14 14:46:03.037 5419-5460/com.antojoh.bottomnavig W/System.err: java.io.FileNotFoundException: https://www.barcodable.com/ean/9781614272137
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
at com.antojoh.bottomnavig.BarcodeActivity$DownloadTask.doInBackground(BarcodeActivity.java:144)
at com.antojoh.bottomnavig.BarcodeActivity$DownloadTask.doInBackground(BarcodeActivity.java:134)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
08-14 14:46:03.038 5419-5460/com.antojoh.bottomnavig W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
08-14 14:46:03.041 5419-5419/com.antojoh.bottomnavig E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antojoh.bottomnavig, PID: 5419
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
at java.util.regex.Matcher.reset(Matcher.java:995)
at java.util.regex.Matcher.<init>(Matcher.java:174)
at java.util.regex.Pattern.matcher(Pattern.java:1006)
at com.antojoh.bottomnavig.BarcodeActivity.update(BarcodeActivity.java:171)
at com.antojoh.bottomnavig.BarcodeActivity.enter(BarcodeActivity.java:190)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

It was simple. The website did not accept too many requests at a time( which I did). So all i had to do was either switch to another website or wait for a specific time to gain entry for requesting access again! Thanks!

Related

Why doesn't this class return the JSON data from given URL?

The class that I have made does not fetch data from the given URL which I have as a String. In a static initializer I make a URL from the String, and then getResponseFromHttpUrl method should have returned the JSON data as a String. However my Log.d("jsondata") don't show anything at all and my app crashes.
package com.example.android.bakingapp;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class RecipeJson {
public static final String url = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json";
public static URL urlBuilt;
public static String jsonData;
static {
try {
urlBuilt = buildUrl();
jsonData = getResponseFromHttpUrl(urlBuilt);
Log.d("jsondata", jsonData);
} catch (Exception e) {
e.printStackTrace();
}
}
public static URL buildUrl() throws java.net.MalformedURLException {
return new URL(url);
}
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
}
Here are the app logs:
08-07 20:59:54.776 26319-26319/com.example.android.bakingapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.bakingapp, PID: 26319
java.lang.ExceptionInInitializerError
at com.example.android.bakingapp.RecipeListFragment.onCreateView(RecipeListFragment.java:68)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3248)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3200)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:195)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:597)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1382)
at android.app.Activity.performStart(Activity.java:7151)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:2949)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:194)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:180)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:157)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:72)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1800)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
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:826)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONArray.<init>(JSONArray.java:92)
at org.json.JSONArray.<init>(JSONArray.java:108)
at com.example.android.bakingapp.dummy.DummyContent.makeJsonArray(DummyContent.java:55)
at com.example.android.bakingapp.dummy.DummyContent.<clinit>(DummyContent.java:28)
The culprit is this line:
jsonArray = new JSONArray(RecipeJson.jsonData);
Which means the problem is really with my class. But what is the source of the problem?
Edit: Here is the RecipeListFragment code
package com.example.android.bakingapp;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.android.bakingapp.dummy.DummyContent;
import com.example.android.bakingapp.dummy.DummyContent.DummyItem;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {#link OnListFragmentInteractionListener}
* interface.
*/
public class RecipeListFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
int dp;
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public RecipeListFragment() {
}
public static RecipeListFragment newInstance(int columnCount) {
RecipeListFragment fragment = new RecipeListFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
dp = config.smallestScreenWidthDp;
if (dp < 600) mColumnCount = 1;
else mColumnCount = 3;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recipelist_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyRecipeListRecyclerViewAdapter(DummyContent.ITEMS, mListener));
}
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction(DummyItem item);
}
}

Barcode Fragment "invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference"

I'm trying to use the ZXing library for make a Bar Code scan in a Fragment.
I have successful imported the library but when I choose from the APP this Fragment the APP crash with the following traceback:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.fastnetserv.barcodeapp.Barcode.onResume(Barcode.java:86)
at android.support.v4.app.Fragment.performResume(Fragment.java:2020)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1107)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
And here the Fragment code
package com.fastnetserv.barcodeapp;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.content.Intent;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Barcode.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Barcode#newInstance} factory method to
* create an instance of this fragment.
*/
public class Barcode extends Fragment implements OnClickListener {
// 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 OnFragmentInteractionListener mListener;
public Barcode() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Barcode.
*/
// TODO: Rename and change types and number of parameters
public static Barcode newInstance(String param1, String param2) {
Barcode fragment = new Barcode();
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);
}
}
private Button scanBtn;
private TextView formatTxt, contentTxt;
#Override
public void onResume() {
super.onResume();
//instantiate button, text, content
scanBtn = (Button) getActivity().findViewById(R.id.scan_button);
formatTxt = (TextView) getActivity().findViewById(R.id.scan_format);
contentTxt = (TextView) getActivity().findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mListener = (OnFragmentInteractionListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
}else{
Toast toast = Toast.makeText(getActivity(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onClick(View v) {
//respond to clicks
if(v.getId()==R.id.scan_button){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.initiateScan();
}
}
}
What I've missing or what I'm doing wrong?
You haven't defined any view for your fragment, so it is unable to find that relevant id thus resulting in Null Pointer Exception. Override onCreateView() method in your fragment and provide a view in that and then write your findViewById code in this method like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout, container, false);
btn_name= (Button) view.findViewById(R.id.your_button_id);
return view;
}
You can't instantiate view using getActivity() in Fragment.
You have to do like below and remove instantiation from onResume():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
scanBtn = (Button) view.findViewById(R.id.scan_button);
formatTxt = (TextView) view.findViewById(R.id.scan_format);
contentTxt = (TextView) view.findViewById(R.id.scan_content);
scanBtn.setOnClickListener(this);
return view;
}

Android Studio - PDF Render Fragment code java

Hello, I have an error when I click on my link that allows me to display my work that contains my pdf
PDFRenderFragement the class is imported from another project. In this project the class is functional. The import of this project gave me this.
Activity PDFRenderFragment
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
public class PDFRenderFragment extends Fragment {
private ParcelFileDescriptor fileDescriptor;
private PdfRenderer pdfRenderer;
private PdfRenderer.Page currentPage;
private ImageView image;
private Button btnPrevious;
private Button btnNext;
public PDFRenderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.affichage_pdf, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Retain view references.
image = (ImageView) view.findViewById(R.id.image);
btnPrevious = (Button) view.findViewById(R.id.btn_previous);
btnNext = (Button) view.findViewById(R.id.btn_next);
//set buttons event
btnPrevious.setOnClickListener(onActionListener(-1)); //previous button clicked
btnNext.setOnClickListener(onActionListener(1)); //next button clicked
int index = 0;
// If there is a savedInstanceState (screen orientations, etc.), we restore the page index.
if (null != savedInstanceState) {
index = savedInstanceState.getInt("current_page", 0);
}
showPage(index);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
openRenderer(activity);
} catch (IOException e) {
e.printStackTrace();
Log.i("Fragment", "Error occurred!");
Log.e("Fragment", e.getMessage());
activity.finish();
}
}
#Override
public void onDestroy() {
try {
closeRenderer();
} catch (IOException e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != currentPage) {
outState.putInt("current_page", currentPage.getIndex());
}
}
/**
* Create a PDF renderer
* #param activity
* #throws IOException
*/
private void openRenderer(Activity activity) throws IOException {
// Reading a PDF file from the assets directory.
fileDescriptor = activity.getAssets().openFd("Protocole.pdf").getParcelFileDescriptor();
// This is the PdfRenderer we use to render the PDF.
pdfRenderer = new PdfRenderer(fileDescriptor);
}
/**
* Closes PdfRenderer and related resources.
*/
private void closeRenderer() throws IOException {
if (null != currentPage) {
currentPage.close();
}
pdfRenderer.close();
fileDescriptor.close();
}
/**
* Shows the specified page of PDF file to screen
* #param index The page index.
*/
private void showPage(int index) {
if (pdfRenderer.getPageCount() <= index) {
return;
}
// Make sure to close the current page before opening another one.
if (null != currentPage) {
currentPage.close();
}
//open a specific page in PDF file
currentPage = pdfRenderer.openPage(index);
// Important: the destination bitmap must be ARGB (not RGB).
Bitmap bitmap = Bitmap.createBitmap(currentPage.getWidth(), currentPage.getHeight(),
Bitmap.Config.ARGB_8888);
// Here, we render the page onto the Bitmap.
currentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// showing bitmap to an imageview
image.setImageBitmap(bitmap);
updateUIData();
}
/**
* Updates the state of 2 control buttons in response to the current page index.
*/
private void updateUIData() {
int index = currentPage.getIndex();
int pageCount = pdfRenderer.getPageCount();
btnPrevious.setEnabled(0 != index);
btnNext.setEnabled(index + 1 < pageCount);
getActivity().setTitle(getString(R.string.app_name, index + 1, pageCount));
}
private View.OnClickListener onActionListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i < 0) {//go to previous page
showPage(currentPage.getIndex() - 1);
} else {
showPage(currentPage.getIndex() + 1);
}
}
};
}
Activity ProtoMain
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.LinearLayout;
public class ProtoMain extends FragmentActivity {
private View btnRender;
private LinearLayout container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.proto_main);
//find view by id
btnRender = (View)findViewById(R.id.btn_render);
container = (LinearLayout)findViewById(R.id.fragment_layout);
//set event handling for button
btnRender.setOnClickListener(onClickListener());
}
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
//replace fragment when clicked
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_layout, new PDFRenderFragment());
ft.commit();
//gone button after all
btnRender.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
}
};
}
Logcat report:
04-13 16:53:50.250 306-1625/? E/AudioMixer: setEqBand
04-13 16:53:50.301 10104-10104/? E/Fragment: not create document. Error:
04-13 16:53:50.335 10104-10104/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sergehuby.seriers232, PID: 10104
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.pdf.PdfRenderer.getPageCount()' on a null object reference
at com.example.sergehuby.seriers232.PDFRenderFragment.showPage(PDFRenderFragment.java:118)
at com.example.sergehuby.seriers232.PDFRenderFragment.onViewCreated(PDFRenderFragment.java:55)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1086)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5319)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1016)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
04-13 16:53:50.465 285-285/? E/lowmemorykiller: Error writing /proc/10104/oom_score_adj; errno=22
04-13 16:53:50.472 865-1077/? E/InputDispatcher: channel '158b3e48 com.example.sergehuby.seriers232/com.example.sergehuby.seriers232.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
04-13 16:53:50.764 10668-10695/? E/CrashMonitor: DropBoxHandler: crashhandler store:

Grid-view is not formed in horizontal-scrolling-pages like home screen when app is in Background or Process is died

I am developing Horizontal Scrolling pages and tabs
MY app is working well in all devices in foreground, but when it goes to background, after one hour, the logs saying that Process com.example.myapp has died. When i reopen the app , the gridview data is not appearing but when scrolling horizontally , getView() method displaying all data like images and text.
that means app has data but view is not formed when process has died. And if i press back button and re-open the app, It is working good
My MainActivity.java is here
package com.bbgusa.bbgdemo.ui.phone;
import java.util.List;
import java.util.Vector;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TabHost;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.listener.phone.CustomViewPager;
import com.bbgusa.bbgdemo.ui.chat.phone.ChatFragmentTab;
import com.bbgusa.bbgdemo.ui.dialpad.phone.DialerFragment;
import com.bbgusa.bbgdemo.ui.home.phone.AlarmFragmentPhone;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragment;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragmentTab;
import com.bbgusa.bbgdemo.ui.home.phone.InfoFragPhone;
import com.bbgusa.bbgdemo.ui.home.phone.MapPhone;
import com.bbgusa.bbgdemo.ui.home.phone.WeatherFragmentPhone;
import com.bbgusa.bbgdemo.ui.messages.phone.MessagesFragment;
import com.bbgusa.bbgdemo.ui.settings.phone.AboutFragment;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentChangedListenerPhone;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
public class MainActivity extends FragmentActivity implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, OnFragmentChangedListenerPhone {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_phone);
this.initialiseTabHost(savedInstanceState);
initialiseViewPager();
}
/**
* Initialise ViewPager
*/
private void initialiseViewPager() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,HomeFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, DialerFragment.class.getName()));
fragments.add(Fragment.instantiate(this,MessagesFragment.class.getName()));
fragments.add(Fragment.instantiate(this,ChatFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, AboutFragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
this.mViewPager = (CustomViewPager) findViewById(R.id.tabviewpager);
this.mViewPager.setAdapter(this.mPagerAdapter);
this.mViewPager.setOnPageChangeListener(this);
this.mViewPager.setOffscreenPageLimit(5);
this.mViewPager.setCurrentItem(0);
}
#Override
public void onFragmentChangePhone(JSONObject response, String whichView, String title, String mPhoneNo) {
Bundle b = new Bundle();
if(response != null)
b.putString("JSONObject", response.toString());
if(title != null)
b.putString("Title", title);
String propertyId = UConnectUtils.getPropertyId(mPref, getString(R.string.property_id));
b.putString(UConnectUtils.PROPERTY_ID_KEY, propertyId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = null;
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
// getSupportFragmentManager().popBackStack();
fragment = new HomeFragment();
} else if (whichView.equals(ConstantsManager.WEATHER)) {
fragment = new WeatherFragmentPhone();
}else if (whichView.equals(ConstantsManager.ALARM)) {
fragment = new AlarmFragmentPhone();
}else if (whichView.equals(ConstantsManager.MAPS)) {
fragment = new MapPhone();
}else if (whichView.equals(ConstantsManager.HELP)) {
fragment = new InfoFragPhone();
}
if (whichView.equals(ConstantsManager.MAPS)) { // to show plus-icon on map top right corner
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, "", View.VISIBLE);
} else if (!whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, mPhoneNo, View.GONE);
}
fragment.setArguments(b);
ft.add(R.id.main_home_frag, fragment);
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
fragmentManager.popBackStack();
} else {
ft.addToBackStack(fragment.toString());
}
ft.commit();
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
}
}
and my HomeFragmentTab.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentTabChangedListener;
#SuppressLint("NewApi")
public class HomeFragmentTab extends Fragment implements OnFragmentTabChangedListener{
private static final String TAG = HomeFragmentTab.class.getSimpleName();
private static HomeFragmentTab tab;
private MainActivity activityPhone;
public static HomeFragmentTab getInstance() {
return tab;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activityPhone = (MainActivity) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
if (container == null) {
return null;
}
Log.i(TAG, "onCreateView");
v = inflater.inflate(R.layout.hometab_phone, container, false);
tab = this;
activityPhone.onFragmentChangePhone(null, ConstantsManager.GRIDVIEWPAGER, getResources().getString(R.string.app_name), "");
return v;
}
#Override
public void onFragmentTabChange(int i, String title, String mPhoneNo, int mapV) {
}
}
and HomeFragment.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.ImageCacheManager;
import com.bbgusa.bbgdemo.ui.cms.tablet.TestTopics;
import com.bbgusa.bbgdemo.ui.cms.tablet.TopicList;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.onGridViewVisibilityChangedListener;
import com.bbgusa.bbgdemo.utils.common.UCConstants;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.IconPagerAdapter;
import com.viewpagerindicator.PageIndicator;
public class HomeFragment extends Fragment implements onGridViewVisibilityChangedListener{
private static final String TAG = HomeFragment.class.getSimpleName();
private ViewPager mViewPager;
private MainActivity activity;
private PageIndicator mIndicator;
private Animation mRotateAnim;
private Dialog indiacatorDialog;
private LinearLayout homeFragmentLL;
private static HomeFragment homeFragment;
public static final HomeFragment getInstance() {
return homeFragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (MainActivity) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.home_phone, container, false);
homeFragment = this;
UConnectUtils.setLauncher(true);
mViewPager = (ViewPager) v.findViewById(R.id.viewpager);
mIndicator = (IconPageIndicator) v.findViewById(R.id.indicator);
homeFragmentLL = (LinearLayout) v.findViewById(R.id.homeFragment);
indiacatorDialog = new Dialog(getActivity());
indiacatorDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
indiacatorDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
indiacatorDialog.setContentView(R.layout.indicator_dialog);
indiacatorDialog.setCanceledOnTouchOutside(false);
Window window = indiacatorDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mRotateAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_and_scale);
UConnectUtils.addAnimationFrameCount(mRotateAnim);
indicatorAnim();
// for property id
// if (activity.isInterNetAvailable()) {
Log.i(TAG, "onCreateView========== isInterNetAvailable");
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
// }
return v;
}
protected void parseJson(JSONObject rootResponce) {
TestTopics.imageUrls.clear();
TestTopics.titles.clear();
TestTopics.mMainMenuID.clear();
TestTopics.mViewType.clear();
TestTopics.mPhoneNo.clear();
try {
//get the Version
String version = rootResponce.optString("VERSION");
SharedPreferences mPref;
SharedPreferences.Editor edit;
mPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
edit = mPref.edit();
edit.putString(getResources().getString(R.string.pref_cms_version_key), version).commit();
JSONArray jsonArray = rootResponce.getJSONArray("MAINMENU");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childMenuObject = jsonArray.getJSONObject(i);
int mainMenuID = childMenuObject.optInt("mainMenuId");
String title = childMenuObject.optString("title");
String viewType = childMenuObject.optString("viewType");
String imageUrl = childMenuObject.optString("imageUrl");
String phoneNo = childMenuObject.optString("phoneNo");
TestTopics.mMainMenuID.add(mainMenuID);
TestTopics.imageUrls.add(imageUrl);
TestTopics.titles.add(title);
TestTopics.mViewType.add(viewType);
TestTopics.mPhoneNo.add(phoneNo);
}
// Create a TopicList for this demo. Save it as the shared instance
// in
// TopicList
String sampleText = getResources().getString(R.string.sample_topic_text);
TopicList tlist = new TopicList(sampleText);
TopicList.setInstance(tlist);
// Create an adapter object that creates the fragments that we need
// to display the images and titles of all the topics.
MyAdapter mAdapter = new MyAdapter(getActivity().getSupportFragmentManager(), tlist, getResources());
// mViewPager.removeAllViews();
mViewPager.setAdapter(mAdapter);
// mViewPager.setPageTransformer(true, new DepthPageTransformer());
mIndicator.setViewPager(mViewPager);
mIndicator.setCurrentItem(0);
mIndicator.notifyDataSetChanged();
ViewTreeObserver observer = mViewPager.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
mViewPager.bringChildToFront(mViewPager.getChildAt(0));
if(Build.VERSION.SDK_INT >= UCConstants.ICE_CREAM_SANDWICH_MR1){
mViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}else{
mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
/*Fragment f = new GridViewFragment();
FragmentTransaction t = getFragmentManager().beginTransaction();
t.replace(R.id.main_home_frag, f);
t.commit();*/
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adapter class
*
* This adapter class sets up GridFragment objects to be displayed by a
* ViewPager.
*/
public static class MyAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter {
private TopicList mTopicList;
private int mNumItems = 0;
private int mNumFragments = 0;
/**
* Return a new adapter.
*/
public MyAdapter(FragmentManager fm, TopicList db, Resources res) {
super(fm);
setup(db, res);
}
/**
* Get the number of fragments to be displayed in the ViewPager.
*/
#Override
public int getCount() {
Log.i(TAG, "getCount : mNumFragments = "+mNumFragments);
return mNumFragments;
}
/**
* Return a new GridFragment that is used to display n items at the
* position given.
*
* #param position
* int - the position of the fragement; 0..numFragments-1
*/
#Override
public Fragment getItem(int position) {
// Create a new Fragment and supply the fragment number, image
// position, and image count as arguments.
// (This was how arguments were handled in the original pager
// example.)
Bundle args = new Bundle();
args.putInt("num", position + 1);
args.putInt("firstImage", position * mNumItems);
// The last page might not have the full number of items.
int imageCount = mNumItems;
if (position == (mNumFragments - 1)) {
int numTopics = mTopicList.getNumTopics();
int rem = numTopics % mNumItems;
if (rem > 0)
imageCount = rem;
}
args.putInt("imageCount", imageCount);
args.putSerializable("topicList", TopicList.getInstance());
// Return a new GridFragment object.
Log.i(TAG, "created fragmenat number:==== "+position+" "+1);
GridViewFragmentPhone f = new GridViewFragmentPhone();
f.setArguments(args);
Log.i(TAG, "getItem : imageCount = "+imageCount);
return f;
}
/**
* Set up the adapter using information from a TopicList and resources
* object. When this method completes, all the instance variables of the
* adapter are valid;
*
* #param tlist
* TopicList
* #param res
* Resources
* #return void
*/
void setup(TopicList tlist, Resources res) {
mTopicList = tlist;
if ((tlist == null) || (res == null)) {
mNumItems = 2;//DEFAULT_NUM_ITEMS;
mNumFragments = 2;//DEFAULT_NUM_FRAGMENTS;
} else {
int numTopics = tlist.getNumTopics();
int numRowsGV = res.getInteger(R.integer.num_of_rows_gridview);
int numColsGV = res.getInteger(R.integer.num_of_cols_gridview);
int numTopicsPerPage = numRowsGV * numColsGV;
int numFragments = numTopics / numTopicsPerPage;
if (numTopics % numTopicsPerPage != 0)
numFragments++; // Add one if there is a partial page
mNumFragments = numFragments;
mNumItems = numTopicsPerPage;
}
} // end setup
#Override
public int getIconResId(int index) {
int[] ICON = new int[mNumFragments];
for (int i = 0; i < mNumFragments; i++) {
ICON[i] = R.drawable.slidericon;
}
return ICON[index % ICON.length];
}
} // end class MyAdapter
#Override
public void onGridViewVisibilityChanged(boolean hide) {
if(hide){
homeFragmentLL.setVisibility(View.GONE);
}else {
homeFragmentLL.setVisibility(View.VISIBLE);
}
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
private class CmsPropertyAsync extends AsyncTask<String, Void, String> {
MainActivity context;
CmsPropertyAsync(MainActivity activityTab) {
context = activityTab;
}
#Override
protected String doInBackground(String... params) {
String propertyId = UConnectUtils.getPropertyId(PreferenceManager.getDefaultSharedPreferences(context),getResources().getString(R.string.property_id));
if(propertyId != null && propertyId.length() > 0){
return propertyId;
}
return UConnectUtils.requestPropertyId(params[0], params[1]);
}
#Override
protected void onPostExecute(String propertyId) {
if(propertyId == null){
indiacatorDialog.dismiss();
showPropertyIdTimeoutAlert(getActivity());
return;
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString(getString(R.string.property_id),propertyId).commit();
String url = null;
String locale = Locale.getDefault().getLanguage();
url = UCConstants.CMS_BASE_URL+"mainMenu?propertyId="+propertyId+"&lang="+locale;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJson(response);
indiacatorDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (activity != null) {
// activity.getConnection(error);
}
indiacatorDialog.dismiss();
}
});
ImageCacheManager.getInstance().getQueueForMainmenu().add(jsObjRequest);
}
}
private void indicatorAnim() {
if (indiacatorDialog != null) {
ImageView alertIndicator = (ImageView) indiacatorDialog.findViewById(R.id.alert_indicator);
alertIndicator.startAnimation(mRotateAnim);
if (!getActivity().isFinishing()) {
indiacatorDialog.show();
}
}
}
// Show alert for Time out
private void showPropertyIdTimeoutAlert(final Activity context) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setIcon(R.drawable.alert_dialog_icon);
alertDialog.setTitle(context.getString(R.string.timeout_msg));
alertDialog.setMessage(context.getString(R.string.timeout_msg2));
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
indicatorAnim();
// for property id
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
}
});
alertDialog.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
getActivity().finish();
}
});
AlertDialog alert = alertDialog.create();
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
if (context != null && !context.isFinishing()) {
alert.show();
}
}
}
Actually, some data is being saved with onSavedInstaceState(). The data is not being deleted when process has been killed on LowMemory.
I fixed this with
#Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}
Just do not call super class. Just comment like above

Error await must not be called on the UI Thread in Android project

I am currently trying to read data from google drive, using a query then transferring the gson to a fragment so I can set the edit text values of said fragment to the gson being read in (Kudos if you followed that!)
Every time I move to open the fragment I am getting the following error message:
05-03 16:12:39.311 12594-12594/com.example.fitness_first.fitnessfirst E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fitness_first.fitnessfirst, PID: 12594
java.lang.IllegalStateException: await must not be called on the UI thread
at com.google.android.gms.common.internal.zzx.zza(Unknown Source)
at com.google.android.gms.common.api.internal.zzb.await(Unknown Source)
at com.example.fitness_first.fitnessfirst.ReadFileInAppFolder$1.onResult(ReadFileInAppFolder.java:63)
at com.example.fitness_first.fitnessfirst.ReadFileInAppFolder$1.onResult(ReadFileInAppFolder.java:50)
at com.google.android.gms.common.api.internal.zzb$zza.zzb(Unknown Source)
at com.google.android.gms.common.api.internal.zzb$zza.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I thought by setting a new thread to handle the data thread itself it would negate this problem but alas this was not the case. Any pointers would be kindly appreciated
The load details activity:
package com.example.fitness_first.fitnessfirst;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.ProgressBar;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.MetadataBuffer;
import com.google.android.gms.drive.query.Filter;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.Query;
import com.google.android.gms.drive.query.SearchableField;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadFileInAppFolder extends MainActivity {
UserDetails result1;
Gson gson = new Gson();
Bundle connectionHint;
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
}
public void retrieveUserDetails() {
DataThread runner = new DataThread();
runner.start();
}
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Filter starredFilter = Filters.eq(SearchableField.STARRED, true);
Filter mimeTypeFilter = Filters.eq(SearchableField.MIME_TYPE, "application/json");
Filter titleFilter = Filters.contains(SearchableField.TITLE, "appconfig.json");
Query query = new Query.Builder().addFilter(starredFilter).addFilter(mimeTypeFilter).addFilter(titleFilter).build();
Drive.DriveApi.getAppFolder(mGoogleApiClient).queryChildren(mGoogleApiClient, query)
.setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Problem while retrieving results");
return;
}
MetadataBuffer metadataBuffer = result.getMetadataBuffer();
DriveId driveId = metadataBuffer.get(0).getDriveId();
DriveFile file = driveId.asDriveFile();
DriveApi.DriveContentsResult driveContentsResult =
file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
driveContentsResult = null;
}
InputStream inputStream = driveContentsResult.getDriveContents().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
result1 = gson.fromJson(reader, UserDetails.class);
Bundle bundle = new Bundle();
android.os.Message message = AccountFragment.dataHandler.obtainMessage();
try {
Thread.sleep(1000);
bundle.putString("NAME", result1.toString());
message.setData(bundle);
AccountFragment.dataHandler.sendMessage(message);
} catch (InterruptedException e) {
Log.i(TAG, "Data thread interrupted");
}
}
});
}
private class DataThread extends Thread implements Runnable {
#Override
public void run()
{
Log.i("Data Thread", "Starting");
onConnected(connectionHint);
Log.i("Data Thread", "Finshed");
}
}
And the fragment I want to pass the data too:
package com.example.fitness_first.fitnessfirst;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
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.Spinner;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.nearby.messages.Message;
public class AccountFragment extends Fragment implements View.OnClickListener{
public static GoogleApiClient getInstance() {
return null;
}
private String activityName = "Account management";
private Button saveDetailsButton;
private static EditText accountName;
private EditText accountUserName;
private EditText accountHeight;
private EditText accountWeight;
private Spinner spinnerGender = null;
private Bundle name = new Bundle();
private String nameKey = "NAME";
private Bundle userName = new Bundle();
private String usernameKey = "USERNAME";
private Bundle gender = new Bundle();
private String genderKey = "GENDER";
private Bundle height = new Bundle();
private String heightKey = "HEIGHT";
private Bundle weight = new Bundle();
private String weightKey = "WEIGHT";
public static Intent detailsIntent = new Intent();
private final int spinnerPosMALE = 0;
private final int spinnerPosFEMALE = 1;
public AccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_account, container, false);
saveDetailsButton = (Button) rootView.findViewById(R.id.buttonSaveDetails);
saveDetailsButton.setOnClickListener(this);
accountName = (EditText) rootView.findViewById(R.id.editTextName);
accountUserName = (EditText) rootView.findViewById(R.id.editTextUsername);
spinnerGender = (Spinner) rootView.findViewById(R.id.spinnerGender);
accountHeight = (EditText) rootView.findViewById(R.id.editTextHeight);
accountWeight = (EditText) rootView.findViewById(R.id.editTextWeight);
super.onCreateView(inflater, container, savedInstanceState);
return rootView;
}
#Override
public void onClick(View v) {
name.putString("NAME", accountName.getText().toString());
userName.putString("USERNAME", accountUserName.getText().toString());
gender.putString("GENDER", spinnerGender.getSelectedItem().toString());
height.putString("HEIGHT", accountHeight.getText().toString());
weight.putString("WEIGHT", accountWeight.getText().toString());
detailsIntent.putExtras(name);
detailsIntent.putExtras(userName);
detailsIntent.putExtras(gender);
detailsIntent.putExtras(height);
detailsIntent.putExtras(weight);
CreateFileInAppFolderActivity saveDetails = new CreateFileInAppFolderActivity();
saveDetails.saveDetails(detailsIntent);
}
#Override
public void onPause() {
super.onPause();
Log.i(activityName, "Paused");
}
#Override
public void onResume() {
super.onResume();
ReadFileInAppFolder dataIn = new ReadFileInAppFolder();
dataIn.retrieveUserDetails();
Log.i(activityName, "Resumed");
}
#Override
public void onStop() {
super.onStop();
Log.i(activityName, "Stopped");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(activityName, "Destroyed");
}
public static Handler dataHandler = new Handler()
{
#Override
public void handleMessage(android.os.Message message){
String s = message.getData().getString("NAME");
accountName.setText(s);
}
};
}
As stated in the Exception message, you shouldn't use await on the UI thread.
Setting a new thread to handle the data should fix it.
[EDIT 1]
The "onResult" function is called on the UI Thread as mentioned in https://developers.google.com/android/reference/com/google/android/gms/common/api/ResultCallback#public-method-summary
public abstract void onResult (R result)
Called when the Result is ready.
It is the responsibility of the callback to release any resources
associated with the result. Some result types may implement
Releasable, in which case release() should be used to free the
associated resources.
This method is called on the main thread, unless overridden by
setHandler(Handler).

Categories

Resources