Save user variables in sharedpreference and connect class with MainActivity? - java

I have to hit a service and if the response came true than I have to verify the user & save the user entered variables in shared preference. my url is: http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id and the response it is giving is {"success":true}. For this I have made a class and declared a static method. Inside the static method I have to do parsing.
my class:
public class InitializeSDK {
/*String json = "";
URL url;
HttpURLConnection connection = null;*/
public static void init(final Context ctx, int offerwall_id, String offerwall_public_key) {
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... arg0) {
//TODO: add code to read http request and store the json data in json variable
String json = "";
//URL url;
HttpURLConnection connection = null;
InputStream is = null;
final String MyPREFERENCES = "MyPrefs" ;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id");//YOUR URL
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONObject jObj = new JSONObject(json);
boolean isSuccess = jObj.getBoolean("success");
System.out.println("success : " + isSuccess);
// SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
/*SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Context ctx);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("isSuccess",isSuccess);
editor.commit();*/
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/* JSONObject jsonObject = new JSONObject(json);
boolean state = jsonObject.getBoolean("success");*/
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}.execute();
}
my MainActivity is:
public class MainActivity extends AppCompatActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
}
How to save the variables in sharedpreference and connect the class with MainActivity? Please help

Do the below changes.
Step1: Change Return type Void to Boolean
new AsyncTask<Void, Void, Boolean>() {}
Step2: In doInBackground return "isSuccess"
Step3: Change the onPostExecute() below
protected void onPostExecute(boolean result) {
super.onPostExecute(result);
if(result){
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putInt"offerwall_id", offerwall_id)
.putString("offerwall_public_key",offerwall_public_key)
.apply();
}
}
Step4: Call from MainActivity
public class MainActivity extends AppCompatActivity {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitializeSDK.init(this,val1,val2);
}
}
}

Make InitializeSDK class extend AsyncTask
like
public class InitializeSDK extends AsyncTask<Void, Integer, String> {
Context ctx;
int offerwall_id;
String offerwall_public_key;
public InitializeSDK (Context ctx, int offerwall_id, String offerwall_public_key){
this.ctx = ctx;
this.offerwall_id = offerwall_id;
this.offerwall_public_key = offerwall_public_key;
}
//rest of the asynctask code
}
and in your MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int id = //your id;
String offerwall_public_key = //your key;
new IntializeSDK(this,id,offerwall_public_key).execute();
}
Your shared preference code is correct, use it in OnPostExecute

Related

I got error Android JSON parsing Retrieve from URL

I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));

Asking the user for a URL to receive a JSON

Just as a practicing exercise i'm trying to make an app that fetches a JSON from a URL.
I found the following code in other thread here in stackoverflow and it works just fine. My problem is that the URL is hardcoded, and i need it to be an input by the user. What should i change/add?
public class MainActivity extends AppCompatActivity {
Button btnHit;
TextView txtJson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute("Url address here");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response..... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
This is the thread where i got that code from:
Get JSON Data from URL Using Android?
Create a constructor in your async Task
private class JSONTask extends AsyncTask<String, String, String> {
String url;
public JSONTask(String url){
this.url=url;
}
use the url string in place of params[0]
And wherever you call your async task do it like this
new JSONTask(textView.getText()).execute()
This should solve it.
Else you can directly use the do in background variable params.
So the problem is that you are using a TextView. TextView does not recieve inputs.
EditText does.
Make these Changes:
TextView txtJson;
In your OnCreate change this:
txtJson = (EditText) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonTask().execute(txtJson.getText());
}
});
Now in your xml file change the Button to EditText.
Hope this helps.

Unable to access string from class

I want to show string from another string in my MainActivity, but the string is getting printed in console. Here is my code:
public class MainActivity extends AppCompatActivity {
Button start;
public TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText= (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetrieveFeedTask click1 = new RetrieveFeedTask();
click1.execute();
showText.setText(click1.getString());
}
});
}
}
And the class:
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
static final String API_URL = "http://numbersapi.com/random/trivia?json";
private Exception exception;
public String finalString;
protected void onPreExecute() { }
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL );
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((finalString = bufferedReader.readLine()) != null) {
stringBuilder.append(finalString).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
public String getString() {
return this.finalString;
}
}
You require the finalString before it's populated with your data. the onPostExecute is executed after the doInBackground so you should pass your text view to your task and set it's value in the onPostExecute
public TextView showText;
public RetrieveFeedTask(TextView showText) { this.showText = showText; }
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
showText.setText(finalString ); // add this
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
The problem is that showText.setText(click1.getString()); of your activity is called earlier than finalString = object.getString("text"); of your task.
Solution:
Create an interface:
public interface DataCallback {
void onNewData(String data);
}
and implement it in your activity:
public class MainActivity extends ... implements DataCallback
public void onNewData(String data) {
showText.setText(data);
}
Pass the interface to your asynctask when you create it:
RetrieveFeedTask click1 = new RetrieveFeedTask(this);
Call the interface inside the task in onPostExecute() to notify the activity that there is new data:
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
callback.onNewData(finalString);

How do i set an ImageView to show an image from an image url?

When i try to set the ImageView variable "profilePicture" to the bitmap from the image url, it doesn't show anything. Please help!! I am getting the image url link from my database. This is what that async task result is.
System.out: Resulted Value: {"image":"http://www.myegotest.com/PhotoUpload/uploads/5.png"}
Here is my Java code
public class HomeActivity extends AppCompatActivity {
//View item variables
private TextView loggedUsersName;
private TextView successMessage;
private Button logoutButton;
private ImageView profilePicture;
//Other variables
private String getProfileImageURL = "http://www.myegotest.com/PhotoUpload/getAllImages.php";
private String firstName;
private String lastName;
private String email;
private Bitmap profilePicBitmap;
LocalDataBase mLocalDataBase;
Boolean imageSet;
Drawable d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//Get logged in user from LocalDataBase and
//Destroy Activity if user is logged out
mLocalDataBase = new LocalDataBase(this);
User user = mLocalDataBase.getLoggedInUserInfo();
if(!mLocalDataBase.userIsLoggedIn()){
HomeActivity.this.finish();
}
//Initialize view item variables.
loggedUsersName = (TextView)findViewById(R.id.login_user);
successMessage = (TextView)findViewById(R.id.message);
logoutButton = (Button)findViewById(R.id.logoutButton);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
//Get intent and values from the intent started this activity and
//Get loggedIn user values from the LocalDataBase .
Intent intent = getIntent();
String message = intent.getStringExtra("MESSAGE");
firstName = user.mFirstName;
lastName = user.mLastName;
email = user.mEmail;
//Set view values to equal values sent from intent.
loggedUsersName.setText(firstName + " " + lastName);
successMessage.setText(message);
netAsync();
}
//Call this method to execute the Async Task
private void netAsync() {
new NetCheck().execute();
}
//Async Task to check whether internet connection is working.
private class NetCheck extends AsyncTask {
private ProgressDialog mDialog;
//Create and show progress dialog box so user knows the app is trying to login.
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(HomeActivity.this);
mDialog.setTitle("Logging In...");
mDialog.setMessage("connecting to server");
mDialog.setIndeterminate(false);
mDialog.setCancelable(true);
mDialog.show();
}
//Gets current device state and checks for working internet connection by trying Google.
#Override
protected Boolean doInBackground(Object[] objects) {
ConnectivityManager mCM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetInfo = mCM.getActiveNetworkInfo();
if ( (myNetInfo != null) && (myNetInfo.isConnected())){
try {
URL url = new URL("http://google.com");
HttpURLConnection myConnection = (HttpURLConnection) url.openConnection();
myConnection.setConnectTimeout(3000);
myConnection.connect();
if (myConnection.getResponseCode() == 200){
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
//If successful internet connection start AsyncTask to register user info on server
if(o.equals(true)){
mDialog.dismiss();
new RegisterUser().execute(getProfileImageURL, email);
} else {
mDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error in Network Connection", Toast.LENGTH_SHORT).show();
}
}
}
//AsyncTask to get profile pic url string from server
private class RegisterUser extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection LucasHttpURLConnection = (HttpURLConnection)url.openConnection();
LucasHttpURLConnection.setRequestMethod("POST");
LucasHttpURLConnection.setDoOutput(true);
LucasHttpURLConnection.setDoInput(true);
LucasHttpURLConnection.setConnectTimeout(1000 * 6);
LucasHttpURLConnection.setReadTimeout(1000 * 6);
//OutputStream to get response
OutputStream outputStream = LucasHttpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data =
URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(params[1], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//InputStream to get response
InputStream IS = LucasHttpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String json;
while( (json = bufferedReader.readLine()) != null){
response.append(json + "\n");
break;
}
bufferedReader.close();
IS.close();
LucasHttpURLConnection.disconnect();
return response.toString().trim();
} catch (MalformedInputException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Print server AsyncTask response
System.out.println("Resulted Value: " + result);
//If null Response
if (result != null && !result.equals("")) {
String profilepic = returnParsedJsonObject(result);
new GetBitmapImageFromUrl().execute(profilepic);
profilePicture = (ImageView)findViewById(R.id.profile_Picture);
profilePicture.setImageBitmap(profilePicBitmap);
} else {
Toast.makeText(HomeActivity.this, "Sorry, there was an error. Please try again", Toast.LENGTH_LONG).show();
}
}
//Method to parse json result and get the value of the key "image"
private String returnParsedJsonObject(String result){
JSONObject resultObject = null;
String returnedResult = "";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("image");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
class GetBitmapImageFromUrl extends AsyncTask<String,Void,Bitmap>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... params) {
try {
profilePicBitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
If you are seeing background white instead image. Out of memory exception by using bitmap.
You could use
Option 1
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
profile_photo.setImageBitmap(mIcon_val);
Picasso
Picasso.with(context).load("http://www.myegotest.com/PhotoUpload/uploads/5.png").into(profilePicture);
I would suggest to go with Piccasso. Since it will handle everything.

Splash Screen activity runs twice

So basically this is the class that starts at the launch of the app and it shows a splashscreen while getting a serverList from a server, once it has the list, it starts the next activity, the problem is that this activity seems to be getting called twice before the next activity is started, what could be causing that?
public class SplashScreen extends Activity {
public static DefaultHttpClient httpClient;
private String resp;
static String res;
private String errorMsg;
final Context context = this;
public static String cookieValue;
public static Cookie cookie;
String now_playing, earned;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
String Wlcclient = "Yes";
String ClientType = "Android";
String Version = "0.103";
new PrefetchData().execute(Wlcclient,ClientType,Version);
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
SplashScreen.httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = SplashScreen.httpClient.execute(request);
List<Cookie> cookies = SplashScreen.httpClient.getCookieStore().getCookies();
cookie = cookies.get(0);
cookieValue = "ASPSESSIONIDCQTCRACT=" + cookie.getValue();
System.out.println("COOK" + cookieValue);
Header[] headers = response.getAllHeaders();
System.out.println("length" + headers.length);
for (int i=0; i < headers.length; i++) {
Header h = headers[i];
System.out.println( "Header names: "+h.getName());
System.out.println( "Header Value: "+h.getValue());
}
CookieManager cookieManager = CookieManager.getInstance();
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class PrefetchData extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// before making http calls
}
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("WlcClient",
params[0])); // params[0] contains the first value that you have passed and params[1] second value.
postParameters.add(new BasicNameValuePair("ClientType",
params[1]));
postParameters.add(new BasicNameValuePair("Version",
params[2]));
String response = null;
try {
response =
executeHttpPost(server,
postParameters);
res = response.toString();
resp = res.replaceAll("\\s+", "");
System.out.println(res);
//resultt =res;
return res;
} catch (Exception e) {
e.printStackTrace();
errorMsg = e.getMessage();
}
return res;
} // end of doInBackground
protected void onPostExecute(String result) {
super.onPostExecute(result);
// After completing http call
// will close this activity and lauch main activity
Intent i = new Intent(SplashScreen.this, LoginLayout.class);
startActivity(i);
// close this activity
finish();
}
}
}
inside onCreate() of SplashScreenActivity
I've replaced finish() with onDestroy() after startActivity(intent)
public class SplashScreenActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable(){
#Override
public void run() {
Intent intent;
intent = new Intent(SplashScreenActivity.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
//here we call the onDestory instead of finish()
onDestroy();
}
}, 1000);
}
}
worked for me

Categories

Resources