如何在不使用任何外部库的情况下将导航抽屉和Tabhost结合使用

时间:2013-12-30 04:36:07

标签: android android-tabhost navigation-drawer

我想在不使用任何外部库的情况下将导航抽屉和Tabhost放在一起使用?

我尝试使用Sherlock Fragment的外部库,但是我遇到了其他问题。

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输出:

    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)

1 个答案:

答案 0 :(得分:1)

由于您在创建片段的实际视图之前调用了NullPointerException,因此您获得了很大的胖getView()。因此,在onCreateView()中,您无法通过ID找到该视图。

此问题的解决方案是尝试使用rootview.findViewById()而不是getView().findViewById()

此外,您是否注意到,您已经对根视图进行了充气,​​没有对其执行任何操作,然后将其返回。因此,只需使用它来查找视图并将所有侦听器绑定到按钮左右。

好吧,至于图像的问题,这是由你自己在onActivityResult()方法中的实现引起的。而且我不知道你的应用程序是如何工作的,所以我只是发布我的代码来实现类似的东西。

@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);
}

我认为应该可以正常工作。