我试图使用参数将数据(PID)从片段扫描保存到片段维护
但我的Log.d中的数据始终为空("标记"," PID扫描:" +数据);
我的论点有什么不对?
这是我的代码
public class FragmentScan extends Fragment { TextView tvPid; TextView txtName; TextView txtPrice; TextView txtDesc; TextView txtSpec; private ProgressDialog pDialog; JSONParser jsonParser = new JSONParser(); private static final String url_product_detials = "http://10.0.3.2/skripsi/get_product_details.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; private static final String TAG_PRODUCT = "product"; private static final String TAG_PID = "pid"; private static final String TAG_NAME = "name"; private static final String TAG_PRICE = "price"; private static final String TAG_DESCRIPTION = "description"; private static final String TAG_SPESIFICATION = "spesification"; // Progress Dialog private static final String PID_KEY = "tvPid"; private static final String NAME_KEY = "tvName"; private static final String PRICE_KEY = "tvPrice"; private static final String DESCRIPTION_KEY = "tvDesc"; private static final String SPESIFICATION_KEY = "tvSpec"; private String mPid=null; private String mName=null; private String mPrice=null; private String mDesc=null; private String mSpec=null; Button Btngetdata; ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d("ZZZ", "ada di oncreateView"); super.onCreate(savedInstanceState); View rootView = inflater.inflate(R.layout.fragment_layout_four, container, false); tvPid = (TextView) rootView.findViewById(R.id.tvPid); txtName = (TextView) rootView.findViewById(R.id.tvName); txtPrice = (TextView) rootView.findViewById(R.id.tvPrice); txtDesc = (TextView) rootView.findViewById(R.id.tvDesc); txtSpec = (TextView) rootView.findViewById(R.id.tvSpec); Btngetdata = (Button)rootView.findViewById(R.id.getdata); Btngetdata.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Fragment fragment = new FragmentMaintenance(); Bundle data = new Bundle(); data.putString("pid", mPid); fragment.setArguments(data); FragmentManager frgManager = getFragmentManager(); Log.d("tag", "PID SCAN: " + data); frgManager.beginTransaction().replace(R.id.content_frame, fragment) .commit(); } }); Button scanBtn = (Button) rootView.findViewById(R.id.btnScan); //in some trigger function e.g. button press within your code you should add: scanBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { Intent intent = new Intent("com.google.zxing.client.android.SCAN"); intent.putExtra("SCAN_MODE", "QR_CODE_MODE,PRODUCT_MODE"); startActivityForResult(intent, 0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getActivity(), "ERROR:" + e, Toast.LENGTH_LONG).show(); } } }); if (savedInstanceState != null) { Log.d("ZZZ", "ada di di dlm if saved"); mPid = savedInstanceState.getString(PID_KEY); mName = savedInstanceState.getString(NAME_KEY); mPrice = savedInstanceState.getString(PRICE_KEY); mDesc = savedInstanceState.getString(DESCRIPTION_KEY); mSpec = savedInstanceState.getString(SPESIFICATION_KEY); tvPid.setText(mPid); txtName.setText(mName); txtPrice.setText(mPrice); txtDesc.setText(mDesc); txtSpec.setText(mSpec); } return rootView; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); Log.d("ZZZ", "Ada di mainactivity"); if (requestCode == 0) { TextView pid = (TextView) getActivity().findViewById(R.id.tvPid); if (resultCode == Activity.RESULT_OK) { pid.setText(intent.getStringExtra("SCAN_RESULT")); new GetProductDetails(getActivity()).execute(pid.getText().toString()); } else if (resultCode == Activity.RESULT_CANCELED) { pid.setText("Scan cancelled."); } } } class GetProductDetails extends AsyncTask<String, Void, String[]> { /** * Before starting background thread Show Progress Dialog */ private Context mContext; public GetProductDetails(Context context) { mContext = context; } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(mContext); pDialog.setMessage("Loading product details. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Getting product details in background thread */ protected String[] doInBackground(String... string) { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("pid", string[0])); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = jsonParser.makeHttpRequest( url_product_detials, "GET", params); Log.d("ZZZ", json.toString()); success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully received product details JSONArray productObj = json.getJSONArray(TAG_PRODUCT); // JSON Array // get first product object from JSON Array JSONObject product = productObj.getJSONObject(0); // product with this pid found // Edit Text String[] result = {Integer.toString(success), product.getString(TAG_NAME), > product.getString(TAG_PRICE), product.getString(TAG_DESCRIPTION), product.getString(TAG_SPESIFICATION)}; // // display product data in EditText // txtName.setText(product.getString(TAG_NAME)); // txtPrice.setText(product.getString(TAG_PRICE)); // txtDesc.setText(product.getString(TAG_DESCRIPTION)); Log.d("ZZZ", result[0]); return result; } else { Log.d("ZZZ", Integer.toString(success)); String[] result = {Integer.toString(success)}; return result; } } catch (JSONException e) { e.printStackTrace(); return null; } } /** * After completing background task Dismiss the progress dialog * * */ protected void onPostExecute(String[] results) { // dismiss the dialog once got all details pDialog.dismiss(); if (results[0] != null) { Log.d("ZZZ", "SUCCESS" + results[0]); if (results[0].matches("1")) { Log.d("ZZZ", "SUCCESS " + results[0]); TextView name = (TextView) getActivity().findViewById(R.id.tvName); name.setText(results[1]); TextView price = (TextView) getActivity().findViewById(R.id.tvPrice); price.setText(results[2]); TextView desc = (TextView) getActivity().findViewById(R.id.tvDesc); desc.setText(results[3]); TextView spec = (TextView) getActivity().findViewById(R.id.tvSpec); spec.setText(results[4]); } else if (results[0].matches("-1")) { Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_SHORT).show(); } else{ Log.d("ZZZ", "UNKNOWN ERROR"); } } } } @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save state information with a collection of key-value pairs // 4 lines of code, one for every count variable super.onSaveInstanceState(savedInstanceState); savedInstanceState.putString(PID_KEY, tvPid.getText().toString()); savedInstanceState.putString(NAME_KEY, txtName.getText().toString()); savedInstanceState.putString(PRICE_KEY, txtPrice.getText().toString()); savedInstanceState.putString(DESCRIPTION_KEY, txtDesc.getText().toString()); savedInstanceState.putString(SPESIFICATION_KEY, txtSpec.getText().toString()); } }
这是我的活动
公共类MainActivity扩展了Activity {
private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; CustomDrawerAdapter adapter; SharedPreferences preferences; String pref; List<DrawerItem> dataList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); preferences = this.getSharedPreferences(Config.PREFERENCES, MODE_PRIVATE); pref = preferences.getString(Config.SESSION,null); // Initializing dataList = new ArrayList<DrawerItem>(); mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // Add Drawer Item to dataList dataList.add(new DrawerItem("Scanner", R.drawable.ic_action_email)); dataList.add(new DrawerItem("Schedule", R.drawable.ic_action_good)); dataList.add(new DrawerItem("Games", R.drawable.ic_action_gamepad)); dataList.add(new DrawerItem("Logout", R.drawable.ic_action_about)); adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item, dataList); mDrawerList.setAdapter(adapter); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to // onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to // onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { SelectItem(0); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void SelectItem(int possition) { Fragment fragment = null; Bundle args = new Bundle(); switch (possition) { case 0: fragment = new FragmentScan(); break; case 1: fragment = new FragmentSchedule(); break; case 2: fragment = new FragmentThree(); args.putString(FragmentThree.ITEM_NAME, dataList.get(possition) .getItemName()); args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition) .getImgResID()); break; case 3: logout(); Intent in = new Intent(this, LoginActivity.class); startActivity(in); finish(); return; default: break; } fragment.setArguments(args); FragmentManager frgManager = getFragmentManager(); frgManager.beginTransaction().replace(R.id.content_frame, fragment) .commit(); mDrawerList.setItemChecked(possition, true); setTitle(dataList.get(possition).getItemName()); mDrawerLayout.closeDrawer(mDrawerList); } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return false; } private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SelectItem(position); } } //In the same activity you’ll need the following to retrieve the results: private void logout(){ //TODO delete cookie from db SharedPreferences.Editor editor = preferences.edit(); editor.remove(Config.SESSION); editor.remove(Config.USERNAME); editor.commit(); }
我希望有人可以帮我解决这个问题, 谢谢。
答案 0 :(得分:0)
我认为它应该不是空的,也许你只是没有正确地检索它。
在您的日志记录代码中,您使用了:
Log.d("tag", "PID SCAN: " + data);
但实际上您使用以下方式存储了pid:
data.putString("pid", mPid);
这意味着,您应该使用键pid
从包中获取值,例如:
Log.d("tag", "PID SCAN: " + data.getString("pid"));
修改强>
如果它是您尝试获取的进程ID,请尝试查看android.os.Process.myPid();
如果pid
是您自己的预定义变量(包含其他内容),
然后你需要在创建片段时传递它,如下所示:
fragment = new FragmentScan();
args.putString("pid", YOUR_TV_PID_VALUE);
从另一方(FragmentScan
),您可以使用getArguments()
获取Bundle
,然后使用getString("pid")
。
<强>更新强>
在更多地阅读你的代码之后,似乎你的循环有点纠结。 但有一个快速的建议是:为什么不尝试以下
data.putString("pid", tvPid.getText());
在原始代码中,点击pid
后,savedInstanceState
中的scanBtn
应该存在,完成/取消扫描。但我认为你的代码流程有点纠结
读取 here,onSaveInstanceState
被调用以在被杀之前从活动中检索每个实例的状态。
=&GT;这意味着,在打开另一个意图(由scanBtn
执行)之前,会调用onSaveInstanceState
并存储tvPid
的空值。当主要意图恢复时,它会获得包含空字符串pid
的包。但它应该是""
,而不是空。