从活动

时间:2017-03-01 06:33:20

标签: android android-fragments textview settext android-toast

我一直在开发一款包括登录注册,GPS和QR扫描仪的应用程序。 现在我在profilefragment.java中有我的QR扫描代码,我从mainactivity.java调用它.QR扫描的按钮位于profilefragment.xml中,主活动有mainactivity.java,它有try catch块。它不是进入try-catch块而是显示toast消息。 QR生成的字符串格式也是正确的。

配置文件片段中的QR扫描代码(主要activity.java中的QR扫描结果)

 public class ProfileFragment extends Fragment implements View.OnClickListener {

private TextView tv_name, tv_email, tv_message;
private SharedPreferences pref;
private AppCompatButton btn_change_password, btn_logout;
private EditText et_old_password, et_new_password;
private AlertDialog dialog;
private ProgressBar progress;
private Button buttonScan, Nextbutton;
private TextView textViewUnique;
private IntentIntegrator qrScan;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_profile, container, false);


    initViews(view);
    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    pref = getActivity().getPreferences(0);
    tv_name.setText("Welcome : " + pref.getString(Constants.NAME, ""));
    tv_email.setText(pref.getString(Constants.EMAIL, ""));

}

private void initViews(View view) {

    tv_name = (TextView) view.findViewById(R.id.tv_name);
    tv_email = (TextView) view.findViewById(R.id.tv_email);
    btn_change_password = (AppCompatButton) view.findViewById(R.id.btn_chg_password);
    btn_logout = (AppCompatButton) view.findViewById(R.id.btn_logout);
    buttonScan = (Button) view.findViewById(R.id.buttonScan);
    Nextbutton = (Button) view.findViewById(R.id.Next);
    textViewUnique = (TextView) view.findViewById(R.id.textViewUniqueId);
    btn_change_password.setOnClickListener(this);
    btn_logout.setOnClickListener(this);
    buttonScan.setOnClickListener(this);
    qrScan = new IntentIntegrator(getActivity());
    Nextbutton.setOnClickListener(this);

}


private void showDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.dialog_change_password, null);
    et_old_password = (EditText) view.findViewById(R.id.et_old_password);
    et_new_password = (EditText) view.findViewById(R.id.et_new_password);
    tv_message = (TextView) view.findViewById(R.id.tv_message);
    progress = (ProgressBar) view.findViewById(R.id.progress);
    builder.setView(view);
    builder.setTitle("Change Password");
    builder.setPositiveButton("Change Password", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    dialog = builder.create();
    dialog.show();
    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String old_password = et_old_password.getText().toString();
            String new_password = et_new_password.getText().toString();
            if (!old_password.isEmpty() && !new_password.isEmpty()) {

                progress.setVisibility(View.VISIBLE);
                changePasswordProcess(pref.getString(Constants.EMAIL, ""), old_password, new_password);

            } else {

                tv_message.setVisibility(View.VISIBLE);
                tv_message.setText("Fields are empty");
            }
        }
    });
}

@Override
public void onClick(View v) {
    switch (v.getId()) {

        case R.id.btn_chg_password:
            showDialog();
            break;
        case R.id.btn_logout:
            logout();
            break;
        case R.id.buttonScan:
            qrScan.initiateScan();
            break;
        case R.id.Next:
            Intent intent = new Intent(getActivity(), MapMainActivity.class);
            getActivity().startActivity(intent);
            break;
    }
}

private void logout() {
    SharedPreferences.Editor editor = pref.edit();
    editor.putBoolean(Constants.IS_LOGGED_IN, false);
    editor.putString(Constants.EMAIL, "");
    editor.putString(Constants.NAME, "");
    editor.putString(Constants.UNIQUE_ID, "");
    editor.apply();
    goToLogin();
}

private void goToLogin() {

    Fragment login = new LoginFragment();
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_frame, login);
    ft.commit();
}

private void changePasswordProcess(String email, String old_password, String new_password) {

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setEmail(email);
    user.setOld_password(old_password);
    user.setNew_password(new_password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.CHANGE_PASSWORD_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();
            if (resp.getResult().equals(Constants.SUCCESS)) {
                progress.setVisibility(View.GONE);
                tv_message.setVisibility(View.GONE);
                dialog.dismiss();
                Snackbar.make(getView(), resp.getMessage(), Snackbar.LENGTH_LONG).show();

            } else {
                progress.setVisibility(View.GONE);
                tv_message.setVisibility(View.VISIBLE);
                tv_message.setText(resp.getMessage());

            }
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

            Log.d(Constants.TAG, "failed");
            progress.setVisibility(View.GONE);
            tv_message.setVisibility(View.VISIBLE);
            tv_message.setText(t.getLocalizedMessage());

        }

    });
}

}

mainactivity.java

public class MainActivity extends FragmentActivity {
private TextView textViewUnique;

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
 View view = inflater.inflate(R.layout.fragment_profile,container,false);
 TextView textViewUnique = (TextView) view.findViewById(R.id.textViewUniqueId);
//return inflater.inflate(R.layout.fragment_profile, container);
 return view;

}
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 textViewUnique = (TextView) findViewById(com.learn2crack.loginregistration.R.id.textViewUniqueId);
 pref = getPreferences(0);
 initFragment();
 }
 private void initFragment() {
 Fragment fragment;
 if (pref.getBoolean(Constants.IS_LOGGED_IN, false)) {
 fragment = new ProfileFragment();
 } else {
   fragment = new LoginFragment();
 }
 FragmentTransaction ft = getFragmentManager().beginTransaction();
 ft.replace(R.id.fragment_frame, fragment);
 ft.commit();
 }
 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
 if (result != null) {
 //if qrcode has nothing in it
 if (result.getContents() == null) {
 Toast.makeText(this, "Result Not Found", Toast.LENGTH_LONG).show();
 } else {
 //if qr contains data
 try {
 ProfileFragment profileFragment = new ProfileFragment();
 profileFragment.onActivityResult(requestCode, resultCode, data);
 JSONObject obj = new JSONObject(result.getContents());
 textViewUnique.setText(obj.getString("unique_id"));
 //textViewUnique.setText(obj.getString("unique id"));
 } catch (Exception e) {
 e.printStackTrace();
 //if control comes here
 //that means the encoded format not matches
 //in this case you can display whatever data is available on the qrcode
 //to a toast
 Toast.makeText(this, result.getContents(), Toast.LENGTH_LONG).show();
 }
 }
 } else {
 super.onActivityResult(requestCode, resultCode, data);
 }
 }
 }

这两个XML是

activitymain.xml

     

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="com.learn2crack.loginregistration.MainActivity">
 <FrameLayout
 android:id="@+id/fragment_frame"
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>
 </LinearLayout>
 </android.support.design.widget.CoordinatorLayout>

profile fragment.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/activity_main"
 android:orientation="vertical"
 android:layout_marginLeft="40dp"
 android:layout_marginRight="40dp"
 android:gravity="center"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:baselineAligned="false">

 <Button
 android:id="@+id/buttonScan"
 android:layout_width="104dp"
 android:layout_height="wrap_content"
 android:text="QR Scan"
 android:layout_gravity="right" />
 <TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="unique_id"
 android:textSize="20dp" />
 <TextView
 android:id="@+id/textViewUniqueId"
 android:layout_marginTop="10dp"
 android:textSize="20sp"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center_horizontal"/>
 </LinearLayout>

1 个答案:

答案 0 :(得分:0)

假设您的代码中的MainActivity容器中fragment_frame替换了您的片段。
我们要遵循的两个步骤 -

1)为您的activity创建公开方法,例如MainActivity

public void setRequiredText(String text) {
    if(textViewUnique != null) {
        textViewUnique.setText(text);
    }
}

2)从MainActivity调用Fragment方法更新TextView

Activity act = getActivity(); // Get activity to which your fragment is attached
if (act instanceof MainActivity) {
    ((MainActivity) act).setRequiredText(obj.getString("unique_id"))
}

你已经完成了。