简体   繁体   中英

set fetched data from database to a textview after calling intent

I've created a Textview with a null value and button in my my Mainactivity and fetched some data from sql database server using AsyncTask method on button click and stored in to my textview .
Then I called an intent to another activity activity2 to show something and I returned to my Mainactivity using intent.But I can't view the previously set data in textview . It shows null value.I want to set it previously fetched data.how can I set that?

public class MainActivity extends Activity {

public ImageView prev, now, next;
    String depvisitid;
    public TextView display, bottom, ptname, docname;
    public String tokenh,tokenext,tokennow;
    public String pname,pnamenext,pnamenow;
    public boolean status;
    public String drname,current;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prev = (ImageView) findViewById(R.id.previmg);
        now = (ImageView) findViewById(R.id.token);
        next = (ImageView) findViewById(R.id.nextimg);
        display = (TextView) findViewById(R.id.textView2);
        ptname = (TextView) findViewById(R.id.textView3);
        bottom = (TextView) findViewById(R.id.tokennum);
        docname = (TextView) findViewById(R.id.textView);

      //  Connect runner = new Connect();
      //  runner.execute();

The setOnClickListener method:

    prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            //  String sleepTime = time.getText().toString();

        }
    });
    now.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            display.setText(tokenh);
            ConnectNow nw = new ConnectNow();
            nw.execute();

            Intent i = new Intent(getApplicationContext(), StatusUpdate.class);
            i.putExtra("patientname", pname);
            i.putExtra("tokenno", tokenh);
            i.putExtra("depvisitid", depvisitid);

            startActivity(i);




        }

    });

    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Connect runner = new Connect();
            runner.execute();

        }
    });




}

The onBackPressed:

public void onBackPressed() {
    // TODO Auto-generated method stub
    //  super.onBackPressed();
    // finish();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    finish();
}

class Connect extends AsyncTask<String, String, String> {


    @Override
    protected String doInBackground(String... params) {
        try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();

        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
        String username = "aaa";
        String password = "sssss";
        Connection DbConn = null;
        try {
            DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
            Log.i("Connection", "openjjj");

        } catch (SQLException e1) {

            e1.printStackTrace();
        }

        Log.w("Connection", "open");
        Statement stmt = null;
        try {
            stmt = DbConn.createStatement();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        ResultSet reset1 = null;


        try {
            reset1 = stmt.executeQuery(" select a.TOKENNO,b.FNAME,a.TOKENSTATUS,e.EMPFNAME,a.DEPVISITID from DEPTVISIT a,PATIENT_MASTER b,APP_EMPLOYEE e  where a.PID=b.PID and (a.TOKENSTATUS='O' or a.TOKENSTATUS='S' ) and e.EMPID=a.EMPID and a.EMPID=2 and CONVERT(date,a.OPDATE)='2016-05-09' order by TOKENNO desc;");
            while (reset1.next()) {

                tokenh = reset1.getString("TOKENNO");
                pname = reset1.getString("FNAME");
                drname = reset1.getString("EMPFNAME");
                depvisitid= reset1.getString("DEPVISITID");
            }


        } catch (SQLException e1) {
            e1.printStackTrace();
        }


        try {
            DbConn.close();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        return tokenh;

    }

    protected void onPostExecute(String result) {


        bottom.setText(tokenh);
        ptname.setText(pname);
        docname.setText(drname);


    }




}

The connect now class:

class ConnectNow extends AsyncTask<String, String, Boolean> {


    @Override
    protected Boolean doInBackground(String... params) {
       try {
            Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();

        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
        String username = "aaaaa";
        String password = "ssssss";
        Connection DbConn = null;
        try {
            DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
            Log.i("Connection", "openjjj****");

        } catch (SQLException e1) {

            e1.printStackTrace();
        }

        Log.w("Connection", "open****");
        Statement stmt = null;
        try {
            stmt = DbConn.createStatement();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }



        try {
            int noOfRows = stmt.executeUpdate(" update DEPTVISIT set TOKENSTATUS='S' where DEPVISITID=" + depvisitid);
            if (noOfRows > 0) {
                status = true;
                System.out.println("status updated to S");
            }



        } catch (SQLException e1) {
            e1.printStackTrace();
        }


        try {
            DbConn.close();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        return status;

  }
 protected void onPostExecute(Boolean result) {


        bottom.setText(tokenh);
        ptname.setText(pnamenext);
        docname.setText(drname);


    }


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {

        Intent settings=new Intent(getApplicationContext(),Settings.class);
        startActivity(settings);
    }

    return super.onOptionsItemSelected(item);
}

}

SECOND ACTIVITY StatusUdate.java:

public class StatusUpdate extends Activity {
    public String tokenstatN, tokenstatY;


    Button visited, notvisited;
    String pname,tokennum,depvisitid;
    TextView patnam,tknum;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.statusupdate);
        visited = (Button) findViewById(R.id.button);
        notvisited = (Button) findViewById(R.id.button2);
        patnam= (TextView) findViewById(R.id.textView4);
        tknum= (TextView) findViewById(R.id.textView5);
        Bundle extras = getIntent().getExtras();
        pname = extras.getString("patientname");
        tokennum = extras.getString("tokenno");
        depvisitid = extras.getString("depvisitid");

        patnam.setText(pname);
        tknum.setText(tokennum);

        visited.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Visit vt= new Visit();
                vt.execute();

                Intent i = new Intent(getApplicationContext(), MainActivity.class);

                startActivity(i);
            }
        });
        notvisited.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               NotVisit n = new NotVisit();
                n.execute();

                Intent i = new Intent(getApplicationContext(), MainActivity.class);

                startActivity(i);
            }
        });
    }

The NotVisit class:

   class NotVisit extends AsyncTask<String, String, Boolean> {

        boolean status = false;

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();

            } catch (InstantiationException e1) {
                e1.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }
            String username = "aaaaa";
            String password = "sssss";
            Connection DbConn = null;
            try {
                DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://xxx.xxx.x.x:1433/DATABASENAME;user=" + username + ";password=" + password);
                Log.i("Connection", "openhhhh");

            } catch (SQLException e1) {

                e1.printStackTrace();
            }

            Log.w("Connection", "openlll");
            Statement stmt = null;
            try {
                stmt = DbConn.createStatement();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }


            try {

                int noOfRows = stmt.executeUpdate("  update DEPTVISIT set TOKENSTATUS='N' where DEPVISITID=" + depvisitid);
                if (noOfRows > 0) {
                    status = true;
                }


                try {
                    DbConn.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }


            } catch (SQLException e) {
                e.printStackTrace();
            }
            Log.d("status", String.valueOf(status));
            return status;

        }
    }

You can store the retrieved text in a static field of your activity class, but it's better save and restore it on activity recreation.
So modify your activity like:

@Override
public void onCreate(Bundle b) {
  // activity initialization
  // textView = ... 
  if (b != null) {
    textView.setText(b.getString("dbtext"));
  }
}

and

@Override
protected void onSaveInstanceState(Bundle b) {
   super.onSaveInstanceState(b);
   b.putString("dbtext", textView.getText());
}

Whenever you wish to go to previous screen, Always finish the Activity that is on top. Here in your case, You are always creating new instance of MainActivity and this is the reason for getting null when you go back. Try using this in your StatusUpdate.java .

visited.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Visit vt= new Visit();
            vt.execute();

            StatusUpdate.this.finish();
        }
});

 notvisited.setOnClickListener(new View.OnClickListener() {  
 @Override
        public void onClick(View v) {

           NotVisit n = new NotVisit();
           n.execute();

           StatusUpdate.this.finish();
        }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM