Can i skip the first activity? - android

my code is
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
Log.d("response", "starting city connection");
HttpPost httppost = new HttpPost(
"http://10.0.2.2/wic3/wic2/mobile/verifyUser");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
sessionResponse = SignUpActivity.httpclient.execute(httppost,
responseHandler);
Log.d("session response", "" + sessionResponse);
if (sessionResponse.equals("true")) {
Intent intent = new Intent(SignUpActivity.this,
FeedListViewActivity.class);
startActivity(intent);
}
} catch (Exception e) {
Log.e("error", "Error in http connection" + e.toString());
}
.............
my question is can i skip the 1st activity(or screen) and directly load some other screen depending on any condition???my intention was to load the home page (skip the login page) if a session already exists....in my case the sessionResponse is true but i still get the login page

Instead of the following code
Intent intent = new Intent(SignUpActivity.this,FeedListViewActivity.class);
startActivity(intent);
Simply put setContentView(). setContentView() is the method that displays the screen in android to the User Interface. If you dont call this method then nothing will be displayed. You will see only a blank screen. Modify your above code as follows
if (sessionResponse.equals("true"))
setContentView(R.layout.screen1);
else
setContentView(R.layout.screen2);

Yes you can Don't set View using setContentView and check the condition and nevigate to the desired activity and finish your first activity. But if your Condition is false you have to handle that too otherwise nothing will be displayed.

Related

Using getIntent() in onCreate() prevents ui from loading... why?

I have an activity that list authorized users, and I'm using getIntent() in my activity's onCreate() method to check if the activity should display a pre-filled add user dialog when it loads. Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_auth_manager);
try{ //check if the activity was launched with a prefill intent
Intent intent = getIntent();
int id = (intent.getIntExtra("notification_id",0));
NotificationUtils notificationUtils = new NotificationUtils();
notificationUtils.hideNotification(this,id);
if (intent.getBooleanExtra("isPrefill",false)){
String preFill = intent.getStringExtra("sender");
showAddUserDialog(preFill);
}
}catch (Exception ignore){} //exception swallowed means no dialog
refreshList(); //loads the list of users into the main listview of the activity
}
My problem is that the call to refreshList() is not resulting in the list being refreshed. I tried putting it before the try block as well, and either way it won't work. I tested with the try block commented out though, and that does work, but then I lose the functionality.
Here is the code of the refreshList() method, in case it's necessary:
private void refreshList(){
SharedPreferences sharedPrefs = getSharedPreferences("users",0);
LinearLayout ll = findViewById(R.id.ll);
ll.removeAllViews();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
for (String sender : sharedPrefs.getAll().keySet()) {
CheckBox checkBox = new CheckBox(this);
checkBox.setText(getContactDisplayName(sender));
checkBox.setTag(sender);
try{
checkBox.setChecked(sharedPrefs.getBoolean(sender,false));
}catch (Exception e){
checkBox.setChecked(false);
}
checkBox.setLayoutParams(layoutParams);
checkBox.setOnClickListener(v -> {
try {
sharedPrefs.edit().putBoolean(sender, checkBox.isChecked()).apply();
}catch (Exception e){
Toast.makeText(this, "Preference not updated.\n"+e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
checkBox.setOnLongClickListener(v -> {
showPopupMenu(v);
return false;
});
ll.addView(checkBox);
}
}
Why does the try block prevent the UI from refreshing, and how can I acheive the functionality I am looking for?
If you intend to run the refreshList method regardless if there is an exception or not you can try using the finally block which would run the code regardless of the exception.

Android: Unable to swap activity and close app when clicking button

I have an activity (let us call "ResultActivity") which receives some results from another activity ("AuditTest"), and there will be two buttons for user:
First button: let user to send the above-mentioned results to the server via connecting to a PHP webpage, and then go back to the main menu (so called "MainActivity")
Second button: let user to send the results to the server by ASyncTask, then ASyncTask will finish
For going back to the main menu, I have tried to use Intent, setClass, startactivity and finish. It could manage to go back to main menu, but this ResultActivity won't finish. Once you press back button on the phone, startActivity will close and that ResultActivity comes out again.
And for quitting the app, I also tried to use simply finish() method to achieve this, but still have no luck.
So here is the code for ResultActivity, and I also included comments to briefly illustrate operations in the app
public class ResultActivity extends AppCompatActivity
{
TextView result_showResultLbl;
Button result_retry,result_leaveBtn;
TextView result_noticeLbl;
boolean fail = false;
char PF = ' ';
final int BUTTON_RETRY=1;
final int BUTTON_LEAVE=2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
//Summary: Just initializing all widgets, get back all elements
//from previous activity and show result to user.
........
........
//setting up onClickListeners for two buttons (result_retry and
result_leavebtn. So the ASyncTask is called SendData.
result_retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//send result to server
SendData s = new
SendData(PF,FArecord,questionAnswers,BUTTON_RETRY);
s.execute();
}
});
result_leaveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendData s = new
SendData(PF,FArecord,questionAnswers,BUTTON_LEAVE);
s.execute();
}
});
}
//ASyncTask class SendData
private class SendData extends AsyncTask<String, String ,String>
{
.......//variables, not mentioned here
//parameters are data from previous activity and which button that user clicked.
SendData(..........)
{
.........
}
#Override
protected String doInBackground(String... strings)
{
//doInBackground of SendData will get all data sent from
//previous activity, then use HttpURLConnection to send out the data and get back the result.
...............//get all data from previous activity
//send php request
URL dbServerURL = new URL(URLAddr);
HttpURLConnection conn = (HttpURLConnection) dbServerURL.openConnection();
Log.v("ResultActivity","URL = "+URLAddr);//for debug
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
OutputStream out = conn.getOutputStream();
//concat the information fields and then send out the data
parameters = ....;// parameters is a concatenated string to carry the data.
out.write(parameters.getBytes());
Log.v("ResultActivity","Trying to send parameter: "+parameters);
out.flush();
out.close();//finish sending out
//data request is successful
InputStream is = conn.getInputStream();
String response = FacilityAuditTest.convertStreamToString(is);
if (response.contentEquals("Error"))
{
//error occurred
Log.v("ResultActivity","Received String: "+response);
} else
{
//get JSON object if no error
JSONObject json = new JSONObject(response);
success = json.getInt("success");
Log.v("ResultActivity","Success= "+success);
Log.v("ResultActivity","Record sent successfully");
}
is.close();
conn.disconnect();
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
if (success == 1)
{
//I use runOnUiThread() to detect which button the user has clicked, then swap activity or close the app.
runOnUiThread(new Runnable() {
#Override
public void run() {
if (clickedButtonType == BUTTON_RETRY)
{
//if user clicked retry button before, show a success message and then go back to information entry page
Toast.makeText(ResultActivity.this,R.string.result_sendSuccess,Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(ResultActivity.this,AuditorInf.class);
startActivity(i);
finish();
}
if (clickedButtonType == BUTTON_LEAVE)
{
Toast.makeText(ResultActivity.this,R.string.result_sendSuccess,Toast.LENGTH_SHORT).show();
//I tried to use android.os.Process.killProcess to kill app, but the app still restart and show this ResultActivity after running killProcess. android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
//finish();
}
}
});
} else
{
//just show fail to transmit message, but the action is similar to (success == 1)
}
}
}
}
As what I have added in the comments of the code, the app won't switch to main menu and close current activity. It also cannot close the app by calling finish. I can give more detail code if you need. Thank you.

Android, using Zxing into a webview, into back button, shows blank activity

Okay, so I have an app that scans qr codes, verifies that it is a qr_code, and then opens the link stored in the code. What I need help with is where to go from here as far as the back button. When you push the back button it goes back to the app, which is fine, but it's a white screen (probably since there is nothing else that needs to be done after scan and webview creation). I've looked at the android activity states and onResume, onStop, onPause, etc are triggered because of both the zxing barcode scanner and the new web activity. I figured I could just set it up to where I start a new intent back to home page but then that wipes out the web activity.
Intent goHome = new Intent(this, EActivity.class);
if (scannedResult != null && resultCode == RESULT_OK)
{
if (scannedResult.getFormatName().equals("QR_CODE"))
{
Uri url = Uri.parse(scannedResult.getContents());
WebView webview = new WebView(this);
setContentView(webview);
Intent orrweb = new Intent(Intent.ACTION_VIEW, url);
startActivity(orrweb);
}
else
{
Toast.makeText(NewScannerActivity.this, "Incorrect Barcode Type. Please retry with QR Code.", Toast.LENGTH_LONG).show();
this.startActivity(goHome);
}
}
else
{
this.startActivity(goHome);
}
}
catch (Exception e)
{
Log.i("GMR", "error: " + e.toString());
}

Simple Android Design Flow Inquiry for Login Activity and Main Activity

I am wondering about a design question about android. I often have two activities to separate my login and my main activity (side note: main activity is usually a navigation drawer). I flow is usually like this:
I was thinking of changing this to:
What do people think?
My issues:
Which Activity really should be in the launcher drawer?
I store authentication information whether they are logged in just in the SharedPreferences. This is how checkLogin() is performed and where data is stored after a successful attemptLogin().
I don't want the user to be able to press the back button to access the Login. Only pressing a designated "Log out" Button should bring them back to the login Activity.
This is an example of some code for the parts
Part A:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkLogin();
uprintDatabaseHelper = new uprintHelper(this);
uprintDatabaseHelper.getWritableDatabase();
setContentView(R.layout.activity_main_nav_drawer);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
Part B:
SharedPreferences sharedPreferences = getSharedPreferences("UserData",MODE_PRIVATE);
if(!sharedPreferences.getBoolean("LOGGED_IN", false)) {
if(!sharedPreferences.getBoolean("DATABASE_EXIST", false)) {
uprintDatabaseHelper = new uprintHelper(this);
uprintDatabaseHelper.getWritableDatabase();
}
Intent intent = new Intent(this,LoginActivity.class);
startActivity(intent);
}
Part C:
final boolean attemptLogin(String user, HttpClient client) {
HttpPost post = new HttpPost(getString(R.string.authorization_url));
String body;
body = "email=" + user;
post.setHeader("Content-type","application/x-www-form-urlencoded");
try {
post.setEntity(new StringEntity(body,"UTF-8"));
try {
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
try {
JSONObject finalResult = new JSONObject(json);
return finalResult.getBoolean("success");
} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}
Part D:
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("LOGGED_IN", true);
editor.commit();
finish();
I'd recommend the following order.
Start your LoginActivity first
Check whether the user is logged in
Not logged in? Proceed to 3.)
Logged in? Proceed to 4.)
Prompt your user to login. Go back to 2.)
Call finish() on your LoginActivity and start your MainAcitivty
Calling finish() will close the LoginActivity and thus make it impossible for the user to get back to it via backpress.
You can implement the log out function vice versa - call finish() on your MainActivity and start your LoginActivity again.

Why can't I fetch the JSONArray from the web

I want to fetch the JSONArray from the internet and show it in the logcat so I use
Log.e("result ", result);
But it seems fail because I can't find any of the JSONArraay in the logcat
Here's my code and I hope you can have a look and tell me what's wrong ?
I know some of you are using BufferReader to read the text from internet
but I guess my way should also be OK
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnParse;
ListView listResult;
btnParse = (Button) findViewById(R.id.btn_parse);
listResult = (ListView) findViewById(R.id.list_result);
btnParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
JSONArray trial = getJSONData();
}
});
}
private JSONArray getJSONData() {
String url = "http://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindAllTypeJ";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
try {
HttpResponse httpresponse = httpClient.execute(httpget);
String result = EntityUtils.toString(httpresponse.getEntity());
Log.e("result ", result);
JSONArray jsonarr = new JSONArray(result);
return jsonarr;
} catch (Exception err) {
return null;
}
}
#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;
}
}
Android does not allow networking on the UI thread. Therefore, when you call HttpResponse httpresponse = httpClient.execute(httpget); It is throwing an android.os.NetworkOnMainThreadException exception. It would be more useful for you to call Log.e("error",err.printStackTrace())in the catch block rather than returning null as this error would be revealed in the logcat. You need to move the code int the try block to another thread. I recommend using an AsyncTask. See this link for more details on this. The basics about AsyncTask: it is a class that abstracts the use of a thread and a handler away from the developer. If you are familiar with threads and handlers you can implement your own solution (not an async task) to avoid having to conform to the asynctask frame work.
Ever since Android 3.0, StrictMode has been enabled by default. What it does it prohibit developers from doing lazy things such as running network code on the UI thread. It forces you to run such code asynchronously so that the application doesn't hang/pause and user interaction remains uninterrupted. You can turn that off so that you don't need to use an AsyncTask/Handler/Volley/whatever. It's a bad way to handle it, but here's one way to do it (don't do this):
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); // Put these two lines before you execute your HTTTP request....
Do this instead:
Use Volley, here's a quick tutorial. Also, a Google Talk about it.

Categories

Resources