0

I want to use navigation drawer and Tabhost together without using any external library is that possible?

I have tried using external library of Sherlock Fragment however, i am getting issues with other things.

FragmentTab1.java

public class FragmentTab1 extends SherlockFragment {

Button postAd, browse;
EditText discription;
EditText price;
String discriptionText;
String priceText;
String adTypetext;
RadioGroup adType;
RadioButton buy;
RadioButton sell;
Bitmap bitmap;
ProgressDialog dialog;
String encodedImage;
String userid;
TextView msgLength;
JSONArray AdsArray = null;
String TAG_ID = "id";
String TAG_IMAGE = "image";
String TAG_TYPE = "adType";
String TAG_DISCRIPTION = "description";
String TAG_PRICE = "price";
ListView lv;
ArrayList<HashMap<String, String>> adList;

private static final int PICK_IMAGE = 1;

@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);

  if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    postAd = (Button) getView().findViewById(R.id.bpostAd);
    discription = (EditText)getView().findViewById(R.id.etDiscription);
    price = (EditText)getView().findViewById(R.id.etPrice);
    final RadioGroup adType = (RadioGroup)getView().findViewById(R.id.radioGroup);
    RadioButton buy = (RadioButton)getView().findViewById(R.id.rbBuy);
    RadioButton sell = (RadioButton)getView().findViewById(R.id.rbSell);
    browse = (Button)getView().findViewById(R.id.bBrowse);
    msgLength = (TextView)getView().findViewById(R.id.tvLength);
    lv = (ListView)getView().findViewById(R.id.listView1);


    SharedPreferences mPrefs = getActivity().getSharedPreferences("IDvalue", 0);
    userid = mPrefs.getString("userIdKey", null);

    adList = new ArrayList<HashMap<String, String>>();
    new LoadMyAds().execute();

    TextWatcher txwatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            int length = s.length();
            int remaining = 140 - length;
            msgLength.setText(String.valueOf(remaining));
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    };

    discription.addTextChangedListener(txwatcher);

    postAd.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            discriptionText = discription.getText().toString();
            priceText = price.getText().toString();

            int selectedRbId = adType.getCheckedRadioButtonId();
            if (selectedRbId == R.id.rbBuy) {
                adTypetext = "Buying";
            }
            if (selectedRbId == R.id.rbSell) {
                adTypetext = "Selling";
            }
            if (bitmap == null) {
                Toast.makeText(getActivity().getApplicationContext(),
                        "Please select image", Toast.LENGTH_SHORT).show();
            } else {

                new ImageUploadTask().execute();

                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.postAd(encodedImage,
                        discriptionText, adTypetext, priceText, userid);
                try {
                    if (json.getString("status") != null) {
                        String res = json.getString("status");
                        if (Integer.parseInt(res) == 1) {
                            Toast.makeText(getActivity().getApplicationContext(),
                                    "Ad has been posted", Toast.LENGTH_LONG)
                                    .show();
                        } else {
                            Toast.makeText(getActivity().getApplicationContext(),
                                    "posting error", Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

        }
    });

    browse.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(
                        Intent.createChooser(intent, "Select Picture"),
                        PICK_IMAGE);
            } catch (Exception e) {
                Toast.makeText(getActivity().getApplicationContext(), "error",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }
    });

  return rootView;




}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    switch (requestCode) {
    case PICK_IMAGE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImageUri = data.getData();
            String filePath = null;

            try {
                // OI FILE Manager
                String filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY
                String selectedImagePath = getPath(selectedImageUri);

                if (selectedImagePath != null) {
                    filePath = selectedImagePath;
                } else if (filemanagerstring != null) {
                    filePath = filemanagerstring;
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "Unknown path",
                            Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                }

                if (filePath != null) {
                    decodeFile(filePath);
                } else {
                    bitmap = null;
                }
            } catch (Exception e) {
                Toast.makeText(getActivity().getApplicationContext(), "Internal error",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }
        break;
    default:
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}

public void decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    Log.e("Decodefile", "bitmap set");
    // imgView.setImageBitmap(bitmap);

}

class ImageUploadTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.JPEG, 100, bos);
        byte[] data = bos.toByteArray();
        // encodedImage = new String(data);
        encodedImage = Base64.encodeToString(data, Base64.DEFAULT);
        return encodedImage;
    }

}

class LoadMyAds extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub
        UserFunctions userFunction = new UserFunctions();
        String type = "MyAds";
        JSONObject json = userFunction.myAds(userid, type);
        try {
            if (json.getString("status") != null) {
                String res = json.getString("status");
                if (Integer.parseInt(res) == 1) {


                    AdsArray = json.getJSONArray("adsArray");
                    for (int i = 0; i < AdsArray.length(); i++) {
                        JSONObject c = AdsArray.getJSONObject(i);
                        String id = c.getString(TAG_ID);
                        String adType = c.getString(TAG_TYPE);
                        String description = c.getString(TAG_DISCRIPTION);
                        String price = c.getString(TAG_PRICE);
                        String image = c.getString(TAG_IMAGE);

                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put(TAG_ID, id);
                        map.put(TAG_IMAGE, image);
                        map.put(TAG_TYPE, adType);
                        map.put(TAG_DISCRIPTION, description);
                        map.put(TAG_PRICE, price);

                        adList.add(map);

                    }
                } else {
                    Toast.makeText(getActivity().getApplicationContext(),
                            "parsing error", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub


        //image parameter need to be added

        ListAdapter adapter = new SimpleAdapter(getActivity(), adList, R.layout.ad_list_item , new String[] { TAG_DISCRIPTION, TAG_PRICE} , new int[] { R.id.title, R.id.price});




        lv.setAdapter(adapter);

    }

}
}

LogCat output:

    12-29 23:42:09.819: E/AndroidRuntime(1061): FATAL EXCEPTION: main
12-29 23:42:09.819: E/AndroidRuntime(1061): java.lang.NullPointerException
12-29 23:42:09.819: E/AndroidRuntime(1061):     at com.backslash.myadds.FragmentTab1.onCreateView(FragmentTab1.java:86)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:279)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.View.dispatchAttachedToWindow(View.java:12125)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2453)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2460)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2460)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2460)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2460)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2460)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2460)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1207)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.Choreographer.doFrame(Choreographer.java:532)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.os.Handler.handleCallback(Handler.java:730)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.os.Looper.loop(Looper.java:137)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at android.app.ActivityThread.main(ActivityThread.java:5103)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at java.lang.reflect.Method.invokeNative(Native Method)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at java.lang.reflect.Method.invoke(Method.java:525)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-29 23:42:09.819: E/AndroidRuntime(1061):     at dalvik.system.NativeStart.main(Native Method)
Deep Rathod
  • 69
  • 3
  • 14
  • you should show which error you have faced. and what you have tried to achieve this ? – Chintan Khetiya Dec 30 '13 at 04:41
  • I have showed my code. Thank you for the reply. @chintankhetiya – Deep Rathod Dec 30 '13 at 04:59
  • 1
    Try replace `getView()` with rootView in `onCreateView()` method – Xiao Liang Dec 30 '13 at 05:25
  • Thanks a lot, now i am able to see the xml file i mean its getting redirected, now i am facing another issue here. Here in the above code i am trying to pick an image, everything is working perfect apart from picking an image from the phone. if you can help me with the same. Thanks in advance. @IzzyLeung – Deep Rathod Dec 30 '13 at 05:39
  • Can you help me with the same ? i am facing one more problem here i have mention it in the above comment. @IzzyLeung – Deep Rathod Dec 30 '13 at 06:06

1 Answers1

1

You are getting a big fat NullPointerException 'cause you are calling getView() before the actual view of the fragment is created. So, in onCreateView() there is no way for you to find the view by id.

The solution to this problem is to try using rootview.findViewById() rather than getView().findViewById().

Also, have you noticed that, you've inflate the rootview, done nothing to it, and then return it. So, just using it to find views and bind all the listeners to buttons or so.

Well, as for the issue for the image, that's caused by your own implementation in the onActivityResult() method. And I don't know how your app works in detail, so I'll just post my code of implementing something analogous here.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
         Uri uri = data.getData();
         ContentResolver cr = this.getContentResolver();
         try {
                 Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                 imageView = (ImageView) findViewById(R.id.image);
                 imageView.setImageBitmap(bitmap);
         } catch (FileNotFoundException e) {
                 Log.e("Exception", e.getMessage(), e);
         }
     }

     super.onActivityResult(requestCode, resultCode, data);
}

Should work fine, I think.

Pang
  • 9,564
  • 146
  • 81
  • 122
Xiao Liang
  • 706
  • 5
  • 13
  • Thanks a lot, now i am able to see the xml file i mean its getting redirected, now i am facing another issue here. Here in the above code i am trying to pick an image, everything is working perfect apart from picking an image from the phone. if you can help me with the same. Thanks in advance @lzzyLeung – Deep Rathod Dec 30 '13 at 05:44
  • Opps, that may be caused by your own implementation in the onActivityResult() method. – Xiao Liang Dec 30 '13 at 06:32
  • I remember that I've wroote an analogous app, picking an image from galary, them set it to an ImageView, and I've put the code in my answer above, so plz check it out! – Xiao Liang Dec 30 '13 at 06:34
  • @DeepRathod The code is posted, wish it helps. Just took a snap, and fall asleep. :-( Sorry to keep you waiting for so long. – Xiao Liang Dec 30 '13 at 06:43
  • @IzzyLeaung I have implemented above code using Activity instead of Fragment and function of picking image works fine. But when i used fragment then OnActivityResult method haven't called. I have searched similar issues and found that many people faced this problem but i am still unable to fix this issue. :/ – Deep Rathod Dec 30 '13 at 07:01
  • @DeepRathod in fact, using my code above, you don't need to really know the exact file location of an image, and can get its stream and the bitmap. I found those code on internet. Altoouhg i don't know exactly the detail behind the secene, but it works at least. :-( – Xiao Liang Dec 30 '13 at 07:02
  • @DeepRathod plz wait a second, I'll help you to check this again. – Xiao Liang Dec 30 '13 at 07:04
  • @DeepRathod plz try paste my code of launching galary in your code. The code goeslike this: `@Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1); }` The tricky part is the number "1", which binds `startActivityForResult()` and `onActivityResult()` together. – Xiao Liang Dec 30 '13 at 07:05
  • Thanks a lot for your reply. Take your time. Your code is working perfectly but problem is onActivityResult method is not getting called in fragment. – Deep Rathod Dec 30 '13 at 07:08
  • I have tried your code, still i am not able to select image :( nodoubt your code would be workig. We have used fragments in our application. have a look at this link http://stackoverflow.com/questions/6147884/onactivityresult-not-being-called-in-fragment – Deep Rathod Dec 30 '13 at 07:13
  • Well, I see, I also faced this issue before, but my way of handling this is not that normal. You can do this, in the activity hoding the fragment, rewrite the onActivityResult method, then passing all it get to the fragment. like this -> in Activity `@Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {someFragment.onActivityResult(requestCode, resultCode, data);}` then handle all the data in the fragment, i think this tmie it should work. Also, check the request code twice, don't forget about that. – Xiao Liang Dec 30 '13 at 07:16
  • @DeepRathod Hi, I don't know if you have solved this problem? :-) – Xiao Liang Dec 30 '13 at 08:19
  • Nops, its not working anywhich way...!! thanks a lot for all the help. I am creating a new question for this. :))) thank you again. – Deep Rathod Dec 30 '13 at 08:21