访问其他java活动时,静态字符串变量不会更改

时间:2017-03-18 09:25:53

标签: java android mysql exception connection

我开发了一个应用程序,我们可以在其中更改IP地址以连接到在xampp服务器上运行的数据库。

这是我的MainActivity.java

其中我声明了一个名为" ip"的公共静态字符串变量。并为其设置默认值。我使用警告框使用菜单选项更改了此ip。当使用snackbar显示更改的ip时,它会显示更改。但试图访问" ip"在另一个名为" doctor_login.java"通过Mainactivity.ip。它不需要更改IP,而是采用默认的ip本身。下面我展示了截图和代码。请帮我解决这个问题。

public class MainActivity extends AppCompatActivity { public static String ip="192.168.43.97";// This is default ip
public static final String dbuser = "root";
public static final String dbpass = "kughan";

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());


    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "App by KUGHAN EV", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

   if (id == R.id.action_settings) {

        AlertDialog.Builder ipalert = new AlertDialog.Builder(MainActivity.this);
        ipalert.setCancelable(false);
        ipalert.setTitle("Change IP");
        ipalert.setMessage("Enter your server ip below:");

        final EditText input = new EditText(MainActivity.this);
        input.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        input.setLayoutParams(lp);
        ipalert.setView(input);
        ipalert.setPositiveButton("CHANGE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                 String cip=input.getText().toString();
                    ip=cip;  // Trying to change ip address from edittext
                    Snackbar.make(getCurrentFocus(),"Ip changed to "+ip,Snackbar.LENGTH_LONG).setAction(null,null).show();
            }
        });
        ipalert.setNegativeButton("CANCEL",null);
        ipalert.show();
    }
    if(id== R.id.showip){
        Snackbar.make(getCurrentFocus(),"Your IP is "+ip,Snackbar.LENGTH_LONG).setAction(null,null).show();
    }

    return super.onOptionsItemSelected(item);
}


public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                doctor_login tab1 = new doctor_login();
                return tab1;
            case 1:
                patient_login tab2 = new patient_login();
                return tab2;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "DOCTOR";
            case 1:
                return "PATIENT";
            }
        return null;
    }


}


//This is my doctor_login activity


public class doctor_login extends Fragment {
public static String logged;
public static String loggedid;
private String url;
private static final String user = MainActivity.dbuser;
private static final String pass = MainActivity.dbpass;

EditText usertxt,passtxt;
Button login,reg;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    final View rootView = inflater.inflate(R.layout.activity_doctor_login, container, false);
    url ="jdbc:mysql://"+MainActivity.ip+":3306/mediapp";  //getting value from mainactivity ip value 

    usertxt=(EditText) rootView.findViewById(R.id.editText);
    passtxt=(EditText)rootView.findViewById(R.id.editText2);
    login=(Button)rootView.findViewById(R.id.button);
    reg=(Button)rootView.findViewById(R.id.button2);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(usertxt.getText().toString().length()==0 || passtxt.getText().toString().length()==0){
                Snackbar.make(getView(),"Fill all credential details",Snackbar.LENGTH_LONG).setAction("Action",null).show();
            }else{
                testDB();
            }
        }
    });

    reg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent1 = new Intent(doctor_login.this.getActivity(),doctor_signup.class);
            startActivity(intent1);
        }
    });

    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    Snackbar.make(getView(),"Welcome to DigiMedApp",Snackbar.LENGTH_LONG).setAction("Action",null).show();
}

public void testDB(){
    Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();

        try
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection(url,user,pass);
            Statement st = con.createStatement();
            ResultSet rs =  st.executeQuery("select name,id from doctorlogin where username='"+usertxt.getText().toString()+"' and password='"+passtxt.getText().toString()+"';");
            if(rs.next()){
                logged=rs.getString(1);
                loggedid=rs.getString(2);
                Toast.makeText(getContext(),"Welcome "+rs.getString(1),Toast.LENGTH_LONG).show();
                Intent intent = new Intent(doctor_login.this.getActivity(),doctor_home.class);
                startActivity(intent);
            } else
            {
                Snackbar.make(getView(),"Wrong Username or password",Snackbar.LENGTH_LONG).setAction("Action",null).show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(getContext(),e.toString(),Toast.LENGTH_LONG).show();
        }
}

}

使用alertdialog更改ip See the editetxt__Screenshot

当尝试从doctor_login页面登录时,它会显示连接异常,因为即使在更改ip之后您也可以看到它正在尝试连接的IP

Exeption__Screenshot

1 个答案:

答案 0 :(得分:0)

这里:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    final View rootView = inflater.inflate(R.layout.activity_doctor_login, container, false);
    url ="jdbc:mysql://"+MainActivity.ip+":3306/mediapp";  //getting value from mainactivity ip value 

doctor_login片段是在MainActivity中更改ip之前创建的 由于url将使用初始化期间存在的MainActivity.ip值而不考虑用户在MainActivity中执行的IP更改,因此此评估不在方便的位置。

要解决您的问题,请使用testDB()方法生成包含IP的网址。

替换

public void testDB(){
    Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();

通过

public void testDB(){
     url ="jdbc:mysql://"+MainActivity.ip+":3306/mediapp";  
    Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();